BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / call / reminder.rs

reminder.rs

reminder.rs 12.2 KiB Download Raw
1use std::collections::HashSet;
2
3use chatsvc::{CalendarEvent, ResponseType};
4use chrono::{DateTime, Duration, FixedOffset, Utc};
5use gpui_kit::Context;
6
7use crate::app_state::{AppEvent, AppState};
8
9pub const LEAD_MINUTES: i64 = 5;
10pub const GRACE_MINUTES: i64 = 5;
11const CHECK_EVERY_SECONDS: i64 = 1;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum ReminderPhase {
15 Soon,
16 Started,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct MeetingToast {
21 pub id: u64,
22 pub event_key: String,
23 pub phase: ReminderPhase,
24 pub subject: String,
25 pub start: DateTime<Utc>,
26 pub join_url: String,
27}
28
29fn event_key(event: &CalendarEvent) -> String {
30 format!("{}@{}", event.object_id, event.start.timestamp())
31}
32
33pub fn phase_at(event: &CalendarEvent, now: DateTime<Utc>) -> Option<ReminderPhase> {
34 let eligible = event.online
35 && !event.cancelled
36 && !event.all_day
37 && event.join_url.is_some()
38 && event.response != ResponseType::Declined;
39 if !eligible {
40 return None;
41 }
42 if now >= event.start - Duration::minutes(LEAD_MINUTES) && now < event.start {
43 return Some(ReminderPhase::Soon);
44 }
45 let started_until = event
46 .end
47 .min(event.start + Duration::minutes(GRACE_MINUTES));
48 (now >= event.start && now < started_until).then_some(ReminderPhase::Started)
49}
50
51pub fn subtitle(toast: &MeetingToast, now: DateTime<Utc>, offset: FixedOffset) -> String {
52 let clock = toast.start.with_timezone(&offset).format("%H:%M");
53 match toast.phase {
54 ReminderPhase::Started => format!("{clock} - started"),
55 ReminderPhase::Soon => {
56 let minutes = ((toast.start - now).num_seconds().max(0) + 59) / 60;
57 match minutes {
58 0 => format!("{clock} - starting now"),
59 1 => format!("{clock} - starts in 1 min"),
60 minutes => format!("{clock} - starts in {minutes} min"),
61 }
62 }
63 }
64}
65
66#[derive(Debug, Default)]
67pub struct MeetingToasts {
68 entries: Vec<MeetingToast>,
69 fired: HashSet<(String, ReminderPhase)>,
70 next_id: u64,
71 last_check: Option<DateTime<Utc>>,
72}
73
74impl MeetingToasts {
75 pub fn entries(&self) -> &[MeetingToast] {
76 &self.entries
77 }
78
79 pub fn get(&self, id: u64) -> Option<&MeetingToast> {
80 self.entries.iter().find(|toast| toast.id == id)
81 }
82
83 pub fn latest(&self) -> Option<&MeetingToast> {
84 self.entries.last()
85 }
86
87 pub fn is_empty(&self) -> bool {
88 self.entries.is_empty()
89 }
90
91 pub fn dismiss(&mut self, id: u64) -> Option<MeetingToast> {
92 let index = self.entries.iter().position(|toast| toast.id == id)?;
93 Some(self.entries.remove(index))
94 }
95
96 pub fn clear(&mut self) -> bool {
97 let had_any = !self.entries.is_empty();
98 self.entries.clear();
99 had_any
100 }
101
102 pub fn is_due_for_check(&self, now: DateTime<Utc>) -> bool {
103 self.last_check
104 .is_none_or(|last| now - last >= Duration::seconds(CHECK_EVERY_SECONDS))
105 }
106
107 pub fn update(&mut self, events: &[CalendarEvent], now: DateTime<Utc>, show: bool) -> bool {
108 self.last_check = Some(now);
109 let before = self.entries.clone();
110 self.entries.retain(|toast| {
111 events
112 .iter()
113 .any(|event| event_key(event) == toast.event_key && phase_at(event, now).is_some())
114 });
115 let keys: HashSet<String> = events.iter().map(event_key).collect();
116 self.fired.retain(|(key, _)| keys.contains(key));
117 for event in events {
118 let Some(phase) = phase_at(event, now) else {
119 continue;
120 };
121 let key = event_key(event);
122 if !self.fired.insert((key.clone(), phase)) || !show {
123 continue;
124 }
125 let Some(join_url) = event.join_url.clone() else {
126 continue;
127 };
128 let subject = if event.subject.is_empty() {
129 "(No title)".to_owned()
130 } else {
131 event.subject.clone()
132 };
133 if let Some(existing) = self.entries.iter_mut().find(|toast| toast.event_key == key) {
134 existing.phase = phase;
135 continue;
136 }
137 self.next_id += 1;
138 self.entries.push(MeetingToast {
139 id: self.next_id,
140 event_key: key,
141 phase,
142 subject,
143 start: event.start,
144 join_url,
145 });
146 }
147 self.entries != before
148 }
149}
150
151impl AppState {
152 pub fn tick_meeting_reminders(&mut self, show: bool, cx: &mut Context<Self>) {
153 let now = Utc::now();
154 let in_call = self.call.is_some();
155 let show = show && !in_call && !self.mode.read_only;
156 let changed = self.meeting_toasts.update(&self.calendar_events, now, show);
157 if (in_call && self.meeting_toasts.clear()) || changed {
158 cx.emit(AppEvent::MeetingReminder);
159 cx.notify();
160 }
161 }
162
163 pub fn join_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
164 let Some(toast) = self.meeting_toasts.dismiss(id) else {
165 return;
166 };
167 cx.emit(AppEvent::MeetingReminder);
168 self.join_meeting_link(&toast.join_url, cx);
169 if let Some(pending) = self.prejoin.as_mut() {
170 pending.join.title = toast.subject;
171 }
172 }
173
174 pub fn join_latest_meeting_toast(&mut self, cx: &mut Context<Self>) {
175 if let Some(id) = self.meeting_toasts.latest().map(|toast| toast.id) {
176 self.join_meeting_toast(id, cx);
177 }
178 }
179
180 pub fn dismiss_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
181 if self.meeting_toasts.dismiss(id).is_some() {
182 cx.emit(AppEvent::MeetingReminder);
183 cx.notify();
184 }
185 }
186}
187
188#[cfg(test)]
189mod tests {
190 use chrono::TimeZone;
191
192 use super::*;
193
194 fn at(hour: u32, minute: u32, second: u32) -> DateTime<Utc> {
195 Utc.with_ymd_and_hms(2026, 10, 13, hour, minute, second)
196 .unwrap()
197 }
198
199 fn event(id: &str) -> CalendarEvent {
200 CalendarEvent {
201 object_id: id.into(),
202 subject: format!("Meeting {id}"),
203 start: at(9, 0, 0),
204 end: at(9, 30, 0),
205 all_day: false,
206 cancelled: false,
207 online: true,
208 join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
209 thread_id: None,
210 organizer_name: Some("Mara".into()),
211 organizer_address: None,
212 ical_uid: None,
213 response: ResponseType::Accepted,
214 }
215 }
216
217 #[test]
218 fn the_phase_follows_the_clock_around_the_start() {
219 let meeting = event("a");
220 assert_eq!(phase_at(&meeting, at(8, 54, 59)), None);
221 assert_eq!(phase_at(&meeting, at(8, 55, 0)), Some(ReminderPhase::Soon));
222 assert_eq!(phase_at(&meeting, at(8, 59, 59)), Some(ReminderPhase::Soon));
223 assert_eq!(
224 phase_at(&meeting, at(9, 0, 0)),
225 Some(ReminderPhase::Started)
226 );
227 assert_eq!(
228 phase_at(&meeting, at(9, 4, 59)),
229 Some(ReminderPhase::Started)
230 );
231 assert_eq!(phase_at(&meeting, at(9, 5, 0)), None);
232 }
233
234 #[test]
235 fn a_short_meeting_stops_reminding_at_its_end() {
236 let short = CalendarEvent {
237 end: at(9, 3, 0),
238 ..event("a")
239 };
240 assert_eq!(phase_at(&short, at(9, 2, 59)), Some(ReminderPhase::Started));
241 assert_eq!(phase_at(&short, at(9, 3, 0)), None);
242 }
243
244 #[test]
245 fn declined_cancelled_all_day_and_offline_events_stay_quiet() {
246 let declined = CalendarEvent {
247 response: ResponseType::Declined,
248 ..event("a")
249 };
250 let cancelled = CalendarEvent {
251 cancelled: true,
252 ..event("a")
253 };
254 let all_day = CalendarEvent {
255 all_day: true,
256 ..event("a")
257 };
258 let offline = CalendarEvent {
259 online: false,
260 ..event("a")
261 };
262 for quiet in [declined, cancelled, all_day, offline] {
263 assert_eq!(phase_at(&quiet, at(8, 58, 0)), None);
264 }
265 }
266
267 #[test]
268 fn each_phase_fires_once_per_meeting() {
269 let events = [event("a")];
270 let mut toasts = MeetingToasts::default();
271 assert!(!toasts.update(&events, at(8, 54, 0), true));
272 assert!(toasts.update(&events, at(8, 55, 0), true));
273 assert_eq!(toasts.entries().len(), 1);
274 let id = toasts.entries()[0].id;
275 toasts.dismiss(id);
276 assert!(!toasts.update(&events, at(8, 56, 0), true));
277 assert!(toasts.is_empty());
278 }
279
280 #[test]
281 fn the_start_brings_a_dismissed_toast_back_and_updates_an_open_one() {
282 let events = [event("a")];
283 let mut toasts = MeetingToasts::default();
284 toasts.update(&events, at(8, 55, 0), true);
285 let id = toasts.entries()[0].id;
286 assert!(toasts.update(&events, at(9, 0, 0), true));
287 assert_eq!(toasts.entries().len(), 1);
288 assert_eq!(toasts.entries()[0].id, id);
289 assert_eq!(toasts.entries()[0].phase, ReminderPhase::Started);
290 let mut dismissed = MeetingToasts::default();
291 dismissed.update(&events, at(8, 55, 0), true);
292 let soon_id = dismissed.entries()[0].id;
293 dismissed.dismiss(soon_id);
294 assert!(dismissed.update(&events, at(9, 0, 0), true));
295 assert_eq!(dismissed.entries()[0].phase, ReminderPhase::Started);
296 }
297
298 #[test]
299 fn a_hidden_reminder_is_spent_and_does_not_appear_later() {
300 let events = [event("a")];
301 let mut toasts = MeetingToasts::default();
302 assert!(!toasts.update(&events, at(8, 56, 0), false));
303 assert!(!toasts.update(&events, at(8, 57, 0), true));
304 assert!(toasts.is_empty());
305 }
306
307 #[test]
308 fn toasts_leave_when_the_window_closes_or_the_event_goes() {
309 let events = [event("a")];
310 let mut toasts = MeetingToasts::default();
311 toasts.update(&events, at(8, 56, 0), true);
312 assert!(toasts.update(&events, at(9, 5, 0), true));
313 assert!(toasts.is_empty());
314 let mut removed = MeetingToasts::default();
315 removed.update(&events, at(8, 56, 0), true);
316 assert!(removed.update(&[], at(8, 57, 0), true));
317 assert!(removed.is_empty());
318 }
319
320 #[test]
321 fn the_latest_toast_is_the_one_a_shortcut_joins() {
322 let events = [event("a"), event("b")];
323 let mut toasts = MeetingToasts::default();
324 toasts.update(&events, at(8, 56, 0), true);
325 assert_eq!(
326 toasts.latest().map(|toast| toast.subject.as_str()),
327 Some("Meeting b")
328 );
329 }
330
331 #[test]
332 fn the_subtitle_counts_down_to_the_start_in_local_time() {
333 let toast = |phase| MeetingToast {
334 id: 1,
335 event_key: "a".into(),
336 phase,
337 subject: "Planning".into(),
338 start: at(9, 0, 0),
339 join_url: "https://example.invalid".into(),
340 };
341 let offset = FixedOffset::east_opt(2 * 3600).unwrap();
342 let soon = toast(ReminderPhase::Soon);
343 assert_eq!(
344 subtitle(&soon, at(8, 55, 0), offset),
345 "11:00 - starts in 5 min"
346 );
347 assert_eq!(
348 subtitle(&soon, at(8, 58, 30), offset),
349 "11:00 - starts in 2 min"
350 );
351 assert_eq!(
352 subtitle(&soon, at(8, 59, 30), offset),
353 "11:00 - starts in 1 min"
354 );
355 assert_eq!(subtitle(&soon, at(9, 0, 0), offset), "11:00 - starting now");
356 assert_eq!(
357 subtitle(&toast(ReminderPhase::Started), at(9, 1, 0), offset),
358 "11:00 - started"
359 );
360 }
361
362 #[test]
363 fn clearing_removes_every_open_toast() {
364 let events = [event("a"), event("b")];
365 let mut toasts = MeetingToasts::default();
366 toasts.update(&events, at(8, 56, 0), true);
367 assert!(toasts.clear());
368 assert!(toasts.is_empty());
369 assert!(!toasts.clear());
370 }
371
372 #[test]
373 fn checks_run_at_most_once_a_second() {
374 let mut toasts = MeetingToasts::default();
375 assert!(toasts.is_due_for_check(at(9, 0, 0)));
376 toasts.update(&[], at(9, 0, 0), true);
377 assert!(!toasts.is_due_for_check(at(9, 0, 0)));
378 assert!(toasts.is_due_for_check(at(9, 0, 1)));
379 }
380}