BlueGit

ict rusty-teams

Files

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

schedule.rs

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