| 1 | use chrono::{DateTime, NaiveDate, NaiveTime, Utc}; |
| 2 | use serde_json::Value; |
| 3 | |
| 4 | use crate::calendar::{ |
| 5 | AttendeeResponseCounts, CalendarEvent, CalendarSource, EventAttendee, ResponseType, ShowAs, |
| 6 | strip_html, truncate_preview, |
| 7 | }; |
| 8 | |
| 9 | pub 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 | |
| 31 | pub 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 | |
| 48 | fn 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. |
| 128 | pub 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('&', "&") |
| 136 | .replace('<', "<") |
| 137 | .replace('>', ">"); |
| 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 | |
| 145 | fn 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 | |
| 160 | fn 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('"', """); |
| 194 | out.push_str(&format!(r#"<a href="{href}">{url}</a>"#)); |
| 195 | rest = &rest[url.len()..]; |
| 196 | } |
| 197 | out |
| 198 | } |
| 199 | |
| 200 | fn default_reminder_minutes(body: &Value) -> Vec<u32> { |
| 201 | reminder_minutes_from(body.get("defaultReminders")) |
| 202 | } |
| 203 | |
| 204 | fn 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 | |
| 223 | fn 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 |
| 231 | .get("method") |
| 232 | .and_then(Value::as_str) |
| 233 | .unwrap_or("popup"); |
| 234 | if method != "popup" && method != "email" { |
| 235 | return None; |
| 236 | } |
| 237 | item.get("minutes") |
| 238 | .and_then(Value::as_u64) |
| 239 | .map(|value| value as u32) |
| 240 | }) |
| 241 | .collect(); |
| 242 | minutes.sort_unstable(); |
| 243 | minutes.dedup(); |
| 244 | minutes |
| 245 | } |
| 246 | |
| 247 | fn google_source_link(entry: &Value) -> Option<(String, String)> { |
| 248 | let source = entry.get("source")?; |
| 249 | let url = text(source, "url").filter(|value| !value.is_empty())?; |
| 250 | let title = text(source, "title") |
| 251 | .filter(|value| !value.is_empty()) |
| 252 | .unwrap_or_else(|| url.clone()); |
| 253 | Some((title, url)) |
| 254 | } |
| 255 | |
| 256 | fn google_attendees(entry: &Value) -> Vec<EventAttendee> { |
| 257 | let Some(list) = entry.get("attendees").and_then(Value::as_array) else { |
| 258 | return Vec::new(); |
| 259 | }; |
| 260 | list.iter() |
| 261 | .filter(|attendee| attendee.get("resource").and_then(Value::as_bool) != Some(true)) |
| 262 | .filter_map(|attendee| { |
| 263 | let address = text(attendee, "email"); |
| 264 | let name = text(attendee, "displayName").or_else(|| address.clone())?; |
| 265 | let response = match attendee.get("responseStatus").and_then(Value::as_str) { |
| 266 | Some("accepted") => ResponseType::Accepted, |
| 267 | Some("declined") => ResponseType::Declined, |
| 268 | Some("tentative") => ResponseType::Tentative, |
| 269 | _ => ResponseType::NotResponded, |
| 270 | }; |
| 271 | Some(EventAttendee { |
| 272 | name, |
| 273 | address, |
| 274 | response, |
| 275 | required: attendee.get("optional").and_then(Value::as_bool) != Some(true), |
| 276 | }) |
| 277 | }) |
| 278 | .collect() |
| 279 | } |
| 280 | |
| 281 | fn google_response_counts(entry: &Value) -> Option<AttendeeResponseCounts> { |
| 282 | let attendees = entry.get("attendees")?.as_array()?; |
| 283 | if attendees.is_empty() { |
| 284 | return None; |
| 285 | } |
| 286 | let mut counts = AttendeeResponseCounts::default(); |
| 287 | for attendee in attendees { |
| 288 | match attendee |
| 289 | .get("responseStatus") |
| 290 | .and_then(Value::as_str) |
| 291 | .unwrap_or("needsAction") |
| 292 | { |
| 293 | "accepted" => counts.accepted += 1, |
| 294 | "declined" => counts.declined += 1, |
| 295 | "tentative" => counts.tentative += 1, |
| 296 | _ => counts.not_responded += 1, |
| 297 | } |
| 298 | } |
| 299 | Some(counts) |
| 300 | } |
| 301 | |
| 302 | fn conference_join_url(entry: &Value) -> Option<String> { |
| 303 | entry |
| 304 | .pointer("/conferenceData/entryPoints") |
| 305 | .and_then(Value::as_array)? |
| 306 | .iter() |
| 307 | .find_map(|point| { |
| 308 | if point.get("entryPointType").and_then(Value::as_str) == Some("video") { |
| 309 | text(point, "uri") |
| 310 | } else { |
| 311 | None |
| 312 | } |
| 313 | }) |
| 314 | } |
| 315 | |
| 316 | fn event_instant(value: &Value) -> Option<(DateTime<Utc>, bool)> { |
| 317 | if let Some(date) = value.get("date").and_then(Value::as_str) { |
| 318 | let day = NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?; |
| 319 | let start = day.and_time(NaiveTime::MIN).and_utc(); |
| 320 | return Some((start, true)); |
| 321 | } |
| 322 | let date_time = value.get("dateTime")?.as_str()?; |
| 323 | DateTime::parse_from_rfc3339(date_time) |
| 324 | .ok() |
| 325 | .map(|time| (time.with_timezone(&Utc), false)) |
| 326 | } |
| 327 | |
| 328 | fn response_status(entry: &Value) -> ResponseType { |
| 329 | let status = entry |
| 330 | .get("attendees") |
| 331 | .and_then(Value::as_array) |
| 332 | .into_iter() |
| 333 | .flatten() |
| 334 | .find(|attendee| attendee.get("self").and_then(Value::as_bool) == Some(true)) |
| 335 | .and_then(|attendee| attendee.get("responseStatus").and_then(Value::as_str)) |
| 336 | .or_else(|| { |
| 337 | entry |
| 338 | .pointer("/organizer/self") |
| 339 | .and_then(Value::as_bool) |
| 340 | .filter(|value| *value) |
| 341 | .map(|_| "accepted") |
| 342 | }); |
| 343 | match status { |
| 344 | Some("accepted") |
| 345 | if entry.pointer("/organizer/self").and_then(Value::as_bool) == Some(true) => |
| 346 | { |
| 347 | ResponseType::Organizer |
| 348 | } |
| 349 | Some("accepted") => ResponseType::Accepted, |
| 350 | Some("tentative") => ResponseType::Tentative, |
| 351 | Some("declined") => ResponseType::Declined, |
| 352 | _ => ResponseType::NotResponded, |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | fn text(entry: &Value, key: &str) -> Option<String> { |
| 357 | entry.get(key)?.as_str().map(str::to_owned) |
| 358 | } |
| 359 | |
| 360 | #[cfg(test)] |
| 361 | mod tests { |
| 362 | use super::*; |
| 363 | |
| 364 | #[test] |
| 365 | fn parses_timed_event_with_teams_link_in_location() { |
| 366 | let body = serde_json::json!({ |
| 367 | "items": [{ |
| 368 | "id": "evt1", |
| 369 | "summary": "Standup", |
| 370 | "iCalUID": "uid-1", |
| 371 | "start": {"dateTime": "2026-11-11T09:00:00Z"}, |
| 372 | "end": {"dateTime": "2026-11-11T09:30:00Z"}, |
| 373 | "location": "https://teams.microsoft.com/l/meetup-join/abc", |
| 374 | "attendees": [{"self": true, "responseStatus": "accepted"}] |
| 375 | }] |
| 376 | }); |
| 377 | let events = parse_google_events(&body, Some("acc"), Some("primary")); |
| 378 | assert_eq!(events.len(), 1); |
| 379 | assert_eq!(events[0].subject, "Standup"); |
| 380 | assert_eq!(events[0].source, CalendarSource::Google); |
| 381 | assert_eq!(events[0].account_id.as_deref(), Some("acc")); |
| 382 | assert_eq!( |
| 383 | events[0].join_url.as_deref(), |
| 384 | Some("https://teams.microsoft.com/l/meetup-join/abc") |
| 385 | ); |
| 386 | assert_eq!(events[0].response, ResponseType::Accepted); |
| 387 | } |
| 388 | |
| 389 | #[test] |
| 390 | fn parses_location_description_series_and_counts() { |
| 391 | let body = serde_json::json!({ |
| 392 | "items": [{ |
| 393 | "id": "evt2", |
| 394 | "summary": "Standup", |
| 395 | "description": "Bring updates", |
| 396 | "location": "Building 3", |
| 397 | "recurrence": ["RRULE:FREQ=WEEKLY"], |
| 398 | "start": {"dateTime": "2026-11-11T09:00:00Z"}, |
| 399 | "end": {"dateTime": "2026-11-11T09:30:00Z"}, |
| 400 | "attendees": [ |
| 401 | {"self": true, "responseStatus": "accepted"}, |
| 402 | {"responseStatus": "declined"}, |
| 403 | {"responseStatus": "needsAction"} |
| 404 | ] |
| 405 | }] |
| 406 | }); |
| 407 | let events = parse_google_events(&body, Some("acc"), Some("primary")); |
| 408 | assert_eq!(events[0].location.as_deref(), Some("Building 3")); |
| 409 | assert_eq!(events[0].body_preview.as_deref(), Some("Bring updates")); |
| 410 | assert!(events[0].series); |
| 411 | let counts = events[0].response_counts.expect("counts"); |
| 412 | assert_eq!(counts.accepted, 1); |
| 413 | assert_eq!(counts.declined, 1); |
| 414 | assert_eq!(counts.not_responded, 1); |
| 415 | } |
| 416 | |
| 417 | #[test] |
| 418 | fn strips_html_from_google_description() { |
| 419 | let body = serde_json::json!({ |
| 420 | "items": [{ |
| 421 | "id": "html", |
| 422 | "summary": "Notes", |
| 423 | "description": "<b>Agenda</b><br> Item 1 & notes", |
| 424 | "start": {"dateTime": "2026-11-11T09:00:00Z"}, |
| 425 | "end": {"dateTime": "2026-11-11T09:30:00Z"} |
| 426 | }] |
| 427 | }); |
| 428 | let events = parse_google_events(&body, None, None); |
| 429 | assert_eq!( |
| 430 | events[0].body_preview.as_deref(), |
| 431 | Some("Agenda Item 1 & notes") |
| 432 | ); |
| 433 | assert_eq!( |
| 434 | events[0].body_html.as_deref(), |
| 435 | Some("Agenda Item 1 & notes") |
| 436 | ); |
| 437 | } |
| 438 | |
| 439 | #[test] |
| 440 | fn html_description_strips_javascript_hrefs() { |
| 441 | let html = description_html( |
| 442 | r#"Click <a href="javascript:alert(1)">here</a> or https://safe.example/x"#, |
| 443 | ); |
| 444 | assert!(!html.to_ascii_lowercase().contains("javascript:")); |
| 445 | assert!(html.contains(r#"<a href="https://safe.example/x">https://safe.example/x</a>"#)); |
| 446 | assert!(html.contains("Click here or")); |
| 447 | } |
| 448 | |
| 449 | #[test] |
| 450 | fn plain_description_keeps_breaks_and_links() { |
| 451 | let html = description_html( |
| 452 | "source: llm\nCloud Native\nhttps://email.linuxfoundation.org/foo?x=1\nFrom: CNCF", |
| 453 | ); |
| 454 | assert!(html.contains("source: llm<br>Cloud Native<br>")); |
| 455 | assert!(html.contains( |
| 456 | r#"<a href="https://email.linuxfoundation.org/foo?x=1">https://email.linuxfoundation.org/foo?x=1</a>"# |
| 457 | )); |
| 458 | assert!(html.ends_with("From: CNCF") || html.contains("From: CNCF")); |
| 459 | assert!(!html.contains("<br><br>From") || html.contains("<br>From: CNCF")); |
| 460 | } |
| 461 | |
| 462 | #[test] |
| 463 | fn reminders_from_overrides_and_defaults() { |
| 464 | let body = serde_json::json!({ |
| 465 | "defaultReminders": [ |
| 466 | {"method": "popup", "minutes": 10}, |
| 467 | {"method": "email", "minutes": 1440} |
| 468 | ], |
| 469 | "items": [ |
| 470 | { |
| 471 | "id": "override", |
| 472 | "summary": "A", |
| 473 | "start": {"dateTime": "2026-11-11T09:00:00Z"}, |
| 474 | "end": {"dateTime": "2026-11-11T09:30:00Z"}, |
| 475 | "reminders": { |
| 476 | "useDefault": false, |
| 477 | "overrides": [ |
| 478 | {"method": "popup", "minutes": 5}, |
| 479 | {"method": "popup", "minutes": 30}, |
| 480 | {"method": "email", "minutes": 15} |
| 481 | ] |
| 482 | }, |
| 483 | "source": {"title": "[Mail] KubeCon", "url": "https://mail.example/1"}, |
| 484 | "htmlLink": "https://calendar.google.com/event?eid=abc" |
| 485 | }, |
| 486 | { |
| 487 | "id": "default", |
| 488 | "summary": "B", |
| 489 | "start": {"dateTime": "2026-11-11T10:00:00Z"}, |
| 490 | "end": {"dateTime": "2026-11-11T10:30:00Z"}, |
| 491 | "reminders": {"useDefault": true} |
| 492 | } |
| 493 | ] |
| 494 | }); |
| 495 | let events = parse_google_events(&body, None, None); |
| 496 | assert_eq!(events[0].reminders, vec![5, 15, 30]); |
| 497 | assert_eq!( |
| 498 | events[0] |
| 499 | .source_link |
| 500 | .as_ref() |
| 501 | .map(|(t, u)| (t.as_str(), u.as_str())), |
| 502 | Some(("[Mail] KubeCon", "https://mail.example/1")) |
| 503 | ); |
| 504 | assert_eq!( |
| 505 | events[0].web_link.as_deref(), |
| 506 | Some("https://calendar.google.com/event?eid=abc") |
| 507 | ); |
| 508 | assert_eq!(events[1].reminders, vec![10, 1440]); |
| 509 | } |
| 510 | |
| 511 | #[test] |
| 512 | fn parses_all_day_and_calendar_list() { |
| 513 | let body = serde_json::json!({ |
| 514 | "items": [{ |
| 515 | "id": "day", |
| 516 | "summary": "Offsite", |
| 517 | "start": {"date": "2026-11-12"}, |
| 518 | "end": {"date": "2026-11-13"}, |
| 519 | "status": "confirmed" |
| 520 | }] |
| 521 | }); |
| 522 | let events = parse_google_events(&body, None, None); |
| 523 | assert!(events[0].all_day); |
| 524 | let list = parse_calendar_list(&serde_json::json!({ |
| 525 | "items": [ |
| 526 | {"id": "primary", "summary": "Joe", "primary": true}, |
| 527 | {"id": "work", "summary": "Work"} |
| 528 | ] |
| 529 | })); |
| 530 | assert_eq!(list[0].0, "primary"); |
| 531 | assert!(list[0].2); |
| 532 | } |
| 533 | } |