BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / calendar / availability.rs

availability.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
availability.rs 4.9 KiB Download Raw
1use chrono::{DateTime, NaiveDateTime, Utc};
2use serde_json::{Value, json};
3use session::{GRAPH, Method, Request, Scope};
4
5use super::Calendar;
6use super::schedule::CALENDARS_SCOPE;
7use crate::cards::CardTransport;
8use crate::error::{Error, Result};
9
10const TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S";
11const READ_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.f";
12const TIME_ZONE: &str = "UTC";
13const VIEW_INTERVAL_MINUTES: u32 = 30;
14const FREE: &str = "free";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct BusyTime {
18 pub start: DateTime<Utc>,
19 pub end: DateTime<Utc>,
20 pub status: String,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct PersonSchedule {
25 pub email: String,
26 pub busy: Vec<BusyTime>,
27 pub error: Option<String>,
28}
29
30fn schedule_url() -> String {
31 format!("{GRAPH}/v1.0/me/calendar/getSchedule")
32}
33
34pub fn schedule_request_body(emails: &[String], start: DateTime<Utc>, end: DateTime<Utc>) -> Value {
35 let stamp = |moment: DateTime<Utc>| json!({"dateTime": moment.format(TIME_FORMAT).to_string(), "timeZone": TIME_ZONE});
36 json!({
37 "schedules": emails,
38 "startTime": stamp(start),
39 "endTime": stamp(end),
40 "availabilityViewInterval": VIEW_INTERVAL_MINUTES,
41 })
42}
43
44fn utc_time(entry: &Value) -> Option<DateTime<Utc>> {
45 let text = entry.get("dateTime")?.as_str()?;
46 NaiveDateTime::parse_from_str(text, READ_FORMAT)
47 .ok()
48 .map(|time| time.and_utc())
49}
50
51fn busy_time(item: &Value) -> Option<BusyTime> {
52 let status = item.get("status")?.as_str()?.to_owned();
53 if status.eq_ignore_ascii_case(FREE) {
54 return None;
55 }
56 Some(BusyTime {
57 start: utc_time(item.get("start")?)?,
58 end: utc_time(item.get("end")?)?,
59 status,
60 })
61}
62
63pub fn parse_schedules(body: &Value) -> Vec<PersonSchedule> {
64 body.get("value")
65 .and_then(Value::as_array)
66 .into_iter()
67 .flatten()
68 .filter_map(|entry| {
69 Some(PersonSchedule {
70 email: entry.get("scheduleId")?.as_str()?.to_owned(),
71 busy: entry
72 .get("scheduleItems")
73 .and_then(Value::as_array)
74 .into_iter()
75 .flatten()
76 .filter_map(busy_time)
77 .collect(),
78 error: entry
79 .pointer("/error/message")
80 .and_then(Value::as_str)
81 .map(str::to_owned),
82 })
83 })
84 .collect()
85}
86
87impl<T: CardTransport> Calendar<T> {
88 pub async fn schedules(
89 &self,
90 emails: &[String],
91 start: DateTime<Utc>,
92 end: DateTime<Utc>,
93 ) -> Result<Vec<PersonSchedule>> {
94 let url = schedule_url();
95 let mut request = Request::with_body(
96 Method::Post,
97 &url,
98 schedule_request_body(emails, start, end),
99 );
100 request.headers.push((
101 "Prefer".to_owned(),
102 format!("outlook.timezone=\"{TIME_ZONE}\""),
103 ));
104 let answer = self
105 .transport
106 .send(request, Scope::graph(CALENDARS_SCOPE))
107 .await?;
108 if !answer.is_success() {
109 return Err(Error::Session(session::Error::api(
110 answer.status,
111 &url,
112 answer.body,
113 )));
114 }
115 Ok(parse_schedules(&answer.body))
116 }
117}
118
119#[cfg(test)]
120mod tests {
121 use chrono::{TimeZone, Utc};
122 use serde_json::json;
123
124 use super::{parse_schedules, schedule_request_body};
125
126 #[test]
127 fn the_request_asks_in_utc() {
128 let start = Utc.with_ymd_and_hms(2026, 11, 20, 8, 0, 0).unwrap();
129 let body = schedule_request_body(
130 &["mara@example.com".to_owned()],
131 start,
132 start + chrono::Duration::hours(10),
133 );
134 assert_eq!(body["startTime"]["dateTime"], "2026-11-20T08:00:00");
135 assert_eq!(body["endTime"]["timeZone"], "UTC");
136 assert_eq!(body["schedules"][0], "mara@example.com");
137 }
138
139 #[test]
140 fn busy_slots_and_errors_are_read_free_ones_dropped() {
141 let body = json!({"value": [
142 {"scheduleId": "mara@example.com", "scheduleItems": [
143 {"status": "busy", "start": {"dateTime": "2026-11-20T09:00:00.0000000", "timeZone": "UTC"}, "end": {"dateTime": "2026-11-20T10:00:00.0000000", "timeZone": "UTC"}},
144 {"status": "free", "start": {"dateTime": "2026-11-20T11:00:00.0000000", "timeZone": "UTC"}, "end": {"dateTime": "2026-11-20T12:00:00.0000000", "timeZone": "UTC"}}
145 ]},
146 {"scheduleId": "guest@other.com", "scheduleItems": [], "error": {"message": "not found"}}
147 ]});
148 let schedules = parse_schedules(&body);
149 assert_eq!(schedules[0].busy.len(), 1);
150 assert_eq!(
151 schedules[0].busy[0].start,
152 Utc.with_ymd_and_hms(2026, 11, 20, 9, 0, 0).unwrap()
153 );
154 assert_eq!(schedules[1].error.as_deref(), Some("not found"));
155 }
156}