BlueGit

ict rusty-teams

Files

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

schedule.rs

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