BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / call / schedule.rs

schedule.rs

82512960 History
schedule.rs 13.2 KiB Download Raw
1use chatsvc::{Attendee, CalendarEvent, Repeat, Reply, ResponseType};
2use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Timelike, Utc};
3use gpui_kit::Context;
4use tokio::sync::oneshot;
5
6use super::actions::NOT_CONNECTED_NOTICE;
7use super::agenda::demo_join_url;
8use crate::app_state::AppState;
9use crate::runtime;
10
11const HALF_HOUR_MINUTES: i64 = 30;
12const DEFAULT_LENGTH_MINUTES: i64 = 30;
13const READ_ONLY_MESSAGE: &str = "Meetings cannot be scheduled in read-only mode.";
14const RESPONSE_FAILED_NOTICE: &str = "Could not send your response";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct Invitee {
18 pub user_id: String,
19 pub name: String,
20 pub mail: Option<String>,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct MeetingDraft {
25 pub subject: String,
26 pub start: DateTime<Utc>,
27 pub end: DateTime<Utc>,
28 pub local_start: NaiveDateTime,
29 pub local_end: NaiveDateTime,
30 pub time_zone_name: Option<String>,
31 pub repeat: Repeat,
32 pub details: String,
33 pub people: Vec<Invitee>,
34}
35
36pub fn default_window(now: DateTime<Utc>, zone: &impl TimeZone) -> (NaiveDateTime, NaiveDateTime) {
37 let local = now.with_timezone(zone).naive_local();
38 let past_half_hour = i64::from(local.minute()) % HALF_HOUR_MINUTES;
39 let start = local
40 .with_second(0)
41 .and_then(|time| time.with_nanosecond(0))
42 .unwrap_or(local)
43 - Duration::minutes(past_half_hour)
44 + Duration::minutes(HALF_HOUR_MINUTES);
45 (start, start + Duration::minutes(DEFAULT_LENGTH_MINUTES))
46}
47
48fn utc_of(zone: &impl TimeZone, date: NaiveDate, time: NaiveTime) -> Option<DateTime<Utc>> {
49 zone.from_local_datetime(&date.and_time(time))
50 .earliest()
51 .map(|moment| moment.with_timezone(&Utc))
52}
53
54#[derive(Debug, Clone)]
55pub struct FormValues {
56 pub subject: String,
57 pub date: Option<NaiveDate>,
58 pub start: NaiveTime,
59 pub end: NaiveTime,
60 pub repeat: Repeat,
61 pub details: String,
62 pub people: Vec<Invitee>,
63}
64
65pub fn draft_from_form(
66 values: FormValues,
67 zone: &impl TimeZone,
68 time_zone_name: Option<String>,
69) -> Result<MeetingDraft, String> {
70 let subject = values.subject.trim();
71 if subject.is_empty() {
72 return Err("Add a title.".to_owned());
73 }
74 let date = values.date.ok_or_else(|| "Pick a date.".to_owned())?;
75 let start = utc_of(zone, date, values.start)
76 .ok_or_else(|| "That start time does not exist.".to_owned())?;
77 let end =
78 utc_of(zone, date, values.end).ok_or_else(|| "That end time does not exist.".to_owned())?;
79 if end <= start {
80 return Err("The end must be after the start.".to_owned());
81 }
82 Ok(MeetingDraft {
83 subject: subject.to_owned(),
84 start,
85 end,
86 local_start: date.and_time(values.start),
87 local_end: date.and_time(values.end),
88 time_zone_name,
89 repeat: values.repeat,
90 details: values.details.trim().to_owned(),
91 people: values.people,
92 })
93}
94
95pub fn attendee_for(invitee: &Invitee, looked_up: Option<String>) -> Result<Attendee, String> {
96 let address = invitee
97 .mail
98 .clone()
99 .or(looked_up)
100 .ok_or_else(|| format!("No email address found for {}.", invitee.name))?;
101 Ok(Attendee {
102 name: invitee.name.clone(),
103 address,
104 })
105}
106
107pub fn response_for(reply: Reply) -> ResponseType {
108 match reply {
109 Reply::Accept => ResponseType::Accepted,
110 Reply::Tentative => ResponseType::Tentative,
111 Reply::Decline => ResponseType::Declined,
112 }
113}
114
115fn demo_event(draft: &MeetingDraft, serial: u64) -> CalendarEvent {
116 CalendarEvent {
117 object_id: format!("demo-new-{serial}"),
118 subject: draft.subject.clone(),
119 start: draft.start,
120 end: draft.end,
121 all_day: false,
122 cancelled: false,
123 online: true,
124 join_url: Some(demo_join_url("demo-new")),
125 thread_id: None,
126 organizer_name: Some("You".to_owned()),
127 organizer_address: None,
128 ical_uid: None,
129 show_as: Default::default(),
130 dial_in: None,
131 response: ResponseType::Organizer,
132 }
133}
134
135impl AppState {
136 pub fn load_own_time_zone(&mut self, cx: &mut Context<Self>) {
137 if self.own_time_zone.is_some() || self.own_time_zone_requested || self.own_email.is_empty()
138 {
139 return;
140 }
141 let Some(launcher) = self.call_launcher.clone() else {
142 return;
143 };
144 self.own_time_zone_requested = true;
145 let mail = self.own_email.clone();
146 let looked_up = runtime::spawn(async move { launcher.time_zone_name(&mail).await });
147 cx.spawn(async move |this, cx| {
148 let time_zone_name = looked_up.await.ok().flatten();
149 this.update(cx, |state, _| {
150 state.own_time_zone_requested = time_zone_name.is_some();
151 state.own_time_zone = time_zone_name;
152 })
153 .ok();
154 })
155 .detach();
156 }
157
158 pub fn create_meeting(
159 &mut self,
160 draft: MeetingDraft,
161 cx: &mut Context<Self>,
162 ) -> oneshot::Receiver<Result<(), String>> {
163 let (sender, receiver) = oneshot::channel();
164 if self.mode.demo {
165 let event = demo_event(&draft, self.demo_meetings.len() as u64 + 1);
166 self.demo_meetings.push(event);
167 self.refresh_calendar(cx);
168 let _ = sender.send(Ok(()));
169 return receiver;
170 }
171 if self.mode.read_only {
172 let _ = sender.send(Err(READ_ONLY_MESSAGE.to_owned()));
173 return receiver;
174 }
175 let Some(launcher) = self.call_launcher.clone() else {
176 let _ = sender.send(Err(NOT_CONNECTED_NOTICE.to_owned()));
177 return receiver;
178 };
179 let created = runtime::spawn(async move { launcher.create_meeting(draft).await });
180 cx.spawn(async move |this, cx| {
181 let outcome = created
182 .await
183 .unwrap_or_else(|_| Err("The request was cancelled.".to_owned()))
184 .map(|_| ());
185 if outcome.is_ok() {
186 this.update(cx, |state, cx| state.refresh_calendar(cx)).ok();
187 }
188 let _ = sender.send(outcome);
189 })
190 .detach();
191 receiver
192 }
193
194 pub fn toggle_rsvp_send_response(&mut self, cx: &mut Context<Self>) {
195 self.rsvp_send_response = !self.rsvp_send_response;
196 cx.notify();
197 }
198
199 fn set_event_response(&mut self, event_id: &str, response: ResponseType) {
200 for event in self
201 .calendar_events
202 .iter_mut()
203 .chain(self.calendar_week.events.iter_mut())
204 .filter(|event| event.object_id == event_id)
205 {
206 event.response = response;
207 }
208 self.calls_list.invalidate();
209 }
210
211 pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {
212 if self.mode.read_only {
213 self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
214 return;
215 }
216 let Some(event) = self
217 .calendar_events
218 .iter()
219 .chain(&self.calendar_week.events)
220 .find(|event| event.object_id == event_key)
221 else {
222 return;
223 };
224 let previous = event.response;
225 let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());
226 self.set_event_response(&event_id, response_for(reply));
227 cx.notify();
228 let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);
229 let Some(launcher) = launcher else {
230 return;
231 };
232 let send_response = self.rsvp_send_response;
233 let answered = runtime::spawn({
234 let event_id = event_id.clone();
235 async move {
236 launcher
237 .respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)
238 .await
239 }
240 });
241 cx.spawn(async move |this, cx| {
242 let sent = answered.await.is_ok_and(|result| result.is_ok());
243 this.update(cx, |state, cx| {
244 if sent {
245 state.refresh_calendar(cx);
246 return;
247 }
248 state.set_event_response(&event_id, previous);
249 state.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
250 })
251 .ok();
252 })
253 .detach();
254 }
255}
256
257#[cfg(test)]
258mod tests {
259 use chrono::FixedOffset;
260
261 use super::*;
262
263 fn utc(hour: u32, minute: u32, second: u32) -> DateTime<Utc> {
264 Utc.with_ymd_and_hms(2026, 10, 13, hour, minute, second)
265 .unwrap()
266 }
267
268 fn plus_two() -> FixedOffset {
269 FixedOffset::east_opt(2 * 3600).unwrap()
270 }
271
272 fn time(hour: u32, minute: u32) -> NaiveTime {
273 NaiveTime::from_hms_opt(hour, minute, 0).unwrap()
274 }
275
276 fn day() -> Option<NaiveDate> {
277 NaiveDate::from_ymd_opt(2026, 10, 14)
278 }
279
280 fn invitee(name: &str, mail: Option<&str>) -> Invitee {
281 Invitee {
282 user_id: format!("id-{name}"),
283 name: name.to_owned(),
284 mail: mail.map(str::to_owned),
285 }
286 }
287
288 #[test]
289 fn the_default_window_starts_at_the_next_half_hour_and_lasts_thirty_minutes() {
290 let (start, end) = default_window(utc(8, 12, 40), &plus_two());
291 assert_eq!(start.to_string(), "2026-10-13 10:30:00");
292 assert_eq!(end.to_string(), "2026-10-13 11:00:00");
293 let (start, _) = default_window(utc(8, 40, 0), &plus_two());
294 assert_eq!(start.to_string(), "2026-10-13 11:00:00");
295 }
296
297 #[test]
298 fn a_time_on_the_half_hour_moves_to_the_following_one() {
299 let (start, _) = default_window(utc(8, 30, 0), &plus_two());
300 assert_eq!(start.to_string(), "2026-10-13 11:00:00");
301 let (start, _) = default_window(utc(8, 0, 0), &plus_two());
302 assert_eq!(start.to_string(), "2026-10-13 10:30:00");
303 }
304
305 #[test]
306 fn the_late_evening_default_rolls_into_the_next_day() {
307 let (start, end) = default_window(utc(21, 45, 0), &plus_two());
308 assert_eq!(start.to_string(), "2026-10-14 00:00:00");
309 assert_eq!(end.to_string(), "2026-10-14 00:30:00");
310 }
311
312 #[test]
313 fn the_form_turns_local_times_into_utc() {
314 let draft = draft_from_form(
315 FormValues {
316 subject: " Planning ".into(),
317 date: day(),
318 start: time(11, 0),
319 end: time(11, 30),
320 repeat: Repeat::Weekly,
321 details: " Agenda ".into(),
322 people: Vec::new(),
323 },
324 &plus_two(),
325 Some("W. Europe Standard Time".into()),
326 )
327 .unwrap();
328 assert_eq!(draft.subject, "Planning");
329 assert_eq!(draft.details, "Agenda");
330 assert_eq!(
331 draft.start,
332 Utc.with_ymd_and_hms(2026, 10, 14, 9, 0, 0).unwrap()
333 );
334 assert_eq!(
335 draft.end,
336 Utc.with_ymd_and_hms(2026, 10, 14, 9, 30, 0).unwrap()
337 );
338 assert_eq!(draft.repeat, Repeat::Weekly);
339 assert_eq!(draft.local_start.to_string(), "2026-10-14 11:00:00");
340 assert_eq!(draft.local_end.to_string(), "2026-10-14 11:30:00");
341 assert_eq!(
342 draft.time_zone_name.as_deref(),
343 Some("W. Europe Standard Time")
344 );
345 }
346
347 #[test]
348 fn the_form_rejects_a_missing_title_date_or_backwards_times() {
349 let build = |subject: &str, date, start, end| {
350 let values = FormValues {
351 subject: subject.into(),
352 date,
353 start,
354 end,
355 repeat: Repeat::Never,
356 details: String::new(),
357 people: Vec::new(),
358 };
359 draft_from_form(values, &plus_two(), None)
360 };
361 assert_eq!(
362 build(" ", day(), time(9, 0), time(10, 0)).unwrap_err(),
363 "Add a title."
364 );
365 assert_eq!(
366 build("x", None, time(9, 0), time(10, 0)).unwrap_err(),
367 "Pick a date."
368 );
369 assert_eq!(
370 build("x", day(), time(10, 0), time(10, 0)).unwrap_err(),
371 "The end must be after the start."
372 );
373 assert!(build("x", day(), time(11, 0), time(10, 0)).is_err());
374 }
375
376 #[test]
377 fn an_invitee_uses_the_known_address_before_a_looked_up_one() {
378 let known = invitee("Mara", Some("mara@example.invalid"));
379 let attendee = attendee_for(&known, Some("other@example.invalid".into())).unwrap();
380 assert_eq!(attendee.address, "mara@example.invalid");
381 let unknown = invitee("Jonas", None);
382 let attendee = attendee_for(&unknown, Some("jonas@example.invalid".into())).unwrap();
383 assert_eq!(attendee.address, "jonas@example.invalid");
384 assert_eq!(attendee.name, "Jonas");
385 }
386
387 #[test]
388 fn an_invitee_without_any_address_is_an_error_naming_the_person() {
389 let error = attendee_for(&invitee("Jonas", None), None).unwrap_err();
390 assert_eq!(error, "No email address found for Jonas.");
391 }
392
393 #[test]
394 fn replies_map_to_the_shown_response() {
395 assert_eq!(response_for(Reply::Accept), ResponseType::Accepted);
396 assert_eq!(response_for(Reply::Tentative), ResponseType::Tentative);
397 assert_eq!(response_for(Reply::Decline), ResponseType::Declined);
398 }
399}