BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / google_calendar / parse.rs

parse.rs

parse.rs 6.7 KiB Download Raw
1use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
2use serde_json::Value;
3
4use crate::calendar::{CalendarEvent, CalendarSource, ResponseType, ShowAs};
5
6pub fn parse_calendar_list(body: &Value) -> Vec<(String, String, bool)> {
7 body.get("items")
8 .and_then(Value::as_array)
9 .into_iter()
10 .flatten()
11 .filter_map(|entry| {
12 Some((
13 entry.get("id")?.as_str()?.to_owned(),
14 entry
15 .get("summary")
16 .and_then(Value::as_str)
17 .unwrap_or("Calendar")
18 .to_owned(),
19 entry
20 .get("primary")
21 .and_then(Value::as_bool)
22 .unwrap_or(false),
23 ))
24 })
25 .collect()
26}
27
28pub fn parse_google_events(
29 body: &Value,
30 account_id: Option<&str>,
31 calendar_id: Option<&str>,
32) -> Vec<CalendarEvent> {
33 let mut events: Vec<CalendarEvent> = body
34 .get("items")
35 .and_then(Value::as_array)
36 .into_iter()
37 .flatten()
38 .filter_map(|entry| parse_event(entry, account_id, calendar_id))
39 .collect();
40 events.sort_by_key(|event| (event.start, event.end));
41 events
42}
43
44fn parse_event(
45 entry: &Value,
46 account_id: Option<&str>,
47 calendar_id: Option<&str>,
48) -> Option<CalendarEvent> {
49 if entry.get("status").and_then(Value::as_str) == Some("cancelled") {
50 // Still show cancelled when times exist.
51 }
52 let object_id = entry.get("id")?.as_str()?.to_owned();
53 let (start, all_day) = event_instant(entry.get("start")?)?;
54 let (end, _) = event_instant(entry.get("end")?)?;
55 let join_url = conference_join_url(entry)
56 .or_else(|| text(entry, "location").filter(|value| value.contains("teams.microsoft.com")))
57 .or_else(|| {
58 text(entry, "description").and_then(|description| {
59 description
60 .split_whitespace()
61 .find(|token| token.contains("teams.microsoft.com"))
62 .map(str::to_owned)
63 })
64 });
65 Some(CalendarEvent {
66 object_id,
67 subject: text(entry, "summary").unwrap_or_default(),
68 start,
69 end,
70 all_day,
71 cancelled: entry.get("status").and_then(Value::as_str) == Some("cancelled"),
72 online: join_url.is_some(),
73 join_url,
74 thread_id: None,
75 organizer_name: entry
76 .pointer("/organizer/displayName")
77 .and_then(Value::as_str)
78 .map(str::to_owned),
79 organizer_address: entry
80 .pointer("/organizer/email")
81 .and_then(Value::as_str)
82 .map(str::to_owned),
83 ical_uid: text(entry, "iCalUID"),
84 response: response_status(entry),
85 show_as: ShowAs::Busy,
86 dial_in: None,
87 source: CalendarSource::Google,
88 account_id: account_id.map(str::to_owned),
89 calendar_id: calendar_id.map(str::to_owned),
90 sources: vec![CalendarSource::Google],
91 })
92}
93
94fn conference_join_url(entry: &Value) -> Option<String> {
95 entry
96 .pointer("/conferenceData/entryPoints")
97 .and_then(Value::as_array)?
98 .iter()
99 .find_map(|point| {
100 if point.get("entryPointType").and_then(Value::as_str) == Some("video") {
101 text(point, "uri")
102 } else {
103 None
104 }
105 })
106}
107
108fn event_instant(value: &Value) -> Option<(DateTime<Utc>, bool)> {
109 if let Some(date) = value.get("date").and_then(Value::as_str) {
110 let day = NaiveDate::parse_from_str(date, "%Y-%m-%d").ok()?;
111 let start = day.and_time(NaiveTime::MIN).and_utc();
112 return Some((start, true));
113 }
114 let date_time = value.get("dateTime")?.as_str()?;
115 DateTime::parse_from_rfc3339(date_time)
116 .ok()
117 .map(|time| (time.with_timezone(&Utc), false))
118}
119
120fn response_status(entry: &Value) -> ResponseType {
121 let status = entry
122 .get("attendees")
123 .and_then(Value::as_array)
124 .into_iter()
125 .flatten()
126 .find(|attendee| attendee.get("self").and_then(Value::as_bool) == Some(true))
127 .and_then(|attendee| attendee.get("responseStatus").and_then(Value::as_str))
128 .or_else(|| {
129 entry
130 .pointer("/organizer/self")
131 .and_then(Value::as_bool)
132 .filter(|value| *value)
133 .map(|_| "accepted")
134 });
135 match status {
136 Some("accepted")
137 if entry.pointer("/organizer/self").and_then(Value::as_bool) == Some(true) =>
138 {
139 ResponseType::Organizer
140 }
141 Some("accepted") => ResponseType::Accepted,
142 Some("tentative") => ResponseType::Tentative,
143 Some("declined") => ResponseType::Declined,
144 _ => ResponseType::NotResponded,
145 }
146}
147
148fn text(entry: &Value, key: &str) -> Option<String> {
149 entry.get(key)?.as_str().map(str::to_owned)
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 #[test]
157 fn parses_timed_event_with_teams_link_in_location() {
158 let body = serde_json::json!({
159 "items": [{
160 "id": "evt1",
161 "summary": "Standup",
162 "iCalUID": "uid-1",
163 "start": {"dateTime": "2026-11-11T09:00:00Z"},
164 "end": {"dateTime": "2026-11-11T09:30:00Z"},
165 "location": "https://teams.microsoft.com/l/meetup-join/abc",
166 "attendees": [{"self": true, "responseStatus": "accepted"}]
167 }]
168 });
169 let events = parse_google_events(&body, Some("acc"), Some("primary"));
170 assert_eq!(events.len(), 1);
171 assert_eq!(events[0].subject, "Standup");
172 assert_eq!(events[0].source, CalendarSource::Google);
173 assert_eq!(events[0].account_id.as_deref(), Some("acc"));
174 assert_eq!(
175 events[0].join_url.as_deref(),
176 Some("https://teams.microsoft.com/l/meetup-join/abc")
177 );
178 assert_eq!(events[0].response, ResponseType::Accepted);
179 }
180
181 #[test]
182 fn parses_all_day_and_calendar_list() {
183 let body = serde_json::json!({
184 "items": [{
185 "id": "day",
186 "summary": "Offsite",
187 "start": {"date": "2026-11-12"},
188 "end": {"date": "2026-11-13"},
189 "status": "confirmed"
190 }]
191 });
192 let events = parse_google_events(&body, None, None);
193 assert!(events[0].all_day);
194 let list = parse_calendar_list(&serde_json::json!({
195 "items": [
196 {"id": "primary", "summary": "Joe", "primary": true},
197 {"id": "work", "summary": "Work"}
198 ]
199 }));
200 assert_eq!(list[0].0, "primary");
201 assert!(list[0].2);
202 }
203}