| 1 | use chrono::{DateTime, Datelike, NaiveDateTime, Utc, Weekday}; |
| 2 | use serde_json::{Value, json}; |
| 3 | use session::{GRAPH, Method, Request, Scope}; |
| 4 | |
| 5 | use super::Calendar; |
| 6 | use crate::cards::CardTransport; |
| 7 | use crate::error::{Error, Result}; |
| 8 | use crate::messages::encode; |
| 9 | |
| 10 | pub(super) const CALENDARS_SCOPE: &str = "Calendars.ReadWrite"; |
| 11 | const GRAPH_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S"; |
| 12 | const GRAPH_DATE_FORMAT: &str = "%Y-%m-%d"; |
| 13 | const TIME_ZONE: &str = "UTC"; |
| 14 | const ONLINE_PROVIDER: &str = "teamsForBusiness"; |
| 15 | const NOT_FOUND: u16 = 404; |
| 16 | const WORK_WEEK: [Weekday; 5] = [ |
| 17 | Weekday::Mon, |
| 18 | Weekday::Tue, |
| 19 | Weekday::Wed, |
| 20 | Weekday::Thu, |
| 21 | Weekday::Fri, |
| 22 | ]; |
| 23 | |
| 24 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 25 | pub enum Repeat { |
| 26 | #[default] |
| 27 | Never, |
| 28 | Daily, |
| 29 | Weekdays, |
| 30 | Weekly, |
| 31 | } |
| 32 | |
| 33 | impl Repeat { |
| 34 | pub const ALL: [Repeat; 4] = [ |
| 35 | Repeat::Never, |
| 36 | Repeat::Daily, |
| 37 | Repeat::Weekdays, |
| 38 | Repeat::Weekly, |
| 39 | ]; |
| 40 | |
| 41 | pub fn label(self) -> &'static str { |
| 42 | match self { |
| 43 | Repeat::Never => "Does not repeat", |
| 44 | Repeat::Daily => "Daily", |
| 45 | Repeat::Weekdays => "Weekdays", |
| 46 | Repeat::Weekly => "Weekly", |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 52 | pub struct Attendee { |
| 53 | pub name: String, |
| 54 | pub address: String, |
| 55 | } |
| 56 | |
| 57 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 58 | pub struct NewEvent { |
| 59 | pub subject: String, |
| 60 | pub start: DateTime<Utc>, |
| 61 | pub end: DateTime<Utc>, |
| 62 | pub local_start: NaiveDateTime, |
| 63 | pub local_end: NaiveDateTime, |
| 64 | pub time_zone_name: Option<String>, |
| 65 | pub attendees: Vec<Attendee>, |
| 66 | pub repeat: Repeat, |
| 67 | pub details: String, |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 71 | pub struct CreatedEvent { |
| 72 | pub id: String, |
| 73 | pub join_url: Option<String>, |
| 74 | } |
| 75 | |
| 76 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 77 | pub enum Reply { |
| 78 | Accept, |
| 79 | Tentative, |
| 80 | Decline, |
| 81 | } |
| 82 | |
| 83 | impl Reply { |
| 84 | fn action(self) -> &'static str { |
| 85 | match self { |
| 86 | Reply::Accept => "accept", |
| 87 | Reply::Tentative => "tentativelyAccept", |
| 88 | Reply::Decline => "decline", |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | fn day_name(weekday: Weekday) -> &'static str { |
| 94 | match weekday { |
| 95 | Weekday::Mon => "monday", |
| 96 | Weekday::Tue => "tuesday", |
| 97 | Weekday::Wed => "wednesday", |
| 98 | Weekday::Thu => "thursday", |
| 99 | Weekday::Fri => "friday", |
| 100 | Weekday::Sat => "saturday", |
| 101 | Weekday::Sun => "sunday", |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | fn graph_time(event: &NewEvent, local: NaiveDateTime, utc: DateTime<Utc>) -> Value { |
| 106 | match &event.time_zone_name { |
| 107 | Some(time_zone_name) => json!({ |
| 108 | "dateTime": local.format(GRAPH_TIME_FORMAT).to_string(), |
| 109 | "timeZone": time_zone_name, |
| 110 | }), |
| 111 | None => json!({ |
| 112 | "dateTime": utc.format(GRAPH_TIME_FORMAT).to_string(), |
| 113 | "timeZone": TIME_ZONE, |
| 114 | }), |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | fn recurrence(repeat: Repeat, start: NaiveDateTime) -> Option<Value> { |
| 119 | let (pattern_type, days): (&str, Vec<Weekday>) = match repeat { |
| 120 | Repeat::Never => return None, |
| 121 | Repeat::Daily => ("daily", Vec::new()), |
| 122 | Repeat::Weekdays => ("weekly", WORK_WEEK.to_vec()), |
| 123 | Repeat::Weekly => ("weekly", vec![start.weekday()]), |
| 124 | }; |
| 125 | let mut pattern = json!({"type": pattern_type, "interval": 1}); |
| 126 | if !days.is_empty() { |
| 127 | pattern["daysOfWeek"] = days.into_iter().map(day_name).collect(); |
| 128 | pattern["firstDayOfWeek"] = json!("monday"); |
| 129 | } |
| 130 | Some(json!({ |
| 131 | "pattern": pattern, |
| 132 | "range": { |
| 133 | "type": "noEnd", |
| 134 | "startDate": start.format(GRAPH_DATE_FORMAT).to_string(), |
| 135 | }, |
| 136 | })) |
| 137 | } |
| 138 | |
| 139 | pub fn new_event_body(event: &NewEvent) -> Value { |
| 140 | let mut body = json!({ |
| 141 | "subject": event.subject, |
| 142 | "start": graph_time(event, event.local_start, event.start), |
| 143 | "end": graph_time(event, event.local_end, event.end), |
| 144 | "attendees": event.attendees.iter().map(|attendee| json!({ |
| 145 | "type": "required", |
| 146 | "emailAddress": {"address": attendee.address, "name": attendee.name}, |
| 147 | })).collect::<Vec<_>>(), |
| 148 | "isOnlineMeeting": true, |
| 149 | "onlineMeetingProvider": ONLINE_PROVIDER, |
| 150 | }); |
| 151 | if !event.details.trim().is_empty() { |
| 152 | body["body"] = json!({"contentType": "text", "content": event.details}); |
| 153 | } |
| 154 | if let Some(recurrence) = recurrence(event.repeat, event.local_start) { |
| 155 | body["recurrence"] = recurrence; |
| 156 | } |
| 157 | body |
| 158 | } |
| 159 | |
| 160 | /// Outlook insert when the Teams join URL already exists (multi-target create). |
| 161 | pub fn new_event_body_with_join(event: &NewEvent, join_url: &str) -> Value { |
| 162 | let mut details = event.details.clone(); |
| 163 | if !details.is_empty() { |
| 164 | details.push_str("\n\n"); |
| 165 | } |
| 166 | details.push_str(join_url); |
| 167 | let mut body = json!({ |
| 168 | "subject": event.subject, |
| 169 | "start": graph_time(event, event.local_start, event.start), |
| 170 | "end": graph_time(event, event.local_end, event.end), |
| 171 | "attendees": event.attendees.iter().map(|attendee| json!({ |
| 172 | "type": "required", |
| 173 | "emailAddress": {"address": attendee.address, "name": attendee.name}, |
| 174 | })).collect::<Vec<_>>(), |
| 175 | "location": {"displayName": join_url}, |
| 176 | "body": {"contentType": "text", "content": details}, |
| 177 | "isOnlineMeeting": false, |
| 178 | }); |
| 179 | if let Some(recurrence) = recurrence(event.repeat, event.local_start) { |
| 180 | body["recurrence"] = recurrence; |
| 181 | } |
| 182 | body |
| 183 | } |
| 184 | |
| 185 | pub fn parse_created_event(body: &Value) -> Option<CreatedEvent> { |
| 186 | Some(CreatedEvent { |
| 187 | id: body.get("id")?.as_str()?.to_owned(), |
| 188 | join_url: body |
| 189 | .pointer("/onlineMeeting/joinUrl") |
| 190 | .and_then(Value::as_str) |
| 191 | .map(str::to_owned), |
| 192 | }) |
| 193 | } |
| 194 | |
| 195 | fn events_url() -> String { |
| 196 | format!("{GRAPH}/v1.0/me/events") |
| 197 | } |
| 198 | |
| 199 | fn event_item_url(event_id: &str) -> String { |
| 200 | format!("{}/{}", events_url(), encode(event_id)) |
| 201 | } |
| 202 | |
| 203 | // Include `body` — series occurrences often have an empty bodyPreview while the |
| 204 | // full HTML agenda lives in body.content (body_preview_text already falls back). |
| 205 | const EVENT_DETAIL_SELECT: &str = "id,subject,body,bodyPreview,location,attendees,type,seriesMasterId,isOnlineMeeting,onlineMeeting,organizer,isAllDay,isCancelled"; |
| 206 | |
| 207 | fn event_details_url(event_id: &str) -> String { |
| 208 | format!( |
| 209 | "{}?$select={}", |
| 210 | event_item_url(event_id), |
| 211 | encode(EVENT_DETAIL_SELECT) |
| 212 | ) |
| 213 | } |
| 214 | |
| 215 | fn reply_url(event_id: &str, reply: Reply) -> String { |
| 216 | format!("{}/{}", event_item_url(event_id), reply.action()) |
| 217 | } |
| 218 | |
| 219 | fn lookup_url(ical_uid: &str) -> String { |
| 220 | format!( |
| 221 | "{}?$filter={}&$select=id&$top=1", |
| 222 | events_url(), |
| 223 | encode(&format!("iCalUId eq '{}'", ical_uid.replace('\'', "''"))) |
| 224 | ) |
| 225 | } |
| 226 | |
| 227 | fn api_error(answer: session::ApiResponse, url: &str) -> Error { |
| 228 | Error::Session(session::Error::api(answer.status, url, answer.body)) |
| 229 | } |
| 230 | |
| 231 | fn details_have_agenda(entry: &Value) -> bool { |
| 232 | entry |
| 233 | .get("bodyPreview") |
| 234 | .and_then(Value::as_str) |
| 235 | .is_some_and(|value| !value.trim().is_empty()) |
| 236 | || entry |
| 237 | .get("bodyContent") |
| 238 | .and_then(Value::as_str) |
| 239 | .is_some_and(|value| !value.trim().is_empty()) |
| 240 | || entry |
| 241 | .pointer("/body/content") |
| 242 | .and_then(Value::as_str) |
| 243 | .is_some_and(|value| !value.trim().is_empty()) |
| 244 | } |
| 245 | |
| 246 | fn merge_detail_bodies(mut graph: Value, teams: Value) -> Value { |
| 247 | if let Some(content) = teams.get("bodyContent").cloned() { |
| 248 | match graph.as_object_mut() { |
| 249 | Some(map) => { |
| 250 | map.entry("bodyContent").or_insert(content); |
| 251 | } |
| 252 | None => return teams, |
| 253 | } |
| 254 | } |
| 255 | if let Some(attendees) = teams.get("attendees").cloned() { |
| 256 | if graph |
| 257 | .get("attendees") |
| 258 | .and_then(Value::as_array) |
| 259 | .is_none_or(|a| a.is_empty()) |
| 260 | { |
| 261 | if let Some(map) = graph.as_object_mut() { |
| 262 | map.insert("attendees".into(), attendees); |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | graph |
| 267 | } |
| 268 | |
| 269 | impl<T: CardTransport> Calendar<T> { |
| 270 | pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> { |
| 271 | self.create_event_body(event, new_event_body(event)).await |
| 272 | } |
| 273 | |
| 274 | pub async fn create_event_with_join( |
| 275 | &self, |
| 276 | event: &NewEvent, |
| 277 | join_url: &str, |
| 278 | ) -> Result<CreatedEvent> { |
| 279 | let mut created = self |
| 280 | .create_event_body(event, new_event_body_with_join(event, join_url)) |
| 281 | .await?; |
| 282 | if created.join_url.is_none() { |
| 283 | created.join_url = Some(join_url.to_owned()); |
| 284 | } |
| 285 | Ok(created) |
| 286 | } |
| 287 | |
| 288 | async fn create_event_body(&self, event: &NewEvent, body: Value) -> Result<CreatedEvent> { |
| 289 | let _ = event; |
| 290 | let url = events_url(); |
| 291 | let request = Request::with_body(Method::Post, &url, body); |
| 292 | let answer = self |
| 293 | .transport |
| 294 | .send(request, Scope::graph(CALENDARS_SCOPE)) |
| 295 | .await?; |
| 296 | if !answer.is_success() { |
| 297 | return Err(api_error(answer, &url)); |
| 298 | } |
| 299 | parse_created_event(&answer.body).ok_or_else(|| api_error(answer, &url)) |
| 300 | } |
| 301 | |
| 302 | pub async fn respond( |
| 303 | &self, |
| 304 | event_id: &str, |
| 305 | ical_uid: Option<&str>, |
| 306 | reply: Reply, |
| 307 | send_response: bool, |
| 308 | comment: &str, |
| 309 | ) -> Result<()> { |
| 310 | let answer = self |
| 311 | .send_reply(event_id, reply, send_response, comment) |
| 312 | .await?; |
| 313 | if answer.is_success() { |
| 314 | return Ok(()); |
| 315 | } |
| 316 | let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else { |
| 317 | return Err(api_error(answer, &reply_url(event_id, reply))); |
| 318 | }; |
| 319 | let graph_id = self.graph_event_id(ical_uid).await?; |
| 320 | let retried = self |
| 321 | .send_reply(&graph_id, reply, send_response, comment) |
| 322 | .await?; |
| 323 | if retried.is_success() { |
| 324 | return Ok(()); |
| 325 | } |
| 326 | Err(api_error(retried, &reply_url(&graph_id, reply))) |
| 327 | } |
| 328 | |
| 329 | pub async fn event_details(&self, event_id: &str, ical_uid: Option<&str>) -> Result<Value> { |
| 330 | let answer = self.fetch_event(event_id).await?; |
| 331 | if answer.is_success() { |
| 332 | if details_have_agenda(&answer.body) { |
| 333 | return Ok(answer.body); |
| 334 | } |
| 335 | // Graph can return RSVP fields with an empty body on occurrences; |
| 336 | // Teams MT beta carries bodyContent + attendees for the same objectId. |
| 337 | if let Ok(teams) = self.fetch_teams_event(event_id).await { |
| 338 | if teams.is_success() && details_have_agenda(&teams.body) { |
| 339 | return Ok(merge_detail_bodies(answer.body, teams.body)); |
| 340 | } |
| 341 | } |
| 342 | return Ok(answer.body); |
| 343 | } |
| 344 | if let Ok(teams) = self.fetch_teams_event(event_id).await { |
| 345 | if teams.is_success() { |
| 346 | return Ok(teams.body); |
| 347 | } |
| 348 | } |
| 349 | let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else { |
| 350 | return Err(api_error(answer, &event_details_url(event_id))); |
| 351 | }; |
| 352 | let graph_id = self.graph_event_id(ical_uid).await?; |
| 353 | let retried = self.fetch_event(&graph_id).await?; |
| 354 | if retried.is_success() { |
| 355 | return Ok(retried.body); |
| 356 | } |
| 357 | Err(api_error(retried, &event_details_url(&graph_id))) |
| 358 | } |
| 359 | |
| 360 | async fn fetch_teams_event(&self, event_id: &str) -> Result<session::ApiResponse> { |
| 361 | let url = self.teams_event_url(event_id); |
| 362 | self.transport |
| 363 | .send(Request::get(&url), crate::cards::spaces_scope()) |
| 364 | .await |
| 365 | } |
| 366 | |
| 367 | pub async fn delete_event(&self, event_id: &str, ical_uid: Option<&str>) -> Result<()> { |
| 368 | let answer = self.send_delete(event_id).await?; |
| 369 | if answer.is_success() { |
| 370 | return Ok(()); |
| 371 | } |
| 372 | let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else { |
| 373 | return Err(api_error(answer, &event_item_url(event_id))); |
| 374 | }; |
| 375 | let graph_id = self.graph_event_id(ical_uid).await?; |
| 376 | let retried = self.send_delete(&graph_id).await?; |
| 377 | if retried.is_success() { |
| 378 | return Ok(()); |
| 379 | } |
| 380 | Err(api_error(retried, &event_item_url(&graph_id))) |
| 381 | } |
| 382 | |
| 383 | async fn send_delete(&self, event_id: &str) -> Result<session::ApiResponse> { |
| 384 | self.transport |
| 385 | .send( |
| 386 | Request::delete(event_item_url(event_id)), |
| 387 | Scope::graph(CALENDARS_SCOPE), |
| 388 | ) |
| 389 | .await |
| 390 | } |
| 391 | |
| 392 | async fn send_reply( |
| 393 | &self, |
| 394 | event_id: &str, |
| 395 | reply: Reply, |
| 396 | send_response: bool, |
| 397 | comment: &str, |
| 398 | ) -> Result<session::ApiResponse> { |
| 399 | let request = Request::with_body( |
| 400 | Method::Post, |
| 401 | reply_url(event_id, reply), |
| 402 | json!({ |
| 403 | "comment": if send_response { comment } else { "" }, |
| 404 | "sendResponse": send_response, |
| 405 | }), |
| 406 | ); |
| 407 | self.transport |
| 408 | .send(request, Scope::graph(CALENDARS_SCOPE)) |
| 409 | .await |
| 410 | } |
| 411 | |
| 412 | async fn fetch_event(&self, event_id: &str) -> Result<session::ApiResponse> { |
| 413 | self.transport |
| 414 | .send( |
| 415 | Request::get(event_details_url(event_id)), |
| 416 | Scope::graph(CALENDARS_SCOPE), |
| 417 | ) |
| 418 | .await |
| 419 | } |
| 420 | |
| 421 | async fn graph_event_id(&self, ical_uid: &str) -> Result<String> { |
| 422 | let url = lookup_url(ical_uid); |
| 423 | let answer = self |
| 424 | .transport |
| 425 | .send(Request::get(&url), Scope::graph(CALENDARS_SCOPE)) |
| 426 | .await?; |
| 427 | if !answer.is_success() { |
| 428 | return Err(api_error(answer, &url)); |
| 429 | } |
| 430 | answer |
| 431 | .body |
| 432 | .pointer("/value/0/id") |
| 433 | .and_then(Value::as_str) |
| 434 | .map(str::to_owned) |
| 435 | .ok_or_else(|| api_error(answer, &url)) |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | #[cfg(test)] |
| 440 | mod tests { |
| 441 | use std::sync::Mutex; |
| 442 | |
| 443 | use chrono::TimeZone; |
| 444 | |
| 445 | use super::*; |
| 446 | use crate::calendar::Calendar; |
| 447 | |
| 448 | struct Scripted { |
| 449 | answers: Mutex<Vec<(u16, Value)>>, |
| 450 | sent: Mutex<Vec<(Method, String, Option<Value>)>>, |
| 451 | } |
| 452 | |
| 453 | impl Scripted { |
| 454 | fn new(answers: Vec<(u16, Value)>) -> Self { |
| 455 | Scripted { |
| 456 | answers: Mutex::new(answers), |
| 457 | sent: Mutex::new(Vec::new()), |
| 458 | } |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | impl CardTransport for Scripted { |
| 463 | async fn send(&self, request: Request, scope: Scope) -> Result<session::ApiResponse> { |
| 464 | let graph = Scope::graph(CALENDARS_SCOPE); |
| 465 | let spaces = crate::cards::spaces_scope(); |
| 466 | assert!( |
| 467 | scope == graph || scope == spaces, |
| 468 | "unexpected scope {scope:?}" |
| 469 | ); |
| 470 | self.sent |
| 471 | .lock() |
| 472 | .unwrap() |
| 473 | .push((request.method, request.url, request.body)); |
| 474 | let (status, body) = self.answers.lock().unwrap().remove(0); |
| 475 | Ok(session::ApiResponse { |
| 476 | status, |
| 477 | body, |
| 478 | retry_after: None, |
| 479 | }) |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | fn local(year: i32, month: u32, day: u32, hour: u32, minute: u32) -> NaiveDateTime { |
| 484 | chrono::NaiveDate::from_ymd_opt(year, month, day) |
| 485 | .unwrap() |
| 486 | .and_hms_opt(hour, minute, 0) |
| 487 | .unwrap() |
| 488 | } |
| 489 | |
| 490 | fn zoned(repeat: Repeat, local_start: NaiveDateTime, offset_hours: i64) -> NewEvent { |
| 491 | let utc_start = local_start.and_utc() - chrono::Duration::hours(offset_hours); |
| 492 | NewEvent { |
| 493 | start: utc_start, |
| 494 | end: utc_start + chrono::Duration::minutes(30), |
| 495 | local_start, |
| 496 | local_end: local_start + chrono::Duration::minutes(30), |
| 497 | time_zone_name: Some("W. Europe Standard Time".into()), |
| 498 | ..event(repeat) |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | fn event(repeat: Repeat) -> NewEvent { |
| 503 | NewEvent { |
| 504 | subject: "Planning".into(), |
| 505 | start: Utc.with_ymd_and_hms(2026, 10, 14, 9, 30, 0).unwrap(), |
| 506 | end: Utc.with_ymd_and_hms(2026, 10, 14, 10, 0, 0).unwrap(), |
| 507 | local_start: local(2026, 10, 14, 11, 30), |
| 508 | local_end: local(2026, 10, 14, 12, 0), |
| 509 | time_zone_name: None, |
| 510 | attendees: vec![Attendee { |
| 511 | name: "Mara Lindqvist".into(), |
| 512 | address: "mara@example.invalid".into(), |
| 513 | }], |
| 514 | repeat, |
| 515 | details: String::new(), |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | #[test] |
| 520 | fn join_first_body_puts_link_in_location_without_online_meeting() { |
| 521 | let body = new_event_body_with_join( |
| 522 | &event(Repeat::Never), |
| 523 | "https://teams.microsoft.com/l/meetup-join/x", |
| 524 | ); |
| 525 | assert_eq!(body["isOnlineMeeting"], false); |
| 526 | assert_eq!( |
| 527 | body["location"]["displayName"], |
| 528 | "https://teams.microsoft.com/l/meetup-join/x" |
| 529 | ); |
| 530 | assert!( |
| 531 | body["body"]["content"] |
| 532 | .as_str() |
| 533 | .unwrap() |
| 534 | .contains("teams.microsoft.com") |
| 535 | ); |
| 536 | } |
| 537 | |
| 538 | #[test] |
| 539 | fn the_body_asks_for_a_teams_meeting_with_utc_times() { |
| 540 | let body = new_event_body(&event(Repeat::Never)); |
| 541 | assert_eq!(body["subject"], "Planning"); |
| 542 | assert_eq!(body["isOnlineMeeting"], true); |
| 543 | assert_eq!(body["onlineMeetingProvider"], "teamsForBusiness"); |
| 544 | assert_eq!(body["start"]["dateTime"], "2026-10-14T09:30:00"); |
| 545 | assert_eq!(body["start"]["timeZone"], "UTC"); |
| 546 | assert_eq!(body["end"]["dateTime"], "2026-10-14T10:00:00"); |
| 547 | assert_eq!(body["attendees"][0]["type"], "required"); |
| 548 | assert_eq!( |
| 549 | body["attendees"][0]["emailAddress"]["address"], |
| 550 | "mara@example.invalid" |
| 551 | ); |
| 552 | assert!(body.get("recurrence").is_none()); |
| 553 | assert!(body.get("body").is_none()); |
| 554 | } |
| 555 | |
| 556 | #[test] |
| 557 | fn summer_and_winter_series_keep_the_same_local_time() { |
| 558 | let summer = new_event_body(&zoned(Repeat::Weekly, local(2026, 7, 15, 9, 0), 2)); |
| 559 | let winter = new_event_body(&zoned(Repeat::Weekly, local(2026, 12, 16, 9, 0), 1)); |
| 560 | assert_eq!(summer["start"]["dateTime"], "2026-07-15T09:00:00"); |
| 561 | assert_eq!(winter["start"]["dateTime"], "2026-12-16T09:00:00"); |
| 562 | for body in [&summer, &winter] { |
| 563 | assert_eq!(body["start"]["timeZone"], "W. Europe Standard Time"); |
| 564 | assert_eq!(body["end"]["dateTime"].as_str().unwrap()[11..], *"09:30:00"); |
| 565 | assert_eq!(body["end"]["timeZone"], "W. Europe Standard Time"); |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | #[test] |
| 570 | fn a_local_half_past_midnight_keeps_its_local_weekday_and_start_date() { |
| 571 | let body = new_event_body(&zoned(Repeat::Weekly, local(2026, 10, 14, 0, 30), 2)); |
| 572 | assert_eq!(body["start"]["dateTime"], "2026-10-14T00:30:00"); |
| 573 | assert_eq!(body["recurrence"]["range"]["startDate"], "2026-10-14"); |
| 574 | assert_eq!( |
| 575 | body["recurrence"]["pattern"]["daysOfWeek"], |
| 576 | json!(["wednesday"]) |
| 577 | ); |
| 578 | } |
| 579 | |
| 580 | #[test] |
| 581 | fn without_a_zone_name_times_stay_utc_but_the_date_is_local() { |
| 582 | let event = NewEvent { |
| 583 | start: Utc.with_ymd_and_hms(2026, 10, 13, 22, 30, 0).unwrap(), |
| 584 | end: Utc.with_ymd_and_hms(2026, 10, 13, 23, 0, 0).unwrap(), |
| 585 | local_start: local(2026, 10, 14, 0, 30), |
| 586 | local_end: local(2026, 10, 14, 1, 0), |
| 587 | ..event(Repeat::Weekly) |
| 588 | }; |
| 589 | let body = new_event_body(&event); |
| 590 | assert_eq!(body["start"]["dateTime"], "2026-10-13T22:30:00"); |
| 591 | assert_eq!(body["start"]["timeZone"], "UTC"); |
| 592 | assert_eq!(body["recurrence"]["range"]["startDate"], "2026-10-14"); |
| 593 | assert_eq!( |
| 594 | body["recurrence"]["pattern"]["daysOfWeek"], |
| 595 | json!(["wednesday"]) |
| 596 | ); |
| 597 | } |
| 598 | |
| 599 | #[test] |
| 600 | fn details_become_a_plain_text_body() { |
| 601 | let body = new_event_body(&NewEvent { |
| 602 | details: "Agenda: roadmap".into(), |
| 603 | ..event(Repeat::Never) |
| 604 | }); |
| 605 | assert_eq!(body["body"]["contentType"], "text"); |
| 606 | assert_eq!(body["body"]["content"], "Agenda: roadmap"); |
| 607 | } |
| 608 | |
| 609 | #[test] |
| 610 | fn recurrence_maps_to_graph_patterns() { |
| 611 | let daily = new_event_body(&event(Repeat::Daily)); |
| 612 | assert_eq!(daily["recurrence"]["pattern"]["type"], "daily"); |
| 613 | assert_eq!(daily["recurrence"]["pattern"]["interval"], 1); |
| 614 | assert_eq!(daily["recurrence"]["range"]["type"], "noEnd"); |
| 615 | assert_eq!(daily["recurrence"]["range"]["startDate"], "2026-10-14"); |
| 616 | let weekdays = new_event_body(&event(Repeat::Weekdays)); |
| 617 | assert_eq!(weekdays["recurrence"]["pattern"]["type"], "weekly"); |
| 618 | assert_eq!( |
| 619 | weekdays["recurrence"]["pattern"]["daysOfWeek"], |
| 620 | json!(["monday", "tuesday", "wednesday", "thursday", "friday"]) |
| 621 | ); |
| 622 | let weekly = new_event_body(&event(Repeat::Weekly)); |
| 623 | assert_eq!( |
| 624 | weekly["recurrence"]["pattern"]["daysOfWeek"], |
| 625 | json!(["wednesday"]) |
| 626 | ); |
| 627 | } |
| 628 | |
| 629 | #[test] |
| 630 | fn the_created_event_carries_its_id_and_join_link() { |
| 631 | let body = |
| 632 | json!({"id": "AAMk", "onlineMeeting": {"joinUrl": "https://example.invalid/join"}}); |
| 633 | assert_eq!( |
| 634 | parse_created_event(&body), |
| 635 | Some(CreatedEvent { |
| 636 | id: "AAMk".into(), |
| 637 | join_url: Some("https://example.invalid/join".into()), |
| 638 | }) |
| 639 | ); |
| 640 | assert_eq!(parse_created_event(&json!({})), None); |
| 641 | } |
| 642 | |
| 643 | #[tokio::test] |
| 644 | async fn create_event_posts_to_graph_events() { |
| 645 | let calendar = |
| 646 | Calendar::with_transport(Scripted::new(vec![(201, json!({"id": "AAMk"}))]), "emea"); |
| 647 | let created = calendar.create_event(&event(Repeat::Never)).await.unwrap(); |
| 648 | assert_eq!(created.id, "AAMk"); |
| 649 | let sent = calendar.transport.sent.lock().unwrap(); |
| 650 | assert_eq!(sent[0].0, Method::Post); |
| 651 | assert_eq!(sent[0].1, "https://graph.microsoft.com/v1.0/me/events"); |
| 652 | } |
| 653 | |
| 654 | #[tokio::test] |
| 655 | async fn create_event_failure_carries_the_service_message() { |
| 656 | let calendar = Calendar::with_transport( |
| 657 | Scripted::new(vec![(403, json!({"error": {"message": "Access denied"}}))]), |
| 658 | "emea", |
| 659 | ); |
| 660 | let error = calendar |
| 661 | .create_event(&event(Repeat::Never)) |
| 662 | .await |
| 663 | .unwrap_err(); |
| 664 | assert!(error.to_string().contains("Access denied")); |
| 665 | } |
| 666 | |
| 667 | #[tokio::test] |
| 668 | async fn respond_posts_the_reply_with_the_send_flag() { |
| 669 | let calendar = Calendar::with_transport(Scripted::new(vec![(202, Value::Null)]), "emea"); |
| 670 | calendar |
| 671 | .respond("AAMk=", None, Reply::Tentative, false, "ignored") |
| 672 | .await |
| 673 | .unwrap(); |
| 674 | let sent = calendar.transport.sent.lock().unwrap(); |
| 675 | assert_eq!( |
| 676 | sent[0].1, |
| 677 | "https://graph.microsoft.com/v1.0/me/events/AAMk%3D/tentativelyAccept" |
| 678 | ); |
| 679 | assert_eq!( |
| 680 | sent[0].2, |
| 681 | Some(json!({"comment": "", "sendResponse": false})) |
| 682 | ); |
| 683 | } |
| 684 | |
| 685 | #[tokio::test] |
| 686 | async fn respond_includes_comment_when_sending() { |
| 687 | let calendar = Calendar::with_transport(Scripted::new(vec![(202, Value::Null)]), "emea"); |
| 688 | calendar |
| 689 | .respond("AAMk=", None, Reply::Accept, true, "See you there") |
| 690 | .await |
| 691 | .unwrap(); |
| 692 | let sent = calendar.transport.sent.lock().unwrap(); |
| 693 | assert_eq!( |
| 694 | sent[0].2, |
| 695 | Some(json!({"comment": "See you there", "sendResponse": true})) |
| 696 | ); |
| 697 | } |
| 698 | |
| 699 | #[tokio::test] |
| 700 | async fn event_details_gets_selected_fields() { |
| 701 | let calendar = Calendar::with_transport( |
| 702 | Scripted::new(vec![( |
| 703 | 200, |
| 704 | json!({ |
| 705 | "id": "AAMk=", |
| 706 | "bodyPreview": "Agenda", |
| 707 | "location": {"displayName": "Microsoft Teams Meeting"}, |
| 708 | "type": "occurrence", |
| 709 | "seriesMasterId": "master", |
| 710 | "attendees": [ |
| 711 | {"status": {"response": "accepted"}}, |
| 712 | {"status": {"response": "declined"}}, |
| 713 | {"status": {"response": "none"}}, |
| 714 | ] |
| 715 | }), |
| 716 | )]), |
| 717 | "emea", |
| 718 | ); |
| 719 | let body = calendar.event_details("AAMk=", None).await.unwrap(); |
| 720 | assert_eq!(body["bodyPreview"], "Agenda"); |
| 721 | let sent = calendar.transport.sent.lock().unwrap(); |
| 722 | assert_eq!(sent[0].0, Method::Get); |
| 723 | assert!(sent[0].1.contains("/me/events/AAMk%3D?")); |
| 724 | assert!(sent[0].1.contains("bodyPreview")); |
| 725 | assert!(sent[0].1.contains("body")); |
| 726 | } |
| 727 | |
| 728 | #[tokio::test] |
| 729 | async fn event_details_merges_teams_body_when_graph_agenda_empty() { |
| 730 | let calendar = Calendar::with_transport( |
| 731 | Scripted::new(vec![ |
| 732 | ( |
| 733 | 200, |
| 734 | json!({ |
| 735 | "id": "AAMk=", |
| 736 | "bodyPreview": "", |
| 737 | "attendees": [{"status": {"response": "accepted"}}] |
| 738 | }), |
| 739 | ), |
| 740 | ( |
| 741 | 200, |
| 742 | json!({ |
| 743 | "bodyContent": "<p>Daily agenda</p>", |
| 744 | "attendees": [ |
| 745 | {"status": {"response": "Accepted"}}, |
| 746 | {"status": {"response": "NotResponded"}}, |
| 747 | ] |
| 748 | }), |
| 749 | ), |
| 750 | ]), |
| 751 | "emea", |
| 752 | ); |
| 753 | let body = calendar.event_details("AAMk=", None).await.unwrap(); |
| 754 | assert_eq!(body["bodyContent"], "<p>Daily agenda</p>"); |
| 755 | let sent = calendar.transport.sent.lock().unwrap(); |
| 756 | assert!(sent[0].1.contains("graph.microsoft.com")); |
| 757 | assert!(sent[1].1.contains("/beta/me/calendarEvents/")); |
| 758 | } |
| 759 | |
| 760 | #[tokio::test] |
| 761 | async fn delete_event_sends_graph_delete() { |
| 762 | let calendar = Calendar::with_transport(Scripted::new(vec![(204, Value::Null)]), "emea"); |
| 763 | calendar.delete_event("AAMk=", None).await.unwrap(); |
| 764 | let sent = calendar.transport.sent.lock().unwrap(); |
| 765 | assert_eq!(sent[0].0, Method::Delete); |
| 766 | assert_eq!( |
| 767 | sent[0].1, |
| 768 | "https://graph.microsoft.com/v1.0/me/events/AAMk%3D" |
| 769 | ); |
| 770 | } |
| 771 | |
| 772 | #[tokio::test] |
| 773 | async fn an_unknown_id_is_looked_up_by_its_ical_uid_once() { |
| 774 | let calendar = Calendar::with_transport( |
| 775 | Scripted::new(vec![ |
| 776 | (404, json!({"error": {"message": "not found"}})), |
| 777 | (200, json!({"value": [{"id": "graph-id"}]})), |
| 778 | (202, Value::Null), |
| 779 | ]), |
| 780 | "emea", |
| 781 | ); |
| 782 | calendar |
| 783 | .respond("mt-id", Some("uid-1"), Reply::Decline, true, "") |
| 784 | .await |
| 785 | .unwrap(); |
| 786 | let sent = calendar.transport.sent.lock().unwrap(); |
| 787 | assert!(sent[1].1.contains("iCalUId%20eq%20'uid-1'")); |
| 788 | assert!(sent[2].1.ends_with("/graph-id/decline")); |
| 789 | } |
| 790 | |
| 791 | #[tokio::test] |
| 792 | async fn a_missing_event_without_an_ical_uid_fails() { |
| 793 | let calendar = Calendar::with_transport( |
| 794 | Scripted::new(vec![(404, json!({"error": {"message": "not found"}}))]), |
| 795 | "emea", |
| 796 | ); |
| 797 | assert!( |
| 798 | calendar |
| 799 | .respond("mt-id", None, Reply::Accept, true, "") |
| 800 | .await |
| 801 | .is_err() |
| 802 | ); |
| 803 | } |
| 804 | } |