| 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 | 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 | pub fn parse_created_event(body: &Value) -> Option<CreatedEvent> { |
| 161 | Some(CreatedEvent { |
| 162 | id: body.get("id")?.as_str()?.to_owned(), |
| 163 | join_url: body |
| 164 | .pointer("/onlineMeeting/joinUrl") |
| 165 | .and_then(Value::as_str) |
| 166 | .map(str::to_owned), |
| 167 | }) |
| 168 | } |
| 169 | |
| 170 | fn events_url() -> String { |
| 171 | format!("{GRAPH}/v1.0/me/events") |
| 172 | } |
| 173 | |
| 174 | fn reply_url(event_id: &str, reply: Reply) -> String { |
| 175 | format!("{}/{}/{}", events_url(), encode(event_id), reply.action()) |
| 176 | } |
| 177 | |
| 178 | fn lookup_url(ical_uid: &str) -> String { |
| 179 | format!( |
| 180 | "{}?$filter={}&$select=id&$top=1", |
| 181 | events_url(), |
| 182 | encode(&format!("iCalUId eq '{}'", ical_uid.replace('\'', "''"))) |
| 183 | ) |
| 184 | } |
| 185 | |
| 186 | fn api_error(answer: session::ApiResponse, url: &str) -> Error { |
| 187 | Error::Session(session::Error::api(answer.status, url, answer.body)) |
| 188 | } |
| 189 | |
| 190 | impl<T: CardTransport> Calendar<T> { |
| 191 | pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> { |
| 192 | let url = events_url(); |
| 193 | let request = Request::with_body(Method::Post, &url, new_event_body(event)); |
| 194 | let answer = self |
| 195 | .transport |
| 196 | .send(request, Scope::graph(CALENDARS_SCOPE)) |
| 197 | .await?; |
| 198 | if !answer.is_success() { |
| 199 | return Err(api_error(answer, &url)); |
| 200 | } |
| 201 | parse_created_event(&answer.body).ok_or_else(|| api_error(answer, &url)) |
| 202 | } |
| 203 | |
| 204 | pub async fn respond( |
| 205 | &self, |
| 206 | event_id: &str, |
| 207 | ical_uid: Option<&str>, |
| 208 | reply: Reply, |
| 209 | send_response: bool, |
| 210 | ) -> Result<()> { |
| 211 | let answer = self.send_reply(event_id, reply, send_response).await?; |
| 212 | if answer.is_success() { |
| 213 | return Ok(()); |
| 214 | } |
| 215 | let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else { |
| 216 | return Err(api_error(answer, &reply_url(event_id, reply))); |
| 217 | }; |
| 218 | let graph_id = self.graph_event_id(ical_uid).await?; |
| 219 | let retried = self.send_reply(&graph_id, reply, send_response).await?; |
| 220 | if retried.is_success() { |
| 221 | return Ok(()); |
| 222 | } |
| 223 | Err(api_error(retried, &reply_url(&graph_id, reply))) |
| 224 | } |
| 225 | |
| 226 | async fn send_reply( |
| 227 | &self, |
| 228 | event_id: &str, |
| 229 | reply: Reply, |
| 230 | send_response: bool, |
| 231 | ) -> Result<session::ApiResponse> { |
| 232 | let request = Request::with_body( |
| 233 | Method::Post, |
| 234 | reply_url(event_id, reply), |
| 235 | json!({"comment": "", "sendResponse": send_response}), |
| 236 | ); |
| 237 | self.transport |
| 238 | .send(request, Scope::graph(CALENDARS_SCOPE)) |
| 239 | .await |
| 240 | } |
| 241 | |
| 242 | async fn graph_event_id(&self, ical_uid: &str) -> Result<String> { |
| 243 | let url = lookup_url(ical_uid); |
| 244 | let answer = self |
| 245 | .transport |
| 246 | .send(Request::get(&url), Scope::graph(CALENDARS_SCOPE)) |
| 247 | .await?; |
| 248 | if !answer.is_success() { |
| 249 | return Err(api_error(answer, &url)); |
| 250 | } |
| 251 | answer |
| 252 | .body |
| 253 | .pointer("/value/0/id") |
| 254 | .and_then(Value::as_str) |
| 255 | .map(str::to_owned) |
| 256 | .ok_or_else(|| api_error(answer, &url)) |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | #[cfg(test)] |
| 261 | mod tests { |
| 262 | use std::sync::Mutex; |
| 263 | |
| 264 | use chrono::TimeZone; |
| 265 | |
| 266 | use super::*; |
| 267 | use crate::calendar::Calendar; |
| 268 | |
| 269 | struct Scripted { |
| 270 | answers: Mutex<Vec<(u16, Value)>>, |
| 271 | sent: Mutex<Vec<(Method, String, Option<Value>)>>, |
| 272 | } |
| 273 | |
| 274 | impl Scripted { |
| 275 | fn new(answers: Vec<(u16, Value)>) -> Self { |
| 276 | Scripted { |
| 277 | answers: Mutex::new(answers), |
| 278 | sent: Mutex::new(Vec::new()), |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | impl CardTransport for Scripted { |
| 284 | async fn send(&self, request: Request, scope: Scope) -> Result<session::ApiResponse> { |
| 285 | assert_eq!(scope, Scope::graph(CALENDARS_SCOPE)); |
| 286 | self.sent |
| 287 | .lock() |
| 288 | .unwrap() |
| 289 | .push((request.method, request.url, request.body)); |
| 290 | let (status, body) = self.answers.lock().unwrap().remove(0); |
| 291 | Ok(session::ApiResponse { |
| 292 | status, |
| 293 | body, |
| 294 | retry_after: None, |
| 295 | }) |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | fn local(year: i32, month: u32, day: u32, hour: u32, minute: u32) -> NaiveDateTime { |
| 300 | chrono::NaiveDate::from_ymd_opt(year, month, day) |
| 301 | .unwrap() |
| 302 | .and_hms_opt(hour, minute, 0) |
| 303 | .unwrap() |
| 304 | } |
| 305 | |
| 306 | fn zoned(repeat: Repeat, local_start: NaiveDateTime, offset_hours: i64) -> NewEvent { |
| 307 | let utc_start = local_start.and_utc() - chrono::Duration::hours(offset_hours); |
| 308 | NewEvent { |
| 309 | start: utc_start, |
| 310 | end: utc_start + chrono::Duration::minutes(30), |
| 311 | local_start, |
| 312 | local_end: local_start + chrono::Duration::minutes(30), |
| 313 | time_zone_name: Some("W. Europe Standard Time".into()), |
| 314 | ..event(repeat) |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | fn event(repeat: Repeat) -> NewEvent { |
| 319 | NewEvent { |
| 320 | subject: "Planning".into(), |
| 321 | start: Utc.with_ymd_and_hms(2026, 10, 14, 9, 30, 0).unwrap(), |
| 322 | end: Utc.with_ymd_and_hms(2026, 10, 14, 10, 0, 0).unwrap(), |
| 323 | local_start: local(2026, 10, 14, 11, 30), |
| 324 | local_end: local(2026, 10, 14, 12, 0), |
| 325 | time_zone_name: None, |
| 326 | attendees: vec![Attendee { |
| 327 | name: "Mara Lindqvist".into(), |
| 328 | address: "mara@example.invalid".into(), |
| 329 | }], |
| 330 | repeat, |
| 331 | details: String::new(), |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | #[test] |
| 336 | fn the_body_asks_for_a_teams_meeting_with_utc_times() { |
| 337 | let body = new_event_body(&event(Repeat::Never)); |
| 338 | assert_eq!(body["subject"], "Planning"); |
| 339 | assert_eq!(body["isOnlineMeeting"], true); |
| 340 | assert_eq!(body["onlineMeetingProvider"], "teamsForBusiness"); |
| 341 | assert_eq!(body["start"]["dateTime"], "2026-10-14T09:30:00"); |
| 342 | assert_eq!(body["start"]["timeZone"], "UTC"); |
| 343 | assert_eq!(body["end"]["dateTime"], "2026-10-14T10:00:00"); |
| 344 | assert_eq!(body["attendees"][0]["type"], "required"); |
| 345 | assert_eq!( |
| 346 | body["attendees"][0]["emailAddress"]["address"], |
| 347 | "mara@example.invalid" |
| 348 | ); |
| 349 | assert!(body.get("recurrence").is_none()); |
| 350 | assert!(body.get("body").is_none()); |
| 351 | } |
| 352 | |
| 353 | #[test] |
| 354 | fn summer_and_winter_series_keep_the_same_local_time() { |
| 355 | let summer = new_event_body(&zoned(Repeat::Weekly, local(2026, 7, 15, 9, 0), 2)); |
| 356 | let winter = new_event_body(&zoned(Repeat::Weekly, local(2026, 12, 16, 9, 0), 1)); |
| 357 | assert_eq!(summer["start"]["dateTime"], "2026-07-15T09:00:00"); |
| 358 | assert_eq!(winter["start"]["dateTime"], "2026-12-16T09:00:00"); |
| 359 | for body in [&summer, &winter] { |
| 360 | assert_eq!(body["start"]["timeZone"], "W. Europe Standard Time"); |
| 361 | assert_eq!(body["end"]["dateTime"].as_str().unwrap()[11..], *"09:30:00"); |
| 362 | assert_eq!(body["end"]["timeZone"], "W. Europe Standard Time"); |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | #[test] |
| 367 | fn a_local_half_past_midnight_keeps_its_local_weekday_and_start_date() { |
| 368 | let body = new_event_body(&zoned(Repeat::Weekly, local(2026, 10, 14, 0, 30), 2)); |
| 369 | assert_eq!(body["start"]["dateTime"], "2026-10-14T00:30:00"); |
| 370 | assert_eq!(body["recurrence"]["range"]["startDate"], "2026-10-14"); |
| 371 | assert_eq!( |
| 372 | body["recurrence"]["pattern"]["daysOfWeek"], |
| 373 | json!(["wednesday"]) |
| 374 | ); |
| 375 | } |
| 376 | |
| 377 | #[test] |
| 378 | fn without_a_zone_name_times_stay_utc_but_the_date_is_local() { |
| 379 | let event = NewEvent { |
| 380 | start: Utc.with_ymd_and_hms(2026, 10, 13, 22, 30, 0).unwrap(), |
| 381 | end: Utc.with_ymd_and_hms(2026, 10, 13, 23, 0, 0).unwrap(), |
| 382 | local_start: local(2026, 10, 14, 0, 30), |
| 383 | local_end: local(2026, 10, 14, 1, 0), |
| 384 | ..event(Repeat::Weekly) |
| 385 | }; |
| 386 | let body = new_event_body(&event); |
| 387 | assert_eq!(body["start"]["dateTime"], "2026-10-13T22:30:00"); |
| 388 | assert_eq!(body["start"]["timeZone"], "UTC"); |
| 389 | assert_eq!(body["recurrence"]["range"]["startDate"], "2026-10-14"); |
| 390 | assert_eq!( |
| 391 | body["recurrence"]["pattern"]["daysOfWeek"], |
| 392 | json!(["wednesday"]) |
| 393 | ); |
| 394 | } |
| 395 | |
| 396 | #[test] |
| 397 | fn details_become_a_plain_text_body() { |
| 398 | let body = new_event_body(&NewEvent { |
| 399 | details: "Agenda: roadmap".into(), |
| 400 | ..event(Repeat::Never) |
| 401 | }); |
| 402 | assert_eq!(body["body"]["contentType"], "text"); |
| 403 | assert_eq!(body["body"]["content"], "Agenda: roadmap"); |
| 404 | } |
| 405 | |
| 406 | #[test] |
| 407 | fn recurrence_maps_to_graph_patterns() { |
| 408 | let daily = new_event_body(&event(Repeat::Daily)); |
| 409 | assert_eq!(daily["recurrence"]["pattern"]["type"], "daily"); |
| 410 | assert_eq!(daily["recurrence"]["pattern"]["interval"], 1); |
| 411 | assert_eq!(daily["recurrence"]["range"]["type"], "noEnd"); |
| 412 | assert_eq!(daily["recurrence"]["range"]["startDate"], "2026-10-14"); |
| 413 | let weekdays = new_event_body(&event(Repeat::Weekdays)); |
| 414 | assert_eq!(weekdays["recurrence"]["pattern"]["type"], "weekly"); |
| 415 | assert_eq!( |
| 416 | weekdays["recurrence"]["pattern"]["daysOfWeek"], |
| 417 | json!(["monday", "tuesday", "wednesday", "thursday", "friday"]) |
| 418 | ); |
| 419 | let weekly = new_event_body(&event(Repeat::Weekly)); |
| 420 | assert_eq!( |
| 421 | weekly["recurrence"]["pattern"]["daysOfWeek"], |
| 422 | json!(["wednesday"]) |
| 423 | ); |
| 424 | } |
| 425 | |
| 426 | #[test] |
| 427 | fn the_created_event_carries_its_id_and_join_link() { |
| 428 | let body = |
| 429 | json!({"id": "AAMk", "onlineMeeting": {"joinUrl": "https://example.invalid/join"}}); |
| 430 | assert_eq!( |
| 431 | parse_created_event(&body), |
| 432 | Some(CreatedEvent { |
| 433 | id: "AAMk".into(), |
| 434 | join_url: Some("https://example.invalid/join".into()), |
| 435 | }) |
| 436 | ); |
| 437 | assert_eq!(parse_created_event(&json!({})), None); |
| 438 | } |
| 439 | |
| 440 | #[tokio::test] |
| 441 | async fn create_event_posts_to_graph_events() { |
| 442 | let calendar = |
| 443 | Calendar::with_transport(Scripted::new(vec![(201, json!({"id": "AAMk"}))]), "emea"); |
| 444 | let created = calendar.create_event(&event(Repeat::Never)).await.unwrap(); |
| 445 | assert_eq!(created.id, "AAMk"); |
| 446 | let sent = calendar.transport.sent.lock().unwrap(); |
| 447 | assert_eq!(sent[0].0, Method::Post); |
| 448 | assert_eq!(sent[0].1, "https://graph.microsoft.com/v1.0/me/events"); |
| 449 | } |
| 450 | |
| 451 | #[tokio::test] |
| 452 | async fn create_event_failure_carries_the_service_message() { |
| 453 | let calendar = Calendar::with_transport( |
| 454 | Scripted::new(vec![(403, json!({"error": {"message": "Access denied"}}))]), |
| 455 | "emea", |
| 456 | ); |
| 457 | let error = calendar |
| 458 | .create_event(&event(Repeat::Never)) |
| 459 | .await |
| 460 | .unwrap_err(); |
| 461 | assert!(error.to_string().contains("Access denied")); |
| 462 | } |
| 463 | |
| 464 | #[tokio::test] |
| 465 | async fn respond_posts_the_reply_with_the_send_flag() { |
| 466 | let calendar = Calendar::with_transport(Scripted::new(vec![(202, Value::Null)]), "emea"); |
| 467 | calendar |
| 468 | .respond("AAMk=", None, Reply::Tentative, false) |
| 469 | .await |
| 470 | .unwrap(); |
| 471 | let sent = calendar.transport.sent.lock().unwrap(); |
| 472 | assert_eq!( |
| 473 | sent[0].1, |
| 474 | "https://graph.microsoft.com/v1.0/me/events/AAMk%3D/tentativelyAccept" |
| 475 | ); |
| 476 | assert_eq!( |
| 477 | sent[0].2, |
| 478 | Some(json!({"comment": "", "sendResponse": false})) |
| 479 | ); |
| 480 | } |
| 481 | |
| 482 | #[tokio::test] |
| 483 | async fn an_unknown_id_is_looked_up_by_its_ical_uid_once() { |
| 484 | let calendar = Calendar::with_transport( |
| 485 | Scripted::new(vec![ |
| 486 | (404, json!({"error": {"message": "not found"}})), |
| 487 | (200, json!({"value": [{"id": "graph-id"}]})), |
| 488 | (202, Value::Null), |
| 489 | ]), |
| 490 | "emea", |
| 491 | ); |
| 492 | calendar |
| 493 | .respond("mt-id", Some("uid-1"), Reply::Decline, true) |
| 494 | .await |
| 495 | .unwrap(); |
| 496 | let sent = calendar.transport.sent.lock().unwrap(); |
| 497 | assert!(sent[1].1.contains("iCalUId%20eq%20'uid-1'")); |
| 498 | assert!(sent[2].1.ends_with("/graph-id/decline")); |
| 499 | } |
| 500 | |
| 501 | #[tokio::test] |
| 502 | async fn a_missing_event_without_an_ical_uid_fails() { |
| 503 | let calendar = Calendar::with_transport( |
| 504 | Scripted::new(vec![(404, json!({"error": {"message": "not found"}}))]), |
| 505 | "emea", |
| 506 | ); |
| 507 | assert!( |
| 508 | calendar |
| 509 | .respond("mt-id", None, Reply::Accept, true) |
| 510 | .await |
| 511 | .is_err() |
| 512 | ); |
| 513 | } |
| 514 | } |