BlueGit

ict rusty-teams

Files

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

schedule.rs

schedule.rs 13.1 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 response: ResponseType::Organizer,
130 }
131}
132
133impl AppState {
134 pub fn load_own_time_zone(&mut self, cx: &mut Context<Self>) {
135 if self.own_time_zone.is_some() || self.own_time_zone_requested || self.own_email.is_empty()
136 {
137 return;
138 }
139 let Some(launcher) = self.call_launcher.clone() else {
140 return;
141 };
142 self.own_time_zone_requested = true;
143 let mail = self.own_email.clone();
144 let looked_up = runtime::spawn(async move { launcher.time_zone_name(&mail).await });
145 cx.spawn(async move |this, cx| {
146 let time_zone_name = looked_up.await.ok().flatten();
147 this.update(cx, |state, _| {
148 state.own_time_zone_requested = time_zone_name.is_some();
149 state.own_time_zone = time_zone_name;
150 })
151 .ok();
152 })
153 .detach();
154 }
155
156 pub fn create_meeting(
157 &mut self,
158 draft: MeetingDraft,
159 cx: &mut Context<Self>,
160 ) -> oneshot::Receiver<Result<(), String>> {
161 let (sender, receiver) = oneshot::channel();
162 if self.mode.demo {
163 let event = demo_event(&draft, self.demo_meetings.len() as u64 + 1);
164 self.demo_meetings.push(event);
165 self.refresh_calendar(cx);
166 let _ = sender.send(Ok(()));
167 return receiver;
168 }
169 if self.mode.read_only {
170 let _ = sender.send(Err(READ_ONLY_MESSAGE.to_owned()));
171 return receiver;
172 }
173 let Some(launcher) = self.call_launcher.clone() else {
174 let _ = sender.send(Err(NOT_CONNECTED_NOTICE.to_owned()));
175 return receiver;
176 };
177 let created = runtime::spawn(async move { launcher.create_meeting(draft).await });
178 cx.spawn(async move |this, cx| {
179 let outcome = created
180 .await
181 .unwrap_or_else(|_| Err("The request was cancelled.".to_owned()))
182 .map(|_| ());
183 if outcome.is_ok() {
184 this.update(cx, |state, cx| state.refresh_calendar(cx)).ok();
185 }
186 let _ = sender.send(outcome);
187 })
188 .detach();
189 receiver
190 }
191
192 pub fn toggle_rsvp_send_response(&mut self, cx: &mut Context<Self>) {
193 self.rsvp_send_response = !self.rsvp_send_response;
194 cx.notify();
195 }
196
197 fn set_event_response(&mut self, event_id: &str, response: ResponseType) {
198 for event in self
199 .calendar_events
200 .iter_mut()
201 .chain(self.calendar_week.events.iter_mut())
202 .filter(|event| event.object_id == event_id)
203 {
204 event.response = response;
205 }
206 self.calls_list.invalidate();
207 }
208
209 pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {
210 if self.mode.read_only {
211 self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
212 return;
213 }
214 let Some(event) = self
215 .calendar_events
216 .iter()
217 .chain(&self.calendar_week.events)
218 .find(|event| event.object_id == event_key)
219 else {
220 return;
221 };
222 let previous = event.response;
223 let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());
224 self.set_event_response(&event_id, response_for(reply));
225 cx.notify();
226 let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);
227 let Some(launcher) = launcher else {
228 return;
229 };
230 let send_response = self.rsvp_send_response;
231 let answered = runtime::spawn({
232 let event_id = event_id.clone();
233 async move {
234 launcher
235 .respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)
236 .await
237 }
238 });
239 cx.spawn(async move |this, cx| {
240 let sent = answered.await.is_ok_and(|result| result.is_ok());
241 this.update(cx, |state, cx| {
242 if sent {
243 state.refresh_calendar(cx);
244 return;
245 }
246 state.set_event_response(&event_id, previous);
247 state.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
248 })
249 .ok();
250 })
251 .detach();
252 }
253}
254
255#[cfg(test)]
256mod tests {
257 use chrono::FixedOffset;
258
259 use super::*;
260
261 fn utc(hour: u32, minute: u32, second: u32) -> DateTime<Utc> {
262 Utc.with_ymd_and_hms(2026, 10, 13, hour, minute, second)
263 .unwrap()
264 }
265
266 fn plus_two() -> FixedOffset {
267 FixedOffset::east_opt(2 * 3600).unwrap()
268 }
269
270 fn time(hour: u32, minute: u32) -> NaiveTime {
271 NaiveTime::from_hms_opt(hour, minute, 0).unwrap()
272 }
273
274 fn day() -> Option<NaiveDate> {
275 NaiveDate::from_ymd_opt(2026, 10, 14)
276 }
277
278 fn invitee(name: &str, mail: Option<&str>) -> Invitee {
279 Invitee {
280 user_id: format!("id-{name}"),
281 name: name.to_owned(),
282 mail: mail.map(str::to_owned),
283 }
284 }
285
286 #[test]
287 fn the_default_window_starts_at_the_next_half_hour_and_lasts_thirty_minutes() {
288 let (start, end) = default_window(utc(8, 12, 40), &plus_two());
289 assert_eq!(start.to_string(), "2026-10-13 10:30:00");
290 assert_eq!(end.to_string(), "2026-10-13 11:00:00");
291 let (start, _) = default_window(utc(8, 40, 0), &plus_two());
292 assert_eq!(start.to_string(), "2026-10-13 11:00:00");
293 }
294
295 #[test]
296 fn a_time_on_the_half_hour_moves_to_the_following_one() {
297 let (start, _) = default_window(utc(8, 30, 0), &plus_two());
298 assert_eq!(start.to_string(), "2026-10-13 11:00:00");
299 let (start, _) = default_window(utc(8, 0, 0), &plus_two());
300 assert_eq!(start.to_string(), "2026-10-13 10:30:00");
301 }
302
303 #[test]
304 fn the_late_evening_default_rolls_into_the_next_day() {
305 let (start, end) = default_window(utc(21, 45, 0), &plus_two());
306 assert_eq!(start.to_string(), "2026-10-14 00:00:00");
307 assert_eq!(end.to_string(), "2026-10-14 00:30:00");
308 }
309
310 #[test]
311 fn the_form_turns_local_times_into_utc() {
312 let draft = draft_from_form(
313 FormValues {
314 subject: " Planning ".into(),
315 date: day(),
316 start: time(11, 0),
317 end: time(11, 30),
318 repeat: Repeat::Weekly,
319 details: " Agenda ".into(),
320 people: Vec::new(),
321 },
322 &plus_two(),
323 Some("W. Europe Standard Time".into()),
324 )
325 .unwrap();
326 assert_eq!(draft.subject, "Planning");
327 assert_eq!(draft.details, "Agenda");
328 assert_eq!(
329 draft.start,
330 Utc.with_ymd_and_hms(2026, 10, 14, 9, 0, 0).unwrap()
331 );
332 assert_eq!(
333 draft.end,
334 Utc.with_ymd_and_hms(2026, 10, 14, 9, 30, 0).unwrap()
335 );
336 assert_eq!(draft.repeat, Repeat::Weekly);
337 assert_eq!(draft.local_start.to_string(), "2026-10-14 11:00:00");
338 assert_eq!(draft.local_end.to_string(), "2026-10-14 11:30:00");
339 assert_eq!(
340 draft.time_zone_name.as_deref(),
341 Some("W. Europe Standard Time")
342 );
343 }
344
345 #[test]
346 fn the_form_rejects_a_missing_title_date_or_backwards_times() {
347 let build = |subject: &str, date, start, end| {
348 let values = FormValues {
349 subject: subject.into(),
350 date,
351 start,
352 end,
353 repeat: Repeat::Never,
354 details: String::new(),
355 people: Vec::new(),
356 };
357 draft_from_form(values, &plus_two(), None)
358 };
359 assert_eq!(
360 build(" ", day(), time(9, 0), time(10, 0)).unwrap_err(),
361 "Add a title."
362 );
363 assert_eq!(
364 build("x", None, time(9, 0), time(10, 0)).unwrap_err(),
365 "Pick a date."
366 );
367 assert_eq!(
368 build("x", day(), time(10, 0), time(10, 0)).unwrap_err(),
369 "The end must be after the start."
370 );
371 assert!(build("x", day(), time(11, 0), time(10, 0)).is_err());
372 }
373
374 #[test]
375 fn an_invitee_uses_the_known_address_before_a_looked_up_one() {
376 let known = invitee("Mara", Some("mara@example.invalid"));
377 let attendee = attendee_for(&known, Some("other@example.invalid".into())).unwrap();
378 assert_eq!(attendee.address, "mara@example.invalid");
379 let unknown = invitee("Jonas", None);
380 let attendee = attendee_for(&unknown, Some("jonas@example.invalid".into())).unwrap();
381 assert_eq!(attendee.address, "jonas@example.invalid");
382 assert_eq!(attendee.name, "Jonas");
383 }
384
385 #[test]
386 fn an_invitee_without_any_address_is_an_error_naming_the_person() {
387 let error = attendee_for(&invitee("Jonas", None), None).unwrap_err();
388 assert_eq!(error, "No email address found for Jonas.");
389 }
390
391 #[test]
392 fn replies_map_to_the_shown_response() {
393 assert_eq!(response_for(Reply::Accept), ResponseType::Accepted);
394 assert_eq!(response_for(Reply::Tentative), ResponseType::Tentative);
395 assert_eq!(response_for(Reply::Decline), ResponseType::Declined);
396 }
397}