BlueGit

ict rusty-teams

Files

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

merge.rs

merge.rs 8.8 KiB Download Raw
1use crate::calendar::{CalendarEvent, CalendarSource};
2
3/// Identity of the home calendar used when Outlook is not among merge contributors.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub struct HomeCalendar<'a> {
6 pub source: CalendarSource,
7 pub account_id: &'a str,
8 pub calendar_id: &'a str,
9}
10
11/// Collapse duplicate meetings that share an iCal UID or the same Teams join URL.
12///
13/// Preference when both sides contribute: Outlook wins; else the home calendar's copy; else keep
14/// the first.
15pub fn merge_calendar_events(
16 events: Vec<CalendarEvent>,
17 home: Option<HomeCalendar<'_>>,
18) -> Vec<CalendarEvent> {
19 let mut merged: Vec<CalendarEvent> = Vec::new();
20 for event in events {
21 if let Some(existing) = merged
22 .iter_mut()
23 .find(|candidate| same_meeting(candidate, &event))
24 {
25 if !existing.sources.contains(&event.source) {
26 existing.sources.push(event.source);
27 }
28 if existing.join_url.is_none() {
29 existing.join_url = event.join_url.clone();
30 existing.online = existing.online || event.online;
31 }
32 if existing.thread_id.is_none() {
33 existing.thread_id = event.thread_id.clone();
34 }
35 if existing.location.is_none() {
36 existing.location = event.location.clone();
37 }
38 if existing.body_preview.is_none() {
39 existing.body_preview = event.body_preview.clone();
40 }
41 if existing.body_html.is_none() {
42 existing.body_html = event.body_html.clone();
43 }
44 if existing.response_counts.is_none() {
45 existing.response_counts = event.response_counts;
46 }
47 if existing.attendees.is_empty() {
48 existing.attendees = event.attendees.clone();
49 }
50 if existing.reminders.is_empty() {
51 existing.reminders = event.reminders.clone();
52 }
53 if existing.source_link.is_none() {
54 existing.source_link = event.source_link.clone();
55 }
56 if existing.web_link.is_none() {
57 existing.web_link = event.web_link.clone();
58 }
59 if existing.calendar_name.is_none() {
60 existing.calendar_name = event.calendar_name.clone();
61 }
62 if event.series {
63 existing.series = true;
64 }
65 if existing.series_master_id.is_none() {
66 existing.series_master_id = event.series_master_id.clone();
67 }
68 if prefers_incoming(existing, &event, home) {
69 take_identity(existing, &event);
70 }
71 continue;
72 }
73 merged.push(event);
74 }
75 merged.sort_by_key(|event| (event.start, event.end));
76 merged
77}
78
79fn prefers_incoming(
80 existing: &CalendarEvent,
81 incoming: &CalendarEvent,
82 home: Option<HomeCalendar<'_>>,
83) -> bool {
84 if incoming.source.is_outlook() && !existing.source.is_outlook() {
85 return true;
86 }
87 if existing.source.is_outlook() {
88 return false;
89 }
90 if let Some(home) = home {
91 let incoming_home = matches_home(incoming, home);
92 let existing_home = matches_home(existing, home);
93 if incoming_home && !existing_home {
94 return true;
95 }
96 }
97 false
98}
99
100fn matches_home(event: &CalendarEvent, home: HomeCalendar<'_>) -> bool {
101 if event.source != home.source {
102 return false;
103 }
104 if home.source.is_outlook() {
105 return true;
106 }
107 event.account_id.as_deref() == Some(home.account_id)
108 && event.calendar_id.as_deref() == Some(home.calendar_id)
109}
110
111fn take_identity(existing: &mut CalendarEvent, incoming: &CalendarEvent) {
112 existing.object_id = incoming.object_id.clone();
113 existing.source = incoming.source;
114 existing.account_id = incoming.account_id.clone();
115 existing.calendar_id = incoming.calendar_id.clone();
116 existing.response = incoming.response;
117 existing.show_as = incoming.show_as;
118}
119
120fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {
121 let same_all_day = left.all_day
122 && right.all_day
123 && (left.start - right.start).abs() < chrono::Duration::days(1);
124 if left.start != right.start && !same_all_day {
125 return false;
126 }
127 if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {
128 if !a.is_empty() && a == b {
129 return true;
130 }
131 }
132 match (
133 left.join_url.as_deref().map(normalize_join_url),
134 right.join_url.as_deref().map(normalize_join_url),
135 ) {
136 (Some(a), Some(b)) if !a.is_empty() && a == b => true,
137 _ => false,
138 }
139}
140
141pub fn normalize_join_url(url: &str) -> String {
142 let trimmed = url.trim().trim_end_matches('/');
143 let without_query = trimmed.split('?').next().unwrap_or(trimmed);
144 without_query.to_ascii_lowercase()
145}
146
147#[cfg(test)]
148mod tests {
149 use chrono::TimeZone;
150
151 use super::*;
152
153 fn event(
154 id: &str,
155 source: CalendarSource,
156 ical: Option<&str>,
157 join: Option<&str>,
158 ) -> CalendarEvent {
159 CalendarEvent {
160 object_id: id.into(),
161 subject: "Sync".into(),
162 start: chrono::Utc
163 .with_ymd_and_hms(2026, 11, 11, 10, 0, 0)
164 .unwrap(),
165 end: chrono::Utc
166 .with_ymd_and_hms(2026, 11, 11, 10, 30, 0)
167 .unwrap(),
168 ical_uid: ical.map(str::to_owned),
169 join_url: join.map(str::to_owned),
170 online: join.is_some(),
171 source,
172 sources: vec![source],
173 account_id: match source {
174 CalendarSource::Google => Some("g1".into()),
175 CalendarSource::CalDav => Some("c1".into()),
176 _ => None,
177 },
178 calendar_id: match source {
179 CalendarSource::Google => Some("primary".into()),
180 CalendarSource::CalDav => Some("/cal/".into()),
181 _ => None,
182 },
183 ..Default::default()
184 }
185 }
186
187 #[test]
188 fn merges_on_ical_uid_and_prefers_outlook() {
189 let merged = merge_calendar_events(
190 vec![
191 event("o1", CalendarSource::Outlook, Some("uid"), None),
192 event(
193 "g1",
194 CalendarSource::Google,
195 Some("uid"),
196 Some("https://teams.microsoft.com/l/meetup-join/x"),
197 ),
198 ],
199 None,
200 );
201 assert_eq!(merged.len(), 1);
202 assert_eq!(merged[0].sources.len(), 2);
203 assert_eq!(merged[0].object_id, "o1");
204 assert!(merged[0].join_url.is_some());
205 }
206
207 #[test]
208 fn prefers_home_when_outlook_absent() {
209 let home = HomeCalendar {
210 source: CalendarSource::CalDav,
211 account_id: "c1",
212 calendar_id: "/cal/",
213 };
214 let google_first = event("g1", CalendarSource::Google, Some("uid"), None);
215 let caldav = event("c1", CalendarSource::CalDav, Some("uid"), None);
216 let merged = merge_calendar_events(vec![google_first, caldav], Some(home));
217 assert_eq!(merged.len(), 1);
218 assert_eq!(merged[0].source, CalendarSource::CalDav);
219 assert_eq!(merged[0].object_id, "c1");
220 }
221
222 #[test]
223 fn occurrences_of_one_series_stay_separate() {
224 let join = Some("https://teams.microsoft.com/l/meetup-join/x");
225 let mut next_day = event("o2", CalendarSource::Outlook, Some("uid"), join);
226 next_day.start += chrono::Duration::days(1);
227 next_day.end += chrono::Duration::days(1);
228 let merged = merge_calendar_events(
229 vec![
230 event("o1", CalendarSource::Outlook, Some("uid"), join),
231 next_day,
232 ],
233 None,
234 );
235 assert_eq!(merged.len(), 2);
236 }
237
238 #[test]
239 fn merges_on_normalized_join_url() {
240 let merged = merge_calendar_events(
241 vec![
242 event(
243 "o1",
244 CalendarSource::Outlook,
245 None,
246 Some("https://teams.microsoft.com/l/meetup-join/X?x=1"),
247 ),
248 event(
249 "g1",
250 CalendarSource::Google,
251 None,
252 Some("https://teams.microsoft.com/l/meetup-join/x/"),
253 ),
254 ],
255 None,
256 );
257 assert_eq!(merged.len(), 1);
258 }
259
260 #[test]
261 fn does_not_merge_on_title_and_time_alone() {
262 let a = event("a", CalendarSource::Outlook, Some("a"), None);
263 let mut b = event("b", CalendarSource::Google, Some("b"), None);
264 b.subject = a.subject.clone();
265 assert_eq!(merge_calendar_events(vec![a, b], None).len(), 2);
266 }
267}