BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / google_calendar / parse.rs

parse.rs

parse.rs 18.3 KiB Download Raw
1use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
2use serde_json::Value;
3
4use crate::calendar::{
5 AttendeeResponseCounts, CalendarEvent, CalendarSource, EventAttendee, ResponseType, ShowAs,
6 strip_html, truncate_preview,
7};
8
9pub fn parse_calendar_list(body: &Value) -> Vec<(String, String, bool)> {
10 body.get("items")
11 .and_then(Value::as_array)
12 .into_iter()
13 .flatten()
14 .filter_map(|entry| {
15 Some((
16 entry.get("id")?.as_str()?.to_owned(),
17 entry
18 .get("summary")
19 .and_then(Value::as_str)
20 .unwrap_or("Calendar")
21 .to_owned(),
22 entry
23 .get("primary")
24 .and_then(Value::as_bool)
25 .unwrap_or(false),
26 ))
27 })
28 .collect()
29}
30
31pub fn parse_google_events(
32 body: &Value,
33 account_id: Option<&str>,
34 calendar_id: Option<&str>,
35) -> Vec<CalendarEvent> {
36 let defaults = default_reminder_minutes(body);
37 let mut events: Vec<CalendarEvent> = body
38 .get("items")
39 .and_then(Value::as_array)
40 .into_iter()
41 .flatten()
42 .filter_map(|entry| parse_event(entry, account_id, calendar_id, &defaults))
43 .collect();
44 events.sort_by_key(|event| (event.start, event.end));
45 events
46}
47
48fn parse_event(
49 entry: &Value,
50 account_id: Option<&str>,
51 calendar_id: Option<&str>,
52 default_reminders: &[u32],
53) -> Option<CalendarEvent> {
54 if entry.get("status").and_then(Value::as_str) == Some("cancelled") {
55 // Still show cancelled when times exist.
56 }
57 let object_id = entry.get("id")?.as_str()?.to_owned();
58 let (start, all_day) = event_instant(entry.get("start")?)?;
59 let (end, _) = event_instant(entry.get("end")?)?;
60 let join_url = conference_join_url(entry)
61 .or_else(|| text(entry, "location").filter(|value| value.contains("teams.microsoft.com")))
62 .or_else(|| {
63 text(entry, "description").and_then(|description| {
64 description
65 .split_whitespace()
66 .find(|token| token.contains("teams.microsoft.com"))
67 .map(str::to_owned)
68 })
69 });
70 let location = text(entry, "location").filter(|value| !value.contains("teams.microsoft.com"));
71 let description = text(entry, "description");
72 let body_preview = description
73 .as_ref()
74 .map(|value| truncate_preview(&strip_html(value)))
75 .filter(|value| !value.is_empty());
76 let body_html = description
77 .as_ref()
78 .filter(|value| !value.trim().is_empty())
79 .map(|value| description_html(value));
80 let series = entry
81 .get("recurrence")
82 .and_then(Value::as_array)
83 .is_some_and(|items| !items.is_empty())
84 || entry.get("recurringEventId").is_some();
85 Some(CalendarEvent {
86 object_id,
87 subject: text(entry, "summary").unwrap_or_default(),
88 start,
89 end,
90 all_day,
91 cancelled: entry.get("status").and_then(Value::as_str) == Some("cancelled"),
92 online: join_url.is_some(),
93 join_url,
94 thread_id: None,
95 organizer_name: entry
96 .pointer("/organizer/displayName")
97 .and_then(Value::as_str)
98 .map(str::to_owned),
99 organizer_address: entry
100 .pointer("/organizer/email")
101 .and_then(Value::as_str)
102 .map(str::to_owned),
103 ical_uid: text(entry, "iCalUID"),
104 response: response_status(entry),
105 show_as: ShowAs::Busy,
106 dial_in: None,
107 source: CalendarSource::Google,
108 account_id: account_id.map(str::to_owned),
109 calendar_id: calendar_id.map(str::to_owned),
110 sources: vec![CalendarSource::Google],
111 location,
112 body_preview,
113 body_html,
114 series,
115 series_master_id: text(entry, "recurringEventId"),
116 response_counts: google_response_counts(entry),
117 attendees: google_attendees(entry),
118 reminders: google_reminders(entry, default_reminders),
119 source_link: google_source_link(entry),
120 web_link: text(entry, "htmlLink"),
121 calendar_name: None,
122 })
123}
124
125/// Google descriptions become escaped HTML with http(s) links and line breaks.
126/// Existing markup is flattened first so untrusted schemes (e.g. `javascript:`)
127/// cannot become clickable `href`s through the message HTML pipeline.
128pub fn description_html(text: &str) -> String {
129 let plain = if looks_like_html(text) {
130 strip_html(text)
131 } else {
132 text.to_owned()
133 };
134 let escaped = plain
135 .replace('&', "&amp;")
136 .replace('<', "&lt;")
137 .replace('>', "&gt;");
138 let with_links = linkify_escaped(&escaped);
139 with_links
140 .replace("\r\n", "\n")
141 .replace('\r', "\n")
142 .replace('\n', "<br>")
143}
144
145fn looks_like_html(text: &str) -> bool {
146 let lower = text.to_ascii_lowercase();
147 lower.contains('<')
148 && (lower.contains("<br")
149 || lower.contains("<p")
150 || lower.contains("<div")
151 || lower.contains("<a ")
152 || lower.contains("<b>")
153 || lower.contains("<i>")
154 || lower.contains("<ul")
155 || lower.contains("<ol")
156 || lower.contains("<li")
157 || lower.contains("<span"))
158}
159
160fn linkify_escaped(text: &str) -> String {
161 let mut out = String::with_capacity(text.len());
162 let mut rest = text;
163 while !rest.is_empty() {
164 let next_https = rest.find("https://");
165 let next_http = rest.find("http://");
166 let (at, scheme) = match (next_https, next_http) {
167 (Some(a), Some(b)) if a <= b => (a, "https://"),
168 (Some(a), None) => (a, "https://"),
169 (None, Some(b)) => (b, "http://"),
170 (None, None) => {
171 out.push_str(rest);
172 break;
173 }
174 (Some(_), Some(b)) => (b, "http://"),
175 };
176 out.push_str(&rest[..at]);
177 rest = &rest[at..];
178 let after = &rest[scheme.len()..];
179 let end = after
180 .find(|character: char| {
181 character.is_whitespace()
182 || matches!(character, '<' | '>' | '"' | '\'' | ')' | ']' | '}')
183 })
184 .unwrap_or(after.len());
185 let mut url = format!("{}{}", scheme, &after[..end]);
186 while url
187 .chars()
188 .last()
189 .is_some_and(|character| matches!(character, '.' | ',' | ';' | ':' | '!'))
190 {
191 url.pop();
192 }
193 let href = url.replace('"', "&quot;");
194 out.push_str(&format!(r#"<a href="{href}">{url}</a>"#));
195 rest = &rest[url.len()..];
196 }
197 out
198}
199
200fn default_reminder_minutes(body: &Value) -> Vec<u32> {
201 reminder_minutes_from(body.get("defaultReminders"))
202}
203
204fn google_reminders(entry: &Value, defaults: &[u32]) -> Vec<u32> {
205 let reminders = entry.get("reminders");
206 if reminders
207 .and_then(|value| value.get("overrides"))
208 .and_then(Value::as_array)
209 .is_some_and(|items| !items.is_empty())
210 {
211 return reminder_minutes_from(reminders.and_then(|value| value.get("overrides")));
212 }
213 if reminders
214 .and_then(|value| value.get("useDefault"))
215 .and_then(Value::as_bool)
216 == Some(true)
217 {
218 return defaults.to_vec();
219 }
220 Vec::new()
221}
222
223fn reminder_minutes_from(list: Option<&Value>) -> Vec<u32> {
224 let Some(items) = list.and_then(Value::as_array) else {
225 return Vec::new();
226 };
227 let mut minutes: Vec<u32> = items
228 .iter()
229 .filter_map(|item| {
230 let method = item.get("method").and_then(Value::as_str).unwrap_or("popup");
231 if method != "popup" && method != "email" {
232 return None;
233 }
234 item.get("minutes")
235 .and_then(Value::as_u64)
236 .map(|value| value as u32)
237 })
238 .collect();
239 minutes.sort_unstable();
240 minutes.dedup();
241 minutes
242}
243
244fn google_source_link(entry: &Value) -> Option<(String, String)> {
245 let source = entry.get("source")?;
246 let url = text(source, "url").filter(|value| !value.is_empty())?;
247 let title = text(source, "title")
248 .filter(|value| !value.is_empty())
249 .unwrap_or_else(|| url.clone());
250 Some((title, url))
251}
252
253fn google_attendees(entry: &Value) -> Vec<EventAttendee> {
254 let Some(list) = entry.get("attendees").and_then(Value::as_array) else {
255 return Vec::new();
256 };
257 list.iter()
258 .filter(|attendee| attendee.get("resource").and_then(Value::as_bool) != Some(true))
259 .filter_map(|attendee| {
260 let address = text(attendee, "email");
261 let name = text(attendee, "displayName").or_else(|| address.clone())?;
262 let response = match attendee.get("responseStatus").and_then(Value::as_str) {
263 Some("accepted") => ResponseType::Accepted,
264 Some("declined") => ResponseType::Declined,
265 Some("tentative") => ResponseType::Tentative,
266 _ => ResponseType::NotResponded,
267 };
268 Some(EventAttendee {
269 name,
270 address,
271 response,
272 required: attendee.get("optional").and_then(Value::as_bool) != Some(true),
273 })
274 })
275 .collect()
276}
277
278fn google_response_counts(entry: &Value) -> Option<AttendeeResponseCounts> {
279 let attendees = entry.get("attendees")?.as_array()?;
280 if attendees.is_empty() {
281 return None;
282 }
283 let mut counts = AttendeeResponseCounts::default();
284 for attendee in attendees {
285 match attendee
286 .get("responseStatus")
287 .and_then(Value::as_str)
288 .unwrap_or("needsAction")
289 {
290 "accepted" => counts.accepted += 1,
291 "declined" => counts.declined += 1,
292 "tentative" => counts.tentative += 1,
293 _ => counts.not_responded += 1,
294 }
295 }
296 Some(counts)
297}
298
299fn conference_join_url(entry: &Value) -> Option<String> {
300 entry
301 .pointer("/conferenceData/entryPoints")
302 .and_then(Value::as_array)?
303 .iter()
304 .find_map(|point| {
305 if point.get("entryPointType").and_then(Value::as_str) == Some("video") {
306 text(point, "uri")
307 } else {
308 None
309 }
310 })
311}
312
313fn event_instant(value: &Value) -> Option<(DateTime<Utc>, bool)> {
314 if let Some(date) = value.get("date").and_then(Value::as_str) {
315 let day = NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;
316 let start = day.and_time(NaiveTime::MIN).and_utc();
317 return Some((start, true));
318 }
319 let date_time = value.get("dateTime")?.as_str()?;
320 DateTime::parse_from_rfc3339(date_time)
321 .ok()
322 .map(|time| (time.with_timezone(&Utc), false))
323}
324
325fn response_status(entry: &Value) -> ResponseType {
326 let status = entry
327 .get("attendees")
328 .and_then(Value::as_array)
329 .into_iter()
330 .flatten()
331 .find(|attendee| attendee.get("self").and_then(Value::as_bool) == Some(true))
332 .and_then(|attendee| attendee.get("responseStatus").and_then(Value::as_str))
333 .or_else(|| {
334 entry
335 .pointer("/organizer/self")
336 .and_then(Value::as_bool)
337 .filter(|value| *value)
338 .map(|_| "accepted")
339 });
340 match status {
341 Some("accepted")
342 if entry.pointer("/organizer/self").and_then(Value::as_bool) == Some(true) =>
343 {
344 ResponseType::Organizer
345 }
346 Some("accepted") => ResponseType::Accepted,
347 Some("tentative") => ResponseType::Tentative,
348 Some("declined") => ResponseType::Declined,
349 _ => ResponseType::NotResponded,
350 }
351}
352
353fn text(entry: &Value, key: &str) -> Option<String> {
354 entry.get(key)?.as_str().map(str::to_owned)
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360
361 #[test]
362 fn parses_timed_event_with_teams_link_in_location() {
363 let body = serde_json::json!({
364 "items": [{
365 "id": "evt1",
366 "summary": "Standup",
367 "iCalUID": "uid-1",
368 "start": {"dateTime": "2026-11-11T09:00:00Z"},
369 "end": {"dateTime": "2026-11-11T09:30:00Z"},
370 "location": "https://teams.microsoft.com/l/meetup-join/abc",
371 "attendees": [{"self": true, "responseStatus": "accepted"}]
372 }]
373 });
374 let events = parse_google_events(&body, Some("acc"), Some("primary"));
375 assert_eq!(events.len(), 1);
376 assert_eq!(events[0].subject, "Standup");
377 assert_eq!(events[0].source, CalendarSource::Google);
378 assert_eq!(events[0].account_id.as_deref(), Some("acc"));
379 assert_eq!(
380 events[0].join_url.as_deref(),
381 Some("https://teams.microsoft.com/l/meetup-join/abc")
382 );
383 assert_eq!(events[0].response, ResponseType::Accepted);
384 }
385
386 #[test]
387 fn parses_location_description_series_and_counts() {
388 let body = serde_json::json!({
389 "items": [{
390 "id": "evt2",
391 "summary": "Standup",
392 "description": "Bring updates",
393 "location": "Building 3",
394 "recurrence": ["RRULE:FREQ=WEEKLY"],
395 "start": {"dateTime": "2026-11-11T09:00:00Z"},
396 "end": {"dateTime": "2026-11-11T09:30:00Z"},
397 "attendees": [
398 {"self": true, "responseStatus": "accepted"},
399 {"responseStatus": "declined"},
400 {"responseStatus": "needsAction"}
401 ]
402 }]
403 });
404 let events = parse_google_events(&body, Some("acc"), Some("primary"));
405 assert_eq!(events[0].location.as_deref(), Some("Building 3"));
406 assert_eq!(events[0].body_preview.as_deref(), Some("Bring updates"));
407 assert!(events[0].series);
408 let counts = events[0].response_counts.expect("counts");
409 assert_eq!(counts.accepted, 1);
410 assert_eq!(counts.declined, 1);
411 assert_eq!(counts.not_responded, 1);
412 }
413
414 #[test]
415 fn strips_html_from_google_description() {
416 let body = serde_json::json!({
417 "items": [{
418 "id": "html",
419 "summary": "Notes",
420 "description": "<b>Agenda</b><br> Item&nbsp;1 &amp; notes",
421 "start": {"dateTime": "2026-11-11T09:00:00Z"},
422 "end": {"dateTime": "2026-11-11T09:30:00Z"}
423 }]
424 });
425 let events = parse_google_events(&body, None, None);
426 assert_eq!(
427 events[0].body_preview.as_deref(),
428 Some("Agenda Item 1 & notes")
429 );
430 assert_eq!(
431 events[0].body_html.as_deref(),
432 Some("Agenda Item 1 &amp; notes")
433 );
434 }
435
436 #[test]
437 fn html_description_strips_javascript_hrefs() {
438 let html = description_html(
439 r#"Click <a href="javascript:alert(1)">here</a> or https://safe.example/x"#,
440 );
441 assert!(!html.to_ascii_lowercase().contains("javascript:"));
442 assert!(html.contains(
443 r#"<a href="https://safe.example/x">https://safe.example/x</a>"#
444 ));
445 assert!(html.contains("Click here or"));
446 }
447
448 #[test]
449 fn plain_description_keeps_breaks_and_links() {
450 let html = description_html(
451 "source: llm\nCloud Native\nhttps://email.linuxfoundation.org/foo?x=1\nFrom: CNCF",
452 );
453 assert!(html.contains("source: llm<br>Cloud Native<br>"));
454 assert!(html.contains(
455 r#"<a href="https://email.linuxfoundation.org/foo?x=1">https://email.linuxfoundation.org/foo?x=1</a>"#
456 ));
457 assert!(html.ends_with("From: CNCF") || html.contains("From: CNCF"));
458 assert!(!html.contains("<br><br>From") || html.contains("<br>From: CNCF"));
459 }
460
461 #[test]
462 fn reminders_from_overrides_and_defaults() {
463 let body = serde_json::json!({
464 "defaultReminders": [
465 {"method": "popup", "minutes": 10},
466 {"method": "email", "minutes": 1440}
467 ],
468 "items": [
469 {
470 "id": "override",
471 "summary": "A",
472 "start": {"dateTime": "2026-11-11T09:00:00Z"},
473 "end": {"dateTime": "2026-11-11T09:30:00Z"},
474 "reminders": {
475 "useDefault": false,
476 "overrides": [
477 {"method": "popup", "minutes": 5},
478 {"method": "popup", "minutes": 30},
479 {"method": "email", "minutes": 15}
480 ]
481 },
482 "source": {"title": "[Mail] KubeCon", "url": "https://mail.example/1"},
483 "htmlLink": "https://calendar.google.com/event?eid=abc"
484 },
485 {
486 "id": "default",
487 "summary": "B",
488 "start": {"dateTime": "2026-11-11T10:00:00Z"},
489 "end": {"dateTime": "2026-11-11T10:30:00Z"},
490 "reminders": {"useDefault": true}
491 }
492 ]
493 });
494 let events = parse_google_events(&body, None, None);
495 assert_eq!(events[0].reminders, vec![5, 15, 30]);
496 assert_eq!(
497 events[0].source_link.as_ref().map(|(t, u)| (t.as_str(), u.as_str())),
498 Some(("[Mail] KubeCon", "https://mail.example/1"))
499 );
500 assert_eq!(
501 events[0].web_link.as_deref(),
502 Some("https://calendar.google.com/event?eid=abc")
503 );
504 assert_eq!(events[1].reminders, vec![10, 1440]);
505 }
506
507 #[test]
508 fn parses_all_day_and_calendar_list() {
509 let body = serde_json::json!({
510 "items": [{
511 "id": "day",
512 "summary": "Offsite",
513 "start": {"date": "2026-11-12"},
514 "end": {"date": "2026-11-13"},
515 "status": "confirmed"
516 }]
517 });
518 let events = parse_google_events(&body, None, None);
519 assert!(events[0].all_day);
520 let list = parse_calendar_list(&serde_json::json!({
521 "items": [
522 {"id": "primary", "summary": "Joe", "primary": true},
523 {"id": "work", "summary": "Work"}
524 ]
525 }));
526 assert_eq!(list[0].0, "primary");
527 assert!(list[0].2);
528 }
529}