| 1 | use chrono::{DateTime, NaiveDateTime, Utc}; |
| 2 | use serde_json::Value; |
| 3 | use session::{ApiResponse, Method, Request, Session}; |
| 4 | |
| 5 | use crate::cards::{CardTransport, DEFAULT_MT_REGION, SessionCardTransport, spaces_scope}; |
| 6 | use crate::error::{Error, Result}; |
| 7 | |
| 8 | mod availability; |
| 9 | mod merge; |
| 10 | mod reminders; |
| 11 | mod schedule; |
| 12 | |
| 13 | pub use availability::{BusyTime, PersonSchedule, parse_schedules}; |
| 14 | pub use merge::{HomeCalendar, merge_calendar_events, normalize_join_url}; |
| 15 | pub use reminders::{Reminder, parse_reminders}; |
| 16 | pub use schedule::{ |
| 17 | Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, new_event_body_with_join, |
| 18 | parse_created_event, |
| 19 | }; |
| 20 | |
| 21 | const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ"; |
| 22 | const NAIVE_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.f"; |
| 23 | |
| 24 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 25 | pub enum ResponseType { |
| 26 | Organizer, |
| 27 | Accepted, |
| 28 | Tentative, |
| 29 | Declined, |
| 30 | #[default] |
| 31 | NotResponded, |
| 32 | } |
| 33 | |
| 34 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 35 | pub enum ShowAs { |
| 36 | Free, |
| 37 | Tentative, |
| 38 | #[default] |
| 39 | Busy, |
| 40 | OutOfOffice, |
| 41 | WorkingElsewhere, |
| 42 | } |
| 43 | |
| 44 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 45 | pub enum CalendarSource { |
| 46 | #[default] |
| 47 | Outlook, |
| 48 | Google, |
| 49 | CalDav, |
| 50 | /// Read-only ICS subscription (holidays, shared links). |
| 51 | Ics, |
| 52 | } |
| 53 | |
| 54 | impl CalendarSource { |
| 55 | pub fn label(self) -> &'static str { |
| 56 | match self { |
| 57 | CalendarSource::Outlook => "Outlook", |
| 58 | CalendarSource::Google => "Google", |
| 59 | CalendarSource::CalDav => "CalDAV", |
| 60 | CalendarSource::Ics => "ICS", |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | pub fn is_outlook(self) -> bool { |
| 65 | matches!(self, CalendarSource::Outlook) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 70 | pub struct AttendeeResponseCounts { |
| 71 | pub accepted: u32, |
| 72 | pub declined: u32, |
| 73 | pub tentative: u32, |
| 74 | pub not_responded: u32, |
| 75 | } |
| 76 | |
| 77 | impl AttendeeResponseCounts { |
| 78 | pub fn is_empty(self) -> bool { |
| 79 | self.accepted == 0 && self.declined == 0 && self.tentative == 0 && self.not_responded == 0 |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 84 | pub struct EventAttendee { |
| 85 | pub name: String, |
| 86 | pub address: Option<String>, |
| 87 | pub response: ResponseType, |
| 88 | pub required: bool, |
| 89 | } |
| 90 | |
| 91 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 92 | pub struct CalendarEvent { |
| 93 | pub object_id: String, |
| 94 | pub subject: String, |
| 95 | pub start: DateTime<Utc>, |
| 96 | pub end: DateTime<Utc>, |
| 97 | pub all_day: bool, |
| 98 | pub cancelled: bool, |
| 99 | pub online: bool, |
| 100 | pub join_url: Option<String>, |
| 101 | pub thread_id: Option<String>, |
| 102 | pub organizer_name: Option<String>, |
| 103 | pub organizer_address: Option<String>, |
| 104 | pub ical_uid: Option<String>, |
| 105 | pub response: ResponseType, |
| 106 | pub show_as: ShowAs, |
| 107 | pub dial_in: Option<DialIn>, |
| 108 | pub source: CalendarSource, |
| 109 | pub account_id: Option<String>, |
| 110 | pub calendar_id: Option<String>, |
| 111 | /// When a merge collapsed duplicates, every contributing source. |
| 112 | pub sources: Vec<CalendarSource>, |
| 113 | pub location: Option<String>, |
| 114 | pub body_preview: Option<String>, |
| 115 | /// Full event body (HTML). `body_preview` from list payloads is server-truncated. |
| 116 | pub body_html: Option<String>, |
| 117 | pub series: bool, |
| 118 | pub series_master_id: Option<String>, |
| 119 | pub response_counts: Option<AttendeeResponseCounts>, |
| 120 | pub attendees: Vec<EventAttendee>, |
| 121 | /// Minutes before start (Google reminders). Empty when unknown. |
| 122 | pub reminders: Vec<u32>, |
| 123 | /// Google `source` title + URL (View source). |
| 124 | pub source_link: Option<(String, String)>, |
| 125 | /// Google `htmlLink` — open in Google Calendar. |
| 126 | pub web_link: Option<String>, |
| 127 | /// Display name of the calendar that owns the event (Google). |
| 128 | pub calendar_name: Option<String>, |
| 129 | } |
| 130 | |
| 131 | impl CalendarEvent { |
| 132 | pub fn outlook_defaults() -> ( |
| 133 | CalendarSource, |
| 134 | Option<String>, |
| 135 | Option<String>, |
| 136 | Vec<CalendarSource>, |
| 137 | ) { |
| 138 | ( |
| 139 | CalendarSource::Outlook, |
| 140 | None, |
| 141 | None, |
| 142 | vec![CalendarSource::Outlook], |
| 143 | ) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | impl Default for CalendarEvent { |
| 148 | fn default() -> Self { |
| 149 | let (source, account_id, calendar_id, sources) = Self::outlook_defaults(); |
| 150 | CalendarEvent { |
| 151 | object_id: String::new(), |
| 152 | subject: String::new(), |
| 153 | start: DateTime::<Utc>::UNIX_EPOCH, |
| 154 | end: DateTime::<Utc>::UNIX_EPOCH, |
| 155 | all_day: false, |
| 156 | cancelled: false, |
| 157 | online: false, |
| 158 | join_url: None, |
| 159 | thread_id: None, |
| 160 | organizer_name: None, |
| 161 | organizer_address: None, |
| 162 | ical_uid: None, |
| 163 | response: ResponseType::default(), |
| 164 | show_as: ShowAs::default(), |
| 165 | dial_in: None, |
| 166 | source, |
| 167 | account_id, |
| 168 | calendar_id, |
| 169 | sources, |
| 170 | location: None, |
| 171 | body_preview: None, |
| 172 | body_html: None, |
| 173 | series: false, |
| 174 | series_master_id: None, |
| 175 | response_counts: None, |
| 176 | attendees: Vec::new(), |
| 177 | reminders: Vec::new(), |
| 178 | source_link: None, |
| 179 | web_link: None, |
| 180 | calendar_name: None, |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 186 | pub struct DialIn { |
| 187 | pub toll_number: String, |
| 188 | pub conference_id: String, |
| 189 | } |
| 190 | |
| 191 | const JOIN_INFO_TITLE: &str = "Microsoft Teams meeting"; |
| 192 | |
| 193 | /// The plain text Teams puts on the clipboard for "Copy join info". |
| 194 | pub fn join_info_text(join_url: &str, dial_in: Option<&DialIn>) -> String { |
| 195 | let mut lines = vec![JOIN_INFO_TITLE.to_owned(), format!("Join: {join_url}")]; |
| 196 | if let Some(dial_in) = dial_in { |
| 197 | lines.push(String::new()); |
| 198 | lines.push("Dial in by phone".to_owned()); |
| 199 | lines.push(format!( |
| 200 | "{},,{}#", |
| 201 | dial_in.toll_number, dial_in.conference_id |
| 202 | )); |
| 203 | lines.push(format!("Phone conference ID: {}#", dial_in.conference_id)); |
| 204 | } |
| 205 | lines.join("\n") |
| 206 | } |
| 207 | |
| 208 | fn dial_in(entry: &Value) -> Option<DialIn> { |
| 209 | Some(DialIn { |
| 210 | toll_number: text(entry, "onlineMeetingTollNumber").filter(|value| !value.is_empty())?, |
| 211 | conference_id: text(entry, "onlineMeetingConferenceId") |
| 212 | .filter(|value| !value.is_empty())?, |
| 213 | }) |
| 214 | } |
| 215 | |
| 216 | pub struct Calendar<T: CardTransport = SessionCardTransport> { |
| 217 | transport: T, |
| 218 | url: String, |
| 219 | create_url: String, |
| 220 | mt_region: String, |
| 221 | } |
| 222 | |
| 223 | impl Calendar<SessionCardTransport> { |
| 224 | pub fn new(session: &Session) -> Self { |
| 225 | Calendar::with_transport(SessionCardTransport::new(session), DEFAULT_MT_REGION) |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | impl<T: CardTransport> Calendar<T> { |
| 230 | pub fn with_transport(transport: T, mt_region: &str) -> Self { |
| 231 | Calendar { |
| 232 | transport, |
| 233 | url: format!( |
| 234 | "https://teams.cloud.microsoft/api/mt/{mt_region}/v2.1/me/calendars/calendarView" |
| 235 | ), |
| 236 | create_url: format!( |
| 237 | "https://teams.cloud.microsoft/api/mt/{mt_region}/beta/me/calendarEvents/privateMeeting/schedulingService/create" |
| 238 | ), |
| 239 | mt_region: mt_region.to_owned(), |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | pub fn teams_event_url(&self, event_id: &str) -> String { |
| 244 | format!( |
| 245 | "https://teams.cloud.microsoft/api/mt/{}/beta/me/calendarEvents/{}", |
| 246 | self.mt_region, |
| 247 | crate::messages::encode(event_id) |
| 248 | ) |
| 249 | } |
| 250 | |
| 251 | pub async fn calendar_view( |
| 252 | &self, |
| 253 | start: DateTime<Utc>, |
| 254 | end: DateTime<Utc>, |
| 255 | ) -> Result<Vec<CalendarEvent>> { |
| 256 | let answer = self.view_response(start, end).await?; |
| 257 | if !answer.is_success() { |
| 258 | return Err(Error::Session(session::Error::api( |
| 259 | answer.status, |
| 260 | &self.url, |
| 261 | answer.body, |
| 262 | ))); |
| 263 | } |
| 264 | Ok(parse_calendar_events(&answer.body)) |
| 265 | } |
| 266 | |
| 267 | pub async fn view_response( |
| 268 | &self, |
| 269 | start: DateTime<Utc>, |
| 270 | end: DateTime<Utc>, |
| 271 | ) -> Result<ApiResponse> { |
| 272 | let url = format!( |
| 273 | "{}?startDate={}&endDate={}", |
| 274 | self.url, |
| 275 | start.format(QUERY_TIME_FORMAT), |
| 276 | end.format(QUERY_TIME_FORMAT) |
| 277 | ); |
| 278 | self.transport.send(Request::get(url), spaces_scope()).await |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | impl<T: CardTransport> Calendar<T> { |
| 283 | pub async fn create_meet_now(&self, subject: &str) -> Result<String> { |
| 284 | let body = serde_json::json!({ |
| 285 | "meetingType": "MeetNow", |
| 286 | "isStreamEnabled": false, |
| 287 | "subject": subject, |
| 288 | "unhideChatThread": true, |
| 289 | }); |
| 290 | let answer = self |
| 291 | .transport |
| 292 | .send( |
| 293 | Request::with_body(Method::Post, &self.create_url, body), |
| 294 | spaces_scope(), |
| 295 | ) |
| 296 | .await?; |
| 297 | if !answer.is_success() { |
| 298 | return Err(Error::Session(session::Error::api( |
| 299 | answer.status, |
| 300 | &self.create_url, |
| 301 | answer.body, |
| 302 | ))); |
| 303 | } |
| 304 | meet_now_join_url(&answer.body).ok_or_else(|| { |
| 305 | Error::Session(session::Error::api( |
| 306 | answer.status, |
| 307 | &self.create_url, |
| 308 | answer.body, |
| 309 | )) |
| 310 | }) |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | pub fn meet_now_join_url(body: &Value) -> Option<String> { |
| 315 | let value = body.get("value")?; |
| 316 | value |
| 317 | .pointer("/links/join") |
| 318 | .or_else(|| value.get("meetingUrl")) |
| 319 | .and_then(Value::as_str) |
| 320 | .map(str::to_owned) |
| 321 | } |
| 322 | |
| 323 | pub fn parse_calendar_events(body: &Value) -> Vec<CalendarEvent> { |
| 324 | let entries = body.get("value").unwrap_or(body); |
| 325 | let mut events: Vec<CalendarEvent> = entries |
| 326 | .as_array() |
| 327 | .into_iter() |
| 328 | .flatten() |
| 329 | .filter_map(parse_event) |
| 330 | .collect(); |
| 331 | events.sort_by_key(|event| (event.start, event.end)); |
| 332 | events |
| 333 | } |
| 334 | |
| 335 | fn text(entry: &Value, key: &str) -> Option<String> { |
| 336 | entry |
| 337 | .get(key)? |
| 338 | .as_str() |
| 339 | .filter(|text| !text.is_empty()) |
| 340 | .map(str::to_owned) |
| 341 | } |
| 342 | |
| 343 | fn flag(entry: &Value, key: &str) -> bool { |
| 344 | entry.get(key).and_then(Value::as_bool).unwrap_or(false) |
| 345 | } |
| 346 | |
| 347 | fn time(entry: &Value, key: &str) -> Option<DateTime<Utc>> { |
| 348 | let text = entry.get(key)?.as_str()?; |
| 349 | DateTime::parse_from_rfc3339(text) |
| 350 | .map(|time| time.with_timezone(&Utc)) |
| 351 | .or_else(|_| { |
| 352 | NaiveDateTime::parse_from_str(text, NAIVE_TIME_FORMAT).map(|time| time.and_utc()) |
| 353 | }) |
| 354 | .ok() |
| 355 | } |
| 356 | |
| 357 | fn thread_id(entry: &Value) -> Option<String> { |
| 358 | text(entry, "threadId").or_else(|| { |
| 359 | let data: Value = serde_json::from_str(entry.get("skypeTeamsData")?.as_str()?).ok()?; |
| 360 | text(&data, "cid") |
| 361 | }) |
| 362 | } |
| 363 | |
| 364 | fn response_type(entry: &Value) -> ResponseType { |
| 365 | if flag(entry, "isOrganizer") { |
| 366 | return ResponseType::Organizer; |
| 367 | } |
| 368 | let label = text(entry, "myResponseType").or_else(|| { |
| 369 | let status = entry.get("responseStatus")?; |
| 370 | status |
| 371 | .as_str() |
| 372 | .map(str::to_owned) |
| 373 | .or_else(|| text(status, "response")) |
| 374 | }); |
| 375 | match label.as_deref() { |
| 376 | Some("Organizer") => ResponseType::Organizer, |
| 377 | Some("Accepted") => ResponseType::Accepted, |
| 378 | Some("TentativelyAccepted" | "Tentative") => ResponseType::Tentative, |
| 379 | Some("Declined") => ResponseType::Declined, |
| 380 | _ => ResponseType::NotResponded, |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | fn show_as(entry: &Value) -> ShowAs { |
| 385 | match text(entry, "showAs").as_deref() { |
| 386 | Some("Free") => ShowAs::Free, |
| 387 | Some("Tentative") => ShowAs::Tentative, |
| 388 | Some("Oof") => ShowAs::OutOfOffice, |
| 389 | Some("WorkingElsewhere") => ShowAs::WorkingElsewhere, |
| 390 | _ => ShowAs::Busy, |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | fn location_text(entry: &Value) -> Option<String> { |
| 395 | text(entry, "locationDisplayName") |
| 396 | .or_else(|| text(entry, "location")) |
| 397 | .or_else(|| { |
| 398 | entry |
| 399 | .get("location") |
| 400 | .and_then(|location| text(location, "displayName")) |
| 401 | }) |
| 402 | .filter(|value| !value.is_empty()) |
| 403 | } |
| 404 | |
| 405 | fn body_preview_text(entry: &Value) -> Option<String> { |
| 406 | text(entry, "bodyPreview") |
| 407 | .or_else(|| text(entry, "bodyContent").map(|content| strip_html(&content))) |
| 408 | .or_else(|| { |
| 409 | entry |
| 410 | .get("body") |
| 411 | .and_then(|body| text(body, "content")) |
| 412 | .map(|content| strip_html(&content)) |
| 413 | }) |
| 414 | .map(|preview| normalize_preview_whitespace(&preview)) |
| 415 | .map(|preview| truncate_preview(&preview)) |
| 416 | .filter(|value| !value.is_empty()) |
| 417 | } |
| 418 | |
| 419 | /// Full body as HTML: Teams MT `bodyContent` or Graph `body.content`. |
| 420 | /// Plain-text bodies are escaped and keep their line breaks. |
| 421 | fn body_html_text(entry: &Value) -> Option<String> { |
| 422 | let (content, kind) = match text(entry, "bodyContent") { |
| 423 | Some(content) => (content, text(entry, "bodyContentType")), |
| 424 | None => { |
| 425 | let body = entry.get("body")?; |
| 426 | (text(body, "content")?, text(body, "contentType")) |
| 427 | } |
| 428 | }; |
| 429 | if content.trim().is_empty() { |
| 430 | return None; |
| 431 | } |
| 432 | if kind.is_some_and(|kind| kind.eq_ignore_ascii_case("text")) { |
| 433 | let escaped = content |
| 434 | .replace('&', "&") |
| 435 | .replace('<', "<") |
| 436 | .replace('>', ">") |
| 437 | .replace("\r\n", "\n") |
| 438 | .replace('\r', "\n") |
| 439 | .replace('\n', "<br>"); |
| 440 | return Some(escaped); |
| 441 | } |
| 442 | Some(content) |
| 443 | } |
| 444 | |
| 445 | fn attendee_response(label: &str) -> ResponseType { |
| 446 | match label { |
| 447 | "accepted" | "Accepted" => ResponseType::Accepted, |
| 448 | "organizer" | "Organizer" => ResponseType::Organizer, |
| 449 | "declined" | "Declined" => ResponseType::Declined, |
| 450 | "tentativelyAccepted" | "TentativelyAccepted" | "tentative" | "Tentative" => { |
| 451 | ResponseType::Tentative |
| 452 | } |
| 453 | _ => ResponseType::NotResponded, |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | /// Attendee roster from Graph (`emailAddress{name,address}`) or Teams MT (`name`, `address`). |
| 458 | pub fn attendees_from_entry(entry: &Value) -> Vec<EventAttendee> { |
| 459 | let Some(list) = entry.get("attendees").and_then(Value::as_array) else { |
| 460 | return Vec::new(); |
| 461 | }; |
| 462 | list.iter() |
| 463 | .filter_map(|attendee| { |
| 464 | let address = attendee |
| 465 | .pointer("/emailAddress/address") |
| 466 | .and_then(Value::as_str) |
| 467 | .or_else(|| attendee.get("address").and_then(Value::as_str)) |
| 468 | .filter(|value| !value.is_empty()) |
| 469 | .map(str::to_owned); |
| 470 | let name = attendee |
| 471 | .pointer("/emailAddress/name") |
| 472 | .and_then(Value::as_str) |
| 473 | .or_else(|| attendee.get("name").and_then(Value::as_str)) |
| 474 | .filter(|value| !value.is_empty()) |
| 475 | .map(str::to_owned) |
| 476 | .or_else(|| address.clone())?; |
| 477 | let required = !attendee |
| 478 | .get("type") |
| 479 | .and_then(Value::as_str) |
| 480 | .is_some_and(|kind| !kind.eq_ignore_ascii_case("required")); |
| 481 | Some(EventAttendee { |
| 482 | name, |
| 483 | address, |
| 484 | response: attendee_response(attendee_response_label(attendee).unwrap_or("none")), |
| 485 | required, |
| 486 | }) |
| 487 | }) |
| 488 | .collect() |
| 489 | } |
| 490 | |
| 491 | fn normalize_preview_whitespace(preview: &str) -> String { |
| 492 | preview |
| 493 | .replace("\r\n", "\n") |
| 494 | .replace('\r', "\n") |
| 495 | .trim() |
| 496 | .to_owned() |
| 497 | } |
| 498 | |
| 499 | pub fn strip_html(input: &str) -> String { |
| 500 | let mut out = String::with_capacity(input.len()); |
| 501 | let mut in_tag = false; |
| 502 | for character in input.chars() { |
| 503 | match character { |
| 504 | '<' => { |
| 505 | in_tag = true; |
| 506 | // Keep a word break when tags sit flush against text (`</p><p>`). |
| 507 | out.push(' '); |
| 508 | } |
| 509 | '>' => in_tag = false, |
| 510 | _ if !in_tag => out.push(character), |
| 511 | _ => {} |
| 512 | } |
| 513 | } |
| 514 | html_entities(&out) |
| 515 | .split_whitespace() |
| 516 | .collect::<Vec<_>>() |
| 517 | .join(" ") |
| 518 | } |
| 519 | |
| 520 | fn html_entities(input: &str) -> String { |
| 521 | input |
| 522 | .replace(" ", " ") |
| 523 | .replace("&", "&") |
| 524 | .replace("<", "<") |
| 525 | .replace(">", ">") |
| 526 | .replace(""", "\"") |
| 527 | .replace("'", "'") |
| 528 | } |
| 529 | |
| 530 | pub fn truncate_preview(preview: &str) -> String { |
| 531 | // Long enough for a Teams peek agenda; UI scrolls instead of hard-clipping. |
| 532 | const MAX_CHARS: usize = 4_000; |
| 533 | let trimmed = preview.trim(); |
| 534 | if trimmed.chars().count() <= MAX_CHARS { |
| 535 | return trimmed.to_owned(); |
| 536 | } |
| 537 | let mut cut: String = trimmed.chars().take(MAX_CHARS).collect(); |
| 538 | cut.push('…'); |
| 539 | cut |
| 540 | } |
| 541 | |
| 542 | fn series_flag(entry: &Value) -> bool { |
| 543 | if flag(entry, "isRecurring") || flag(entry, "isSeriesMaster") { |
| 544 | return true; |
| 545 | } |
| 546 | match text(entry, "eventType") |
| 547 | .or_else(|| text(entry, "type")) |
| 548 | .as_deref() |
| 549 | { |
| 550 | Some("occurrence" | "exception" | "seriesMaster") => true, |
| 551 | _ => { |
| 552 | entry |
| 553 | .get("seriesMasterId") |
| 554 | .and_then(Value::as_str) |
| 555 | .is_some() |
| 556 | || entry.get("recurrence").is_some() |
| 557 | } |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | fn series_master_id(entry: &Value) -> Option<String> { |
| 562 | text(entry, "seriesMasterId").or_else(|| text(entry, "seriesMasterObjectId")) |
| 563 | } |
| 564 | |
| 565 | fn attendee_response_label(attendee: &Value) -> Option<&str> { |
| 566 | attendee |
| 567 | .pointer("/status/response") |
| 568 | .and_then(Value::as_str) |
| 569 | .or_else(|| attendee.get("responseStatus").and_then(Value::as_str)) |
| 570 | } |
| 571 | |
| 572 | pub fn response_counts_from_attendees(entry: &Value) -> Option<AttendeeResponseCounts> { |
| 573 | let attendees = entry.get("attendees")?.as_array()?; |
| 574 | if attendees.is_empty() { |
| 575 | return None; |
| 576 | } |
| 577 | let mut counts = AttendeeResponseCounts::default(); |
| 578 | for attendee in attendees { |
| 579 | match attendee_response_label(attendee).unwrap_or("none") { |
| 580 | "accepted" | "Accepted" | "organizer" | "Organizer" => counts.accepted += 1, |
| 581 | "declined" | "Declined" => counts.declined += 1, |
| 582 | "tentativelyAccepted" | "TentativelyAccepted" | "tentative" | "Tentative" => { |
| 583 | counts.tentative += 1 |
| 584 | } |
| 585 | _ => counts.not_responded += 1, |
| 586 | } |
| 587 | } |
| 588 | Some(counts) |
| 589 | } |
| 590 | |
| 591 | /// Merge Graph / detail fields into a calendar event without wiping list data. |
| 592 | pub fn apply_event_details(event: &mut CalendarEvent, entry: &Value) { |
| 593 | if entry.get("location").is_some() || entry.get("locationDisplayName").is_some() { |
| 594 | event.location = location_text(entry); |
| 595 | } |
| 596 | if let Some(preview) = body_preview_text(entry) { |
| 597 | event.body_preview = Some(preview); |
| 598 | } |
| 599 | if let Some(html) = body_html_text(entry) { |
| 600 | event.body_html = Some(html); |
| 601 | } |
| 602 | if series_flag(entry) { |
| 603 | event.series = true; |
| 604 | } |
| 605 | if let Some(master) = series_master_id(entry) { |
| 606 | event.series_master_id = Some(master); |
| 607 | event.series = true; |
| 608 | } |
| 609 | if entry.get("attendees").is_some_and(Value::is_array) { |
| 610 | event.response_counts = response_counts_from_attendees(entry); |
| 611 | event.attendees = attendees_from_entry(entry); |
| 612 | } |
| 613 | if let Some(name) = entry |
| 614 | .pointer("/organizer/emailAddress/name") |
| 615 | .and_then(Value::as_str) |
| 616 | .filter(|value| !value.is_empty()) |
| 617 | { |
| 618 | event.organizer_name = Some(name.to_owned()); |
| 619 | } |
| 620 | if let Some(address) = entry |
| 621 | .pointer("/organizer/emailAddress/address") |
| 622 | .and_then(Value::as_str) |
| 623 | .filter(|value| !value.is_empty()) |
| 624 | { |
| 625 | event.organizer_address = Some(address.to_owned()); |
| 626 | } |
| 627 | if event.join_url.is_none() { |
| 628 | if let Some(url) = entry |
| 629 | .pointer("/onlineMeeting/joinUrl") |
| 630 | .and_then(Value::as_str) |
| 631 | .map(str::to_owned) |
| 632 | .or_else(|| text(entry, "skypeTeamsMeetingUrl")) |
| 633 | .or_else(|| text(entry, "joinUrl")) |
| 634 | { |
| 635 | event.join_url = Some(url); |
| 636 | event.online = true; |
| 637 | } |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | fn parse_event(entry: &Value) -> Option<CalendarEvent> { |
| 642 | let join_url = text(entry, "skypeTeamsMeetingUrl").or_else(|| text(entry, "joinUrl")); |
| 643 | let (source, account_id, calendar_id, sources) = CalendarEvent::outlook_defaults(); |
| 644 | Some(CalendarEvent { |
| 645 | object_id: text(entry, "objectId").or_else(|| text(entry, "id"))?, |
| 646 | subject: text(entry, "subject").unwrap_or_default(), |
| 647 | start: time(entry, "startTime")?, |
| 648 | end: time(entry, "endTime")?, |
| 649 | all_day: flag(entry, "isAllDayEvent") || flag(entry, "isAllDay"), |
| 650 | cancelled: flag(entry, "isCancelled"), |
| 651 | online: flag(entry, "isOnlineMeeting") || join_url.is_some(), |
| 652 | join_url, |
| 653 | thread_id: thread_id(entry), |
| 654 | organizer_name: text(entry, "organizerName"), |
| 655 | organizer_address: text(entry, "organizerAddress"), |
| 656 | ical_uid: text(entry, "iCalUid") |
| 657 | .or_else(|| text(entry, "iCalUId")) |
| 658 | .or_else(|| text(entry, "iCalUID")), |
| 659 | response: response_type(entry), |
| 660 | show_as: show_as(entry), |
| 661 | dial_in: dial_in(entry), |
| 662 | source, |
| 663 | account_id, |
| 664 | calendar_id, |
| 665 | sources, |
| 666 | location: location_text(entry), |
| 667 | body_preview: body_preview_text(entry), |
| 668 | body_html: body_html_text(entry), |
| 669 | series: series_flag(entry), |
| 670 | series_master_id: series_master_id(entry), |
| 671 | response_counts: response_counts_from_attendees(entry), |
| 672 | attendees: attendees_from_entry(entry), |
| 673 | reminders: Vec::new(), |
| 674 | source_link: None, |
| 675 | web_link: None, |
| 676 | calendar_name: None, |
| 677 | }) |
| 678 | } |
| 679 | |
| 680 | #[cfg(test)] |
| 681 | mod tests { |
| 682 | #[test] |
| 683 | fn join_info_carries_the_phone_dial_in_like_teams() { |
| 684 | let entry = serde_json::json!({ |
| 685 | "onlineMeetingTollNumber": "+49 30 123456", |
| 686 | "onlineMeetingConferenceId": "987654321", |
| 687 | }); |
| 688 | let parsed = dial_in(&entry).expect("dial in"); |
| 689 | assert_eq!( |
| 690 | join_info_text("https://teams.microsoft.com/l/meetup-join/x", Some(&parsed)), |
| 691 | "Microsoft Teams meeting\nJoin: https://teams.microsoft.com/l/meetup-join/x\n\nDial in by phone\n+49 30 123456,,987654321#\nPhone conference ID: 987654321#" |
| 692 | ); |
| 693 | assert_eq!( |
| 694 | dial_in(&serde_json::json!({"onlineMeetingTollNumber": ""})), |
| 695 | None |
| 696 | ); |
| 697 | assert_eq!( |
| 698 | join_info_text("https://x", None), |
| 699 | "Microsoft Teams meeting\nJoin: https://x" |
| 700 | ); |
| 701 | } |
| 702 | |
| 703 | #[test] |
| 704 | fn meet_now_join_url_prefers_the_join_link() { |
| 705 | let body = serde_json::json!({"value": { |
| 706 | "links": {"join": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_a%40thread.v2/0"}, |
| 707 | "meetingUrl": "https://example.invalid/other", |
| 708 | }}); |
| 709 | assert_eq!( |
| 710 | meet_now_join_url(&body).as_deref(), |
| 711 | Some("https://teams.microsoft.com/l/meetup-join/19%3ameeting_a%40thread.v2/0") |
| 712 | ); |
| 713 | assert_eq!(meet_now_join_url(&serde_json::json!({"value": {}})), None); |
| 714 | } |
| 715 | |
| 716 | use std::sync::Mutex; |
| 717 | |
| 718 | use chrono::{Duration, TimeZone}; |
| 719 | use session::Scope; |
| 720 | |
| 721 | use super::*; |
| 722 | |
| 723 | struct Canned { |
| 724 | body: Value, |
| 725 | sent: Mutex<Vec<(Request, Scope)>>, |
| 726 | } |
| 727 | |
| 728 | impl CardTransport for Canned { |
| 729 | async fn send(&self, request: Request, scope: Scope) -> Result<ApiResponse> { |
| 730 | self.sent.lock().unwrap().push((request, scope)); |
| 731 | Ok(ApiResponse { |
| 732 | status: 200, |
| 733 | body: self.body.clone(), |
| 734 | retry_after: None, |
| 735 | }) |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | fn fixture() -> Value { |
| 740 | serde_json::from_str(include_str!("../tests/fixtures/calendar_view.json")).unwrap() |
| 741 | } |
| 742 | |
| 743 | #[test] |
| 744 | fn events_are_parsed_and_sorted_by_start() { |
| 745 | let events = parse_calendar_events(&fixture()); |
| 746 | assert_eq!(events.len(), 4); |
| 747 | let offsite = &events[0]; |
| 748 | assert!(offsite.all_day); |
| 749 | assert!(!offsite.online); |
| 750 | assert_eq!(offsite.join_url, None); |
| 751 | assert_eq!(offsite.thread_id, None); |
| 752 | assert_eq!(offsite.response, ResponseType::NotResponded); |
| 753 | let standup = &events[1]; |
| 754 | assert_eq!(standup.subject, "Team standup"); |
| 755 | assert_eq!( |
| 756 | standup.start, |
| 757 | Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap() |
| 758 | ); |
| 759 | assert_eq!(standup.organizer_name.as_deref(), Some("Mara Lindqvist")); |
| 760 | assert_eq!( |
| 761 | standup.join_url.as_deref(), |
| 762 | Some("https://teams.microsoft.com/l/meetup-join/19%3ameeting_demo1%40thread.v2/0") |
| 763 | ); |
| 764 | assert!(standup.online); |
| 765 | assert_eq!(standup.response, ResponseType::Accepted); |
| 766 | assert_eq!( |
| 767 | standup.thread_id.as_deref(), |
| 768 | Some("19:meeting_demo1@thread.v2") |
| 769 | ); |
| 770 | assert_eq!(standup.location.as_deref(), Some("Microsoft Teams Meeting")); |
| 771 | assert_eq!( |
| 772 | standup.body_preview.as_deref(), |
| 773 | Some("Daily agenda and blockers") |
| 774 | ); |
| 775 | assert!(standup.series); |
| 776 | assert_eq!( |
| 777 | standup.series_master_id.as_deref(), |
| 778 | Some("evt-standup-master") |
| 779 | ); |
| 780 | let counts = standup.response_counts.expect("counts"); |
| 781 | assert_eq!(counts.accepted, 2); |
| 782 | assert_eq!(counts.declined, 1); |
| 783 | assert_eq!(counts.not_responded, 2); |
| 784 | } |
| 785 | |
| 786 | #[test] |
| 787 | fn strip_html_flattens_markup_for_peek_preview() { |
| 788 | assert_eq!(strip_html("<p>Hello <b>team</b></p>"), "Hello team"); |
| 789 | assert_eq!(strip_html("<p>NEUE</p><p>Agenda</p>"), "NEUE Agenda"); |
| 790 | assert_eq!(truncate_preview(&"x".repeat(4_100)).chars().count(), 4_001); |
| 791 | } |
| 792 | |
| 793 | #[test] |
| 794 | fn apply_event_details_fills_missing_peek_fields() { |
| 795 | let mut event = CalendarEvent { |
| 796 | object_id: "a".into(), |
| 797 | start: Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap(), |
| 798 | end: Utc.with_ymd_and_hms(2026, 10, 12, 9, 0, 0).unwrap(), |
| 799 | ..Default::default() |
| 800 | }; |
| 801 | apply_event_details( |
| 802 | &mut event, |
| 803 | &serde_json::json!({ |
| 804 | "bodyPreview": "Notes", |
| 805 | "location": {"displayName": "Room A"}, |
| 806 | "type": "seriesMaster", |
| 807 | "seriesMasterId": "master", |
| 808 | "attendees": [ |
| 809 | {"status": {"response": "accepted"}}, |
| 810 | {"status": {"response": "tentativelyAccepted"}}, |
| 811 | ], |
| 812 | "onlineMeeting": {"joinUrl": "https://teams.microsoft.com/l/meetup-join/z"} |
| 813 | }), |
| 814 | ); |
| 815 | assert_eq!(event.body_preview.as_deref(), Some("Notes")); |
| 816 | assert_eq!(event.location.as_deref(), Some("Room A")); |
| 817 | assert!(event.series); |
| 818 | assert_eq!(event.series_master_id.as_deref(), Some("master")); |
| 819 | assert_eq!( |
| 820 | event.join_url.as_deref(), |
| 821 | Some("https://teams.microsoft.com/l/meetup-join/z") |
| 822 | ); |
| 823 | let counts = event.response_counts.expect("counts"); |
| 824 | assert_eq!(counts.accepted, 1); |
| 825 | assert_eq!(counts.tentative, 1); |
| 826 | } |
| 827 | |
| 828 | #[test] |
| 829 | fn parses_teams_ical_uid_and_body_content() { |
| 830 | let events = parse_calendar_events(&serde_json::json!({ |
| 831 | "value": [{ |
| 832 | "objectId": "evt-1", |
| 833 | "subject": "Standup", |
| 834 | "startTime": "2026-11-09T11:00:00Z", |
| 835 | "endTime": "2026-11-09T11:15:00Z", |
| 836 | "iCalUID": "uid-from-teams", |
| 837 | "bodyContent": "<p>NEUE TERMINE</p><p>Agenda</p>", |
| 838 | "location": "Microsoft Teams-Besprechung" |
| 839 | }] |
| 840 | })); |
| 841 | assert_eq!(events[0].ical_uid.as_deref(), Some("uid-from-teams")); |
| 842 | assert_eq!( |
| 843 | events[0].body_preview.as_deref(), |
| 844 | Some("NEUE TERMINE Agenda") |
| 845 | ); |
| 846 | assert_eq!( |
| 847 | events[0].location.as_deref(), |
| 848 | Some("Microsoft Teams-Besprechung") |
| 849 | ); |
| 850 | } |
| 851 | |
| 852 | #[test] |
| 853 | fn text_body_normalizes_lone_carriage_returns() { |
| 854 | let mut event = CalendarEvent { |
| 855 | object_id: "cr".into(), |
| 856 | start: Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap(), |
| 857 | end: Utc.with_ymd_and_hms(2026, 10, 12, 9, 0, 0).unwrap(), |
| 858 | ..Default::default() |
| 859 | }; |
| 860 | apply_event_details( |
| 861 | &mut event, |
| 862 | &serde_json::json!({ |
| 863 | "body": {"contentType": "text", "content": "Line1\rLine2\r\nLine3"} |
| 864 | }), |
| 865 | ); |
| 866 | assert_eq!(event.body_html.as_deref(), Some("Line1<br>Line2<br>Line3")); |
| 867 | } |
| 868 | |
| 869 | #[test] |
| 870 | fn details_clear_a_removed_location_and_attendees() { |
| 871 | let mut event = CalendarEvent { |
| 872 | object_id: "stale".into(), |
| 873 | location: Some("Room 1".into()), |
| 874 | attendees: vec![EventAttendee { |
| 875 | name: "Someone".into(), |
| 876 | address: None, |
| 877 | response: ResponseType::Accepted, |
| 878 | required: true, |
| 879 | }], |
| 880 | response_counts: Some(AttendeeResponseCounts { |
| 881 | accepted: 1, |
| 882 | ..Default::default() |
| 883 | }), |
| 884 | ..Default::default() |
| 885 | }; |
| 886 | apply_event_details(&mut event, &serde_json::json!({"subject": "kept"})); |
| 887 | assert_eq!(event.location.as_deref(), Some("Room 1")); |
| 888 | assert_eq!(event.attendees.len(), 1); |
| 889 | apply_event_details( |
| 890 | &mut event, |
| 891 | &serde_json::json!({"location": {"displayName": ""}, "attendees": []}), |
| 892 | ); |
| 893 | assert_eq!(event.location, None); |
| 894 | assert!(event.attendees.is_empty()); |
| 895 | assert_eq!(event.response_counts, None); |
| 896 | } |
| 897 | |
| 898 | #[test] |
| 899 | fn apply_event_details_uses_body_content_when_preview_missing() { |
| 900 | let mut event = CalendarEvent { |
| 901 | object_id: "b".into(), |
| 902 | start: Utc.with_ymd_and_hms(2026, 10, 12, 8, 30, 0).unwrap(), |
| 903 | end: Utc.with_ymd_and_hms(2026, 10, 12, 9, 0, 0).unwrap(), |
| 904 | ..Default::default() |
| 905 | }; |
| 906 | apply_event_details( |
| 907 | &mut event, |
| 908 | &serde_json::json!({ |
| 909 | "body": {"contentType": "html", "content": "<p>NEUE TERMINE!!!!!</p><p>Agenda</p>"}, |
| 910 | "attendees": [{"status": {"response": "accepted"}}] |
| 911 | }), |
| 912 | ); |
| 913 | assert_eq!( |
| 914 | event.body_preview.as_deref(), |
| 915 | Some("NEUE TERMINE!!!!! Agenda") |
| 916 | ); |
| 917 | assert_eq!( |
| 918 | event.body_html.as_deref(), |
| 919 | Some("<p>NEUE TERMINE!!!!!</p><p>Agenda</p>") |
| 920 | ); |
| 921 | } |
| 922 | |
| 923 | #[test] |
| 924 | fn attendees_parse_graph_and_teams_shapes() { |
| 925 | let mut event = CalendarEvent::default(); |
| 926 | apply_event_details( |
| 927 | &mut event, |
| 928 | &serde_json::json!({ |
| 929 | "attendees": [ |
| 930 | {"emailAddress": {"name": "Ada", "address": "ada@x.ch"}, |
| 931 | "status": {"response": "accepted"}, "type": "required"}, |
| 932 | {"name": "Bob", "address": "bob@x.ch", |
| 933 | "status": {"response": "NotResponded"}, "type": "Optional"}, |
| 934 | {"address": "eve@x.ch", "status": {"response": "Declined"}} |
| 935 | ] |
| 936 | }), |
| 937 | ); |
| 938 | let roster: Vec<_> = event |
| 939 | .attendees |
| 940 | .iter() |
| 941 | .map(|a| (a.name.as_str(), a.response, a.required)) |
| 942 | .collect(); |
| 943 | assert_eq!( |
| 944 | roster, |
| 945 | vec![ |
| 946 | ("Ada", ResponseType::Accepted, true), |
| 947 | ("Bob", ResponseType::NotResponded, false), |
| 948 | ("eve@x.ch", ResponseType::Declined, true), |
| 949 | ] |
| 950 | ); |
| 951 | } |
| 952 | |
| 953 | #[test] |
| 954 | fn plain_text_body_becomes_escaped_html() { |
| 955 | let mut event = CalendarEvent::default(); |
| 956 | apply_event_details( |
| 957 | &mut event, |
| 958 | &serde_json::json!({"body": {"contentType": "text", "content": "a < b\r\nnext"}}), |
| 959 | ); |
| 960 | assert_eq!(event.body_html.as_deref(), Some("a < b<br>next")); |
| 961 | } |
| 962 | |
| 963 | #[test] |
| 964 | fn zone_less_times_and_embedded_thread_data_are_understood() { |
| 965 | let events = parse_calendar_events(&fixture()); |
| 966 | let review = &events[2]; |
| 967 | assert_eq!(review.response, ResponseType::Tentative); |
| 968 | assert_eq!( |
| 969 | review.thread_id.as_deref(), |
| 970 | Some("19:meeting_demo2@thread.v2") |
| 971 | ); |
| 972 | assert_eq!( |
| 973 | review.start, |
| 974 | Utc.with_ymd_and_hms(2026, 10, 12, 13, 0, 0).unwrap() |
| 975 | ); |
| 976 | assert!(events[3].cancelled); |
| 977 | } |
| 978 | |
| 979 | #[test] |
| 980 | fn the_organizer_flag_and_calendar_uid_are_read() { |
| 981 | let body = serde_json::json!({"value": [{ |
| 982 | "objectId": "a", |
| 983 | "startTime": "2026-10-12T08:30:00Z", |
| 984 | "endTime": "2026-10-12T09:00:00Z", |
| 985 | "isOrganizer": true, |
| 986 | "myResponseType": "Accepted", |
| 987 | "iCalUid": "uid-a" |
| 988 | }]}); |
| 989 | let events = parse_calendar_events(&body); |
| 990 | assert_eq!(events[0].response, ResponseType::Organizer); |
| 991 | assert_eq!(events[0].ical_uid.as_deref(), Some("uid-a")); |
| 992 | } |
| 993 | |
| 994 | #[test] |
| 995 | fn the_free_busy_status_is_read_and_defaults_to_busy() { |
| 996 | let entry = |show_as: &str| { |
| 997 | serde_json::json!({ |
| 998 | "objectId": show_as, |
| 999 | "startTime": "2026-10-12T08:30:00Z", |
| 1000 | "endTime": "2026-10-12T09:00:00Z", |
| 1001 | "showAs": show_as |
| 1002 | }) |
| 1003 | }; |
| 1004 | let body = serde_json::json!({"value": [entry("Free"), entry("Tentative"), entry("Oof"), entry("Unknown")]}); |
| 1005 | let statuses: Vec<ShowAs> = parse_calendar_events(&body) |
| 1006 | .iter() |
| 1007 | .map(|event| event.show_as) |
| 1008 | .collect(); |
| 1009 | assert_eq!( |
| 1010 | statuses, |
| 1011 | [ |
| 1012 | ShowAs::Free, |
| 1013 | ShowAs::Tentative, |
| 1014 | ShowAs::OutOfOffice, |
| 1015 | ShowAs::Busy |
| 1016 | ] |
| 1017 | ); |
| 1018 | } |
| 1019 | |
| 1020 | #[test] |
| 1021 | fn entries_without_an_id_or_times_are_skipped() { |
| 1022 | let body = |
| 1023 | serde_json::json!({"value": [{"subject": "x"}, {"objectId": "a", "subject": "y"}]}); |
| 1024 | assert!(parse_calendar_events(&body).is_empty()); |
| 1025 | } |
| 1026 | |
| 1027 | #[tokio::test] |
| 1028 | async fn calendar_view_gets_the_range_with_the_spaces_scope() { |
| 1029 | let calendar = Calendar::with_transport( |
| 1030 | Canned { |
| 1031 | body: fixture(), |
| 1032 | sent: Mutex::new(Vec::new()), |
| 1033 | }, |
| 1034 | "emea", |
| 1035 | ); |
| 1036 | let start = Utc.with_ymd_and_hms(2026, 10, 12, 0, 0, 0).unwrap(); |
| 1037 | let events = calendar |
| 1038 | .calendar_view(start, start + Duration::days(7)) |
| 1039 | .await |
| 1040 | .unwrap(); |
| 1041 | assert_eq!(events.len(), 4); |
| 1042 | let sent = calendar.transport.sent.lock().unwrap(); |
| 1043 | assert_eq!( |
| 1044 | sent[0].0.url, |
| 1045 | "https://teams.cloud.microsoft/api/mt/emea/v2.1/me/calendars/calendarView?startDate=2026-10-12T00:00:00Z&endDate=2026-10-19T00:00:00Z" |
| 1046 | ); |
| 1047 | assert_eq!(sent[0].1, spaces_scope()); |
| 1048 | } |
| 1049 | } |