| 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 | fn reply_url(event_id: &str, reply: Reply) -> String { |
| 204 | format!("{}/{}", event_item_url(event_id), reply.action()) |
| 205 | } |
| 206 | |
| 207 | fn lookup_url(ical_uid: &str) -> String { |
| 208 | format!( |
| 209 | "{}?$filter={}&$select=id&$top=1", |
| 210 | events_url(), |
| 211 | encode(&format!("iCalUId eq '{}'", ical_uid.replace('\'', "''"))) |
| 212 | ) |
| 213 | } |
| 214 | |
| 215 | fn api_error(answer: session::ApiResponse, url: &str) -> Error { |
| 216 | Error::Session(session::Error::api(answer.status, url, answer.body)) |
| 217 | } |
| 218 | |
| 219 | impl<T: CardTransport> Calendar<T> { |
| 220 | pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> { |
| 221 | self.create_event_body(event, new_event_body(event)).await |
| 222 | } |
| 223 | |
| 224 | pub async fn create_event_with_join( |
| 225 | &self, |
| 226 | event: &NewEvent, |
| 227 | join_url: &str, |
| 228 | ) -> Result<CreatedEvent> { |
| 229 | let mut created = self |
| 230 | .create_event_body(event, new_event_body_with_join(event, join_url)) |
| 231 | .await?; |
| 232 | if created.join_url.is_none() { |
| 233 | created.join_url = Some(join_url.to_owned()); |
| 234 | } |
| 235 | Ok(created) |
| 236 | } |
| 237 | |
| 238 | async fn create_event_body(&self, event: &NewEvent, body: Value) -> Result<CreatedEvent> { |
| 239 | let _ = event; |
| 240 | let url = events_url(); |
| 241 | let request = Request::with_body(Method::Post, &url, body); |
| 242 | let answer = self |
| 243 | .transport |
| 244 | .send(request, Scope::graph(CALENDARS_SCOPE)) |
| 245 | .await?; |
| 246 | if !answer.is_success() { |
| 247 | return Err(api_error(answer, &url)); |
| 248 | } |
| 249 | parse_created_event(&answer.body).ok_or_else(|| api_error(answer, &url)) |
| 250 | } |
| 251 | |
| 252 | pub async fn respond( |
| 253 | &self, |
| 254 | event_id: &str, |
| 255 | ical_uid: Option<&str>, |
| 256 | reply: Reply, |
| 257 | send_response: bool, |
| 258 | ) -> Result<()> { |
| 259 | let answer = self.send_reply(event_id, reply, send_response).await?; |
| 260 | if answer.is_success() { |
| 261 | return Ok(()); |
| 262 | } |
| 263 | let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else { |
| 264 | return Err(api_error(answer, &reply_url(event_id, reply))); |
| 265 | }; |
| 266 | let graph_id = self.graph_event_id(ical_uid).await?; |
| 267 | let retried = self.send_reply(&graph_id, reply, send_response).await?; |
| 268 | if retried.is_success() { |
| 269 | return Ok(()); |
| 270 | } |
| 271 | Err(api_error(retried, &reply_url(&graph_id, reply))) |
| 272 | } |
| 273 | |
| 274 | pub async fn delete_event(&self, event_id: &str, ical_uid: Option<&str>) -> Result<()> { |
| 275 | let answer = self.send_delete(event_id).await?; |
| 276 | if answer.is_success() { |
| 277 | return Ok(()); |
| 278 | } |
| 279 | let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else { |
| 280 | return Err(api_error(answer, &event_item_url(event_id))); |
| 281 | }; |
| 282 | let graph_id = self.graph_event_id(ical_uid).await?; |
| 283 | let retried = self.send_delete(&graph_id).await?; |
| 284 | if retried.is_success() { |
| 285 | return Ok(()); |
| 286 | } |
| 287 | Err(api_error(retried, &event_item_url(&graph_id))) |
| 288 | } |
| 289 | |
| 290 | async fn send_delete(&self, event_id: &str) -> Result<session::ApiResponse> { |
| 291 | self.transport |
| 292 | .send( |
| 293 | Request::delete(event_item_url(event_id)), |
| 294 | Scope::graph(CALENDARS_SCOPE), |
| 295 | ) |
| 296 | .await |
| 297 | } |
| 298 | |
| 299 | async fn send_reply( |
| 300 | &self, |
| 301 | event_id: &str, |
| 302 | reply: Reply, |
| 303 | send_response: bool, |
| 304 | ) -> Result<session::ApiResponse> { |
| 305 | let request = Request::with_body( |
| 306 | Method::Post, |
| 307 | reply_url(event_id, reply), |
| 308 | json!({"comment": "", "sendResponse": send_response}), |
| 309 | ); |
| 310 | self.transport |
| 311 | .send(request, Scope::graph(CALENDARS_SCOPE)) |
| 312 | .await |
| 313 | } |
| 314 | |
| 315 | async fn graph_event_id(&self, ical_uid: &str) -> Result<String> { |
| 316 | let url = lookup_url(ical_uid); |
| 317 | let answer = self |
| 318 | .transport |
| 319 | .send(Request::get(&url), Scope::graph(CALENDARS_SCOPE)) |
| 320 | .await?; |
| 321 | if !answer.is_success() { |
| 322 | return Err(api_error(answer, &url)); |
| 323 | } |
| 324 | answer |
| 325 | .body |
| 326 | .pointer("/value/0/id") |
| 327 | .and_then(Value::as_str) |
| 328 | .map(str::to_owned) |
| 329 | .ok_or_else(|| api_error(answer, &url)) |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | #[cfg(test)] |
| 334 | mod tests { |
| 335 | use std::sync::Mutex; |
| 336 | |
| 337 | use chrono::TimeZone; |
| 338 | |
| 339 | use super::*; |
| 340 | use crate::calendar::Calendar; |
| 341 | |
| 342 | struct Scripted { |
| 343 | answers: Mutex<Vec<(u16, Value)>>, |
| 344 | sent: Mutex<Vec<(Method, String, Option<Value>)>>, |
| 345 | } |
| 346 | |
| 347 | impl Scripted { |
| 348 | fn new(answers: Vec<(u16, Value)>) -> Self { |
| 349 | Scripted { |
| 350 | answers: Mutex::new(answers), |
| 351 | sent: Mutex::new(Vec::new()), |
| 352 | } |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | impl CardTransport for Scripted { |
| 357 | async fn send(&self, request: Request, scope: Scope) -> Result<session::ApiResponse> { |
| 358 | assert_eq!(scope, Scope::graph(CALENDARS_SCOPE)); |
| 359 | self.sent |
| 360 | .lock() |
| 361 | .unwrap() |
| 362 | .push((request.method, request.url, request.body)); |
| 363 | let (status, body) = self.answers.lock().unwrap().remove(0); |
| 364 | Ok(session::ApiResponse { |
| 365 | status, |
| 366 | body, |
| 367 | retry_after: None, |
| 368 | }) |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | fn local(year: i32, month: u32, day: u32, hour: u32, minute: u32) -> NaiveDateTime { |
| 373 | chrono::NaiveDate::from_ymd_opt(year, month, day) |
| 374 | .unwrap() |
| 375 | .and_hms_opt(hour, minute, 0) |
| 376 | .unwrap() |
| 377 | } |
| 378 | |
| 379 | fn zoned(repeat: Repeat, local_start: NaiveDateTime, offset_hours: i64) -> NewEvent { |
| 380 | let utc_start = local_start.and_utc() - chrono::Duration::hours(offset_hours); |
| 381 | NewEvent { |
| 382 | start: utc_start, |
| 383 | end: utc_start + chrono::Duration::minutes(30), |
| 384 | local_start, |
| 385 | local_end: local_start + chrono::Duration::minutes(30), |
| 386 | time_zone_name: Some("W. Europe Standard Time".into()), |
| 387 | ..event(repeat) |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | fn event(repeat: Repeat) -> NewEvent { |
| 392 | NewEvent { |
| 393 | subject: "Planning".into(), |
| 394 | start: Utc.with_ymd_and_hms(2026, 10, 14, 9, 30, 0).unwrap(), |
| 395 | end: Utc.with_ymd_and_hms(2026, 10, 14, 10, 0, 0).unwrap(), |
| 396 | local_start: local(2026, 10, 14, 11, 30), |
| 397 | local_end: local(2026, 10, 14, 12, 0), |
| 398 | time_zone_name: None, |
| 399 | attendees: vec![Attendee { |
| 400 | name: "Mara Lindqvist".into(), |
| 401 | address: "mara@example.invalid".into(), |
| 402 | }], |
| 403 | repeat, |
| 404 | details: String::new(), |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | #[test] |
| 409 | fn join_first_body_puts_link_in_location_without_online_meeting() { |
| 410 | let body = new_event_body_with_join( |
| 411 | &event(Repeat::Never), |
| 412 | "https://teams.microsoft.com/l/meetup-join/x", |
| 413 | ); |
| 414 | assert_eq!(body["isOnlineMeeting"], false); |
| 415 | assert_eq!( |
| 416 | body["location"]["displayName"], |
| 417 | "https://teams.microsoft.com/l/meetup-join/x" |
| 418 | ); |
| 419 | assert!( |
| 420 | body["body"]["content"] |
| 421 | .as_str() |
| 422 | .unwrap() |
| 423 | .contains("teams.microsoft.com") |
| 424 | ); |
| 425 | } |
| 426 | |
| 427 | #[test] |
| 428 | fn the_body_asks_for_a_teams_meeting_with_utc_times() { |
| 429 | let body = new_event_body(&event(Repeat::Never)); |
| 430 | assert_eq!(body["subject"], "Planning"); |
| 431 | assert_eq!(body["isOnlineMeeting"], true); |
| 432 | assert_eq!(body["onlineMeetingProvider"], "teamsForBusiness"); |
| 433 | assert_eq!(body["start"]["dateTime"], "2026-10-14T09:30:00"); |
| 434 | assert_eq!(body["start"]["timeZone"], "UTC"); |
| 435 | assert_eq!(body["end"]["dateTime"], "2026-10-14T10:00:00"); |
| 436 | assert_eq!(body["attendees"][0]["type"], "required"); |
| 437 | assert_eq!( |
| 438 | body["attendees"][0]["emailAddress"]["address"], |
| 439 | "mara@example.invalid" |
| 440 | ); |
| 441 | assert!(body.get("recurrence").is_none()); |
| 442 | assert!(body.get("body").is_none()); |
| 443 | } |
| 444 | |
| 445 | #[test] |
| 446 | fn summer_and_winter_series_keep_the_same_local_time() { |
| 447 | let summer = new_event_body(&zoned(Repeat::Weekly, local(2026, 7, 15, 9, 0), 2)); |
| 448 | let winter = new_event_body(&zoned(Repeat::Weekly, local(2026, 12, 16, 9, 0), 1)); |
| 449 | assert_eq!(summer["start"]["dateTime"], "2026-07-15T09:00:00"); |
| 450 | assert_eq!(winter["start"]["dateTime"], "2026-12-16T09:00:00"); |
| 451 | for body in [&summer, &winter] { |
| 452 | assert_eq!(body["start"]["timeZone"], "W. Europe Standard Time"); |
| 453 | assert_eq!(body["end"]["dateTime"].as_str().unwrap()[11..], *"09:30:00"); |
| 454 | assert_eq!(body["end"]["timeZone"], "W. Europe Standard Time"); |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | #[test] |
| 459 | fn a_local_half_past_midnight_keeps_its_local_weekday_and_start_date() { |
| 460 | let body = new_event_body(&zoned(Repeat::Weekly, local(2026, 10, 14, 0, 30), 2)); |
| 461 | assert_eq!(body["start"]["dateTime"], "2026-10-14T00:30:00"); |
| 462 | assert_eq!(body["recurrence"]["range"]["startDate"], "2026-10-14"); |
| 463 | assert_eq!( |
| 464 | body["recurrence"]["pattern"]["daysOfWeek"], |
| 465 | json!(["wednesday"]) |
| 466 | ); |
| 467 | } |
| 468 | |
| 469 | #[test] |
| 470 | fn without_a_zone_name_times_stay_utc_but_the_date_is_local() { |
| 471 | let event = NewEvent { |
| 472 | start: Utc.with_ymd_and_hms(2026, 10, 13, 22, 30, 0).unwrap(), |
| 473 | end: Utc.with_ymd_and_hms(2026, 10, 13, 23, 0, 0).unwrap(), |
| 474 | local_start: local(2026, 10, 14, 0, 30), |
| 475 | local_end: local(2026, 10, 14, 1, 0), |
| 476 | ..event(Repeat::Weekly) |
| 477 | }; |
| 478 | let body = new_event_body(&event); |
| 479 | assert_eq!(body["start"]["dateTime"], "2026-10-13T22:30:00"); |
| 480 | assert_eq!(body["start"]["timeZone"], "UTC"); |
| 481 | assert_eq!(body["recurrence"]["range"]["startDate"], "2026-10-14"); |
| 482 | assert_eq!( |
| 483 | body["recurrence"]["pattern"]["daysOfWeek"], |
| 484 | json!(["wednesday"]) |
| 485 | ); |
| 486 | } |
| 487 | |
| 488 | #[test] |
| 489 | fn details_become_a_plain_text_body() { |
| 490 | let body = new_event_body(&NewEvent { |
| 491 | details: "Agenda: roadmap".into(), |
| 492 | ..event(Repeat::Never) |
| 493 | }); |
| 494 | assert_eq!(body["body"]["contentType"], "text"); |
| 495 | assert_eq!(body["body"]["content"], "Agenda: roadmap"); |
| 496 | } |
| 497 | |
| 498 | #[test] |
| 499 | fn recurrence_maps_to_graph_patterns() { |
| 500 | let daily = new_event_body(&event(Repeat::Daily)); |
| 501 | assert_eq!(daily["recurrence"]["pattern"]["type"], "daily"); |
| 502 | assert_eq!(daily["recurrence"]["pattern"]["interval"], 1); |
| 503 | assert_eq!(daily["recurrence"]["range"]["type"], "noEnd"); |
| 504 | assert_eq!(daily["recurrence"]["range"]["startDate"], "2026-10-14"); |
| 505 | let weekdays = new_event_body(&event(Repeat::Weekdays)); |
| 506 | assert_eq!(weekdays["recurrence"]["pattern"]["type"], "weekly"); |
| 507 | assert_eq!( |
| 508 | weekdays["recurrence"]["pattern"]["daysOfWeek"], |
| 509 | json!(["monday", "tuesday", "wednesday", "thursday", "friday"]) |
| 510 | ); |
| 511 | let weekly = new_event_body(&event(Repeat::Weekly)); |
| 512 | assert_eq!( |
| 513 | weekly["recurrence"]["pattern"]["daysOfWeek"], |
| 514 | json!(["wednesday"]) |
| 515 | ); |
| 516 | } |
| 517 | |
| 518 | #[test] |
| 519 | fn the_created_event_carries_its_id_and_join_link() { |
| 520 | let body = |
| 521 | json!({"id": "AAMk", "onlineMeeting": {"joinUrl": "https://example.invalid/join"}}); |
| 522 | assert_eq!( |
| 523 | parse_created_event(&body), |
| 524 | Some(CreatedEvent { |
| 525 | id: "AAMk".into(), |
| 526 | join_url: Some("https://example.invalid/join".into()), |
| 527 | }) |
| 528 | ); |
| 529 | assert_eq!(parse_created_event(&json!({})), None); |
| 530 | } |
| 531 | |
| 532 | #[tokio::test] |
| 533 | async fn create_event_posts_to_graph_events() { |
| 534 | let calendar = |
| 535 | Calendar::with_transport(Scripted::new(vec![(201, json!({"id": "AAMk"}))]), "emea"); |
| 536 | let created = calendar.create_event(&event(Repeat::Never)).await.unwrap(); |
| 537 | assert_eq!(created.id, "AAMk"); |
| 538 | let sent = calendar.transport.sent.lock().unwrap(); |
| 539 | assert_eq!(sent[0].0, Method::Post); |
| 540 | assert_eq!(sent[0].1, "https://graph.microsoft.com/v1.0/me/events"); |
| 541 | } |
| 542 | |
| 543 | #[tokio::test] |
| 544 | async fn create_event_failure_carries_the_service_message() { |
| 545 | let calendar = Calendar::with_transport( |
| 546 | Scripted::new(vec![(403, json!({"error": {"message": "Access denied"}}))]), |
| 547 | "emea", |
| 548 | ); |
| 549 | let error = calendar |
| 550 | .create_event(&event(Repeat::Never)) |
| 551 | .await |
| 552 | .unwrap_err(); |
| 553 | assert!(error.to_string().contains("Access denied")); |
| 554 | } |
| 555 | |
| 556 | #[tokio::test] |
| 557 | async fn respond_posts_the_reply_with_the_send_flag() { |
| 558 | let calendar = Calendar::with_transport(Scripted::new(vec![(202, Value::Null)]), "emea"); |
| 559 | calendar |
| 560 | .respond("AAMk=", None, Reply::Tentative, false) |
| 561 | .await |
| 562 | .unwrap(); |
| 563 | let sent = calendar.transport.sent.lock().unwrap(); |
| 564 | assert_eq!( |
| 565 | sent[0].1, |
| 566 | "https://graph.microsoft.com/v1.0/me/events/AAMk%3D/tentativelyAccept" |
| 567 | ); |
| 568 | assert_eq!( |
| 569 | sent[0].2, |
| 570 | Some(json!({"comment": "", "sendResponse": false})) |
| 571 | ); |
| 572 | } |
| 573 | |
| 574 | #[tokio::test] |
| 575 | async fn delete_event_sends_graph_delete() { |
| 576 | let calendar = Calendar::with_transport(Scripted::new(vec![(204, Value::Null)]), "emea"); |
| 577 | calendar.delete_event("AAMk=", None).await.unwrap(); |
| 578 | let sent = calendar.transport.sent.lock().unwrap(); |
| 579 | assert_eq!(sent[0].0, Method::Delete); |
| 580 | assert_eq!( |
| 581 | sent[0].1, |
| 582 | "https://graph.microsoft.com/v1.0/me/events/AAMk%3D" |
| 583 | ); |
| 584 | } |
| 585 | |
| 586 | #[tokio::test] |
| 587 | async fn an_unknown_id_is_looked_up_by_its_ical_uid_once() { |
| 588 | let calendar = Calendar::with_transport( |
| 589 | Scripted::new(vec![ |
| 590 | (404, json!({"error": {"message": "not found"}})), |
| 591 | (200, json!({"value": [{"id": "graph-id"}]})), |
| 592 | (202, Value::Null), |
| 593 | ]), |
| 594 | "emea", |
| 595 | ); |
| 596 | calendar |
| 597 | .respond("mt-id", Some("uid-1"), Reply::Decline, true) |
| 598 | .await |
| 599 | .unwrap(); |
| 600 | let sent = calendar.transport.sent.lock().unwrap(); |
| 601 | assert!(sent[1].1.contains("iCalUId%20eq%20'uid-1'")); |
| 602 | assert!(sent[2].1.ends_with("/graph-id/decline")); |
| 603 | } |
| 604 | |
| 605 | #[tokio::test] |
| 606 | async fn a_missing_event_without_an_ical_uid_fails() { |
| 607 | let calendar = Calendar::with_transport( |
| 608 | Scripted::new(vec![(404, json!({"error": {"message": "not found"}}))]), |
| 609 | "emea", |
| 610 | ); |
| 611 | assert!( |
| 612 | calendar |
| 613 | .respond("mt-id", None, Reply::Accept, true) |
| 614 | .await |
| 615 | .is_err() |
| 616 | ); |
| 617 | } |
| 618 | } |