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