BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / own_status.rs

own_status.rs

own_status.rs 19.3 KiB Download Raw
1use std::sync::Arc;
2
3use chrono::{DateTime, Datelike, Duration, NaiveTime, TimeZone, Utc};
4use gpui_kit::*;
5use teams_core::{
6 ForcedAvailability, ForcedKind, PresenceStatus, StatusNote, WorkLocation, WorkLocationKind,
7 WorkLocationSource,
8};
9
10use crate::app_state::{AppEvent, AppState};
11use crate::backend::Engine;
12use crate::data::PresenceKind;
13
14pub const NOTE_LIMIT: usize = 280;
15const WORK_LOCATION_FAILED: &str = "Work location couldn't be set. Try again.";
16pub const STATUS_CHOICES: [ForcedKind; 6] = [
17 ForcedKind::Available,
18 ForcedKind::Busy,
19 ForcedKind::DoNotDisturb,
20 ForcedKind::BeRightBack,
21 ForcedKind::Away,
22 ForcedKind::Offline,
23];
24pub const STATUS_DURATIONS: [StatusDuration; 5] = [
25 StatusDuration::HalfHour,
26 StatusDuration::OneHour,
27 StatusDuration::TwoHours,
28 StatusDuration::Today,
29 StatusDuration::ThisWeek,
30];
31pub const NOTE_DURATIONS: [NoteDuration; 5] = [
32 NoteDuration::Never,
33 NoteDuration::OneHour,
34 NoteDuration::FourHours,
35 NoteDuration::Today,
36 NoteDuration::ThisWeek,
37];
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum StatusDuration {
41 HalfHour,
42 OneHour,
43 TwoHours,
44 Today,
45 ThisWeek,
46}
47
48impl StatusDuration {
49 pub fn label(self) -> &'static str {
50 match self {
51 StatusDuration::HalfHour => "30 minutes",
52 StatusDuration::OneHour => "1 hour",
53 StatusDuration::TwoHours => "2 hours",
54 StatusDuration::Today => "Today",
55 StatusDuration::ThisWeek => "This week",
56 }
57 }
58
59 pub fn expires_at<Zone: TimeZone>(self, now: DateTime<Zone>) -> DateTime<Utc> {
60 match self {
61 StatusDuration::HalfHour => after(&now, Duration::minutes(30)),
62 StatusDuration::OneHour => after(&now, Duration::hours(1)),
63 StatusDuration::TwoHours => after(&now, Duration::hours(2)),
64 StatusDuration::Today => end_of_day(&now),
65 StatusDuration::ThisWeek => end_of_week(&now),
66 }
67 }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum NoteDuration {
72 Never,
73 OneHour,
74 FourHours,
75 Today,
76 ThisWeek,
77}
78
79impl NoteDuration {
80 pub const DEFAULT: NoteDuration = NoteDuration::Today;
81
82 pub fn label(self) -> &'static str {
83 match self {
84 NoteDuration::Never => "Never",
85 NoteDuration::OneHour => "1 hour",
86 NoteDuration::FourHours => "4 hours",
87 NoteDuration::Today => "Today",
88 NoteDuration::ThisWeek => "This week",
89 }
90 }
91
92 pub fn expires_at<Zone: TimeZone>(self, now: DateTime<Zone>) -> Option<DateTime<Utc>> {
93 match self {
94 NoteDuration::Never => None,
95 NoteDuration::OneHour => Some(after(&now, Duration::hours(1))),
96 NoteDuration::FourHours => Some(after(&now, Duration::hours(4))),
97 NoteDuration::Today => Some(end_of_day(&now)),
98 NoteDuration::ThisWeek => Some(end_of_week(&now)),
99 }
100 }
101}
102
103fn after<Zone: TimeZone>(now: &DateTime<Zone>, span: Duration) -> DateTime<Utc> {
104 (now.clone() + span).with_timezone(&Utc)
105}
106
107fn end_of_local_date<Zone: TimeZone>(now: &DateTime<Zone>, days_ahead: i64) -> DateTime<Utc> {
108 let last_moment = NaiveTime::from_hms_milli_opt(23, 59, 59, 999).unwrap_or(NaiveTime::MIN);
109 let date = now.date_naive() + Duration::days(days_ahead);
110 now.timezone()
111 .from_local_datetime(&date.and_time(last_moment))
112 .latest()
113 .map_or_else(
114 || after(now, Duration::days(days_ahead + 1)),
115 |moment| moment.with_timezone(&Utc),
116 )
117}
118
119pub fn end_of_day<Zone: TimeZone>(now: &DateTime<Zone>) -> DateTime<Utc> {
120 end_of_local_date(now, 0)
121}
122
123pub fn end_of_week<Zone: TimeZone>(now: &DateTime<Zone>) -> DateTime<Utc> {
124 let days_since_sunday = i64::from(now.weekday().num_days_from_sunday());
125 end_of_local_date(now, 6 - days_since_sunday)
126}
127
128pub fn choice_label(kind: ForcedKind) -> &'static str {
129 match kind {
130 ForcedKind::Away => "Appear away",
131 ForcedKind::Offline => "Appear offline",
132 other => state_label(other),
133 }
134}
135
136pub fn state_label(kind: ForcedKind) -> &'static str {
137 match kind {
138 ForcedKind::Available => "Available",
139 ForcedKind::Busy => "Busy",
140 ForcedKind::DoNotDisturb => "Do not disturb",
141 ForcedKind::BeRightBack => "Be right back",
142 ForcedKind::Away => "Away",
143 ForcedKind::Offline => "Offline",
144 }
145}
146
147pub fn presence_kind_for(kind: ForcedKind) -> PresenceKind {
148 match kind {
149 ForcedKind::Available => PresenceKind::Available,
150 ForcedKind::Busy => PresenceKind::Busy,
151 ForcedKind::DoNotDisturb => PresenceKind::DoNotDisturb,
152 ForcedKind::BeRightBack | ForcedKind::Away => PresenceKind::Away,
153 ForcedKind::Offline => PresenceKind::Offline,
154 }
155}
156
157pub fn until_label<Zone: TimeZone>(expires_at: DateTime<Utc>, now: &DateTime<Zone>) -> String
158where
159 Zone::Offset: std::fmt::Display,
160{
161 let local = expires_at.with_timezone(&now.timezone());
162 if local.date_naive() == now.date_naive() {
163 format!("until {}", local.format("%H:%M"))
164 } else {
165 format!("until {}", local.format("%a %H:%M"))
166 }
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct StateSummary {
171 pub label: &'static str,
172 pub presence: PresenceKind,
173 pub until: Option<String>,
174}
175
176pub fn state_summary<Zone: TimeZone>(
177 status: &PresenceStatus,
178 live: PresenceKind,
179 now: &DateTime<Zone>,
180) -> StateSummary
181where
182 Zone::Offset: std::fmt::Display,
183{
184 match status.forced {
185 Some(forced) => StateSummary {
186 label: state_label(forced.kind),
187 presence: presence_kind_for(forced.kind),
188 until: forced
189 .expires_at
190 .map(|expires_at| until_label(expires_at, now)),
191 },
192 None => StateSummary {
193 label: match live.label() {
194 "" => "Set status",
195 label => label,
196 },
197 presence: live,
198 until: None,
199 },
200 }
201}
202
203pub fn duration_target(status: &PresenceStatus) -> Option<ForcedKind> {
204 status
205 .forced
206 .map(|forced| forced.kind)
207 .filter(|kind| *kind != ForcedKind::Available)
208}
209
210pub fn with_forced(status: &PresenceStatus, forced: Option<ForcedAvailability>) -> PresenceStatus {
211 let availability = match forced {
212 Some(forced) => forced.kind.code().to_owned(),
213 None => status.availability.clone(),
214 };
215 PresenceStatus {
216 availability,
217 forced,
218 ..status.clone()
219 }
220}
221
222pub fn with_note(status: &PresenceStatus, note: Option<StatusNote>) -> PresenceStatus {
223 PresenceStatus {
224 note,
225 ..status.clone()
226 }
227}
228
229pub fn work_location_label(location: Option<WorkLocation>) -> &'static str {
230 match location {
231 None => "Set work location",
232 Some(WorkLocation {
233 kind: WorkLocationKind::Office,
234 source: WorkLocationSource::Set,
235 }) => "In the office",
236 Some(WorkLocation {
237 kind: WorkLocationKind::Office,
238 source: WorkLocationSource::Scheduled,
239 }) => "Planned in the office",
240 Some(WorkLocation {
241 kind: WorkLocationKind::Office,
242 source: WorkLocationSource::Verified,
243 }) => "Checked in to the office",
244 Some(WorkLocation {
245 kind: WorkLocationKind::Remote,
246 source: WorkLocationSource::Scheduled,
247 }) => "Planned to work remotely",
248 Some(WorkLocation {
249 kind: WorkLocationKind::Remote,
250 ..
251 }) => "Working remotely",
252 }
253}
254
255pub fn with_work_location(
256 status: &PresenceStatus,
257 work_location: Option<WorkLocation>,
258) -> PresenceStatus {
259 PresenceStatus {
260 work_location,
261 ..status.clone()
262 }
263}
264
265pub fn clamp_note(text: &str) -> String {
266 text.chars().take(NOTE_LIMIT).collect()
267}
268
269pub fn demo_status() -> PresenceStatus {
270 PresenceStatus {
271 availability: "Available".to_owned(),
272 ..PresenceStatus::default()
273 }
274}
275
276impl AppState {
277 pub fn own_presence_kind(&self) -> PresenceKind {
278 match &self.directory.me {
279 Some(me) => self.directory.presence_of(&me.user_id).kind(),
280 None => PresenceKind::Unknown,
281 }
282 }
283
284 pub fn set_status_menu_open(&mut self, open: bool, cx: &mut Context<Self>) {
285 if self.status_menu_open != open {
286 self.status_menu_open = open;
287 cx.notify();
288 }
289 }
290
291 pub fn request_status_message(&mut self, cx: &mut Context<Self>) {
292 self.status_message_request = true;
293 cx.emit(AppEvent::StatusMessage);
294 cx.notify();
295 }
296
297 pub fn take_status_message_request(&mut self) -> bool {
298 std::mem::take(&mut self.status_message_request)
299 }
300
301 pub fn refresh_own_status(&mut self, cx: &mut Context<Self>) {
302 let Some(engine) = self.engine.clone().filter(|_| !self.mode.demo) else {
303 return;
304 };
305 drop(crate::runtime::spawn(async move {
306 engine.refresh_own_status().await
307 }));
308 cx.notify();
309 }
310
311 pub fn apply_own_status(&mut self, status: PresenceStatus, cx: &mut Context<Self>) {
312 self.own_status = status;
313 cx.emit(AppEvent::Directory);
314 cx.notify();
315 }
316
317 pub fn set_own_availability(
318 &mut self,
319 forced: Option<ForcedAvailability>,
320 cx: &mut Context<Self>,
321 ) {
322 let Some(engine_or_demo) = self.own_status_engine(cx) else {
323 return;
324 };
325 let previous_status = self.own_status.clone();
326 let previous_presence = self.own_presence_kind();
327 self.own_status = with_forced(&previous_status, forced);
328 if let Some(forced) = forced {
329 self.show_own_presence(presence_kind_for(forced.kind), cx);
330 }
331 let Some(engine) = engine_or_demo else {
332 return;
333 };
334 self.run_chat_action(
335 "Status",
336 async move { engine.set_own_availability(forced).await },
337 move |state, cx| {
338 state.own_status = previous_status;
339 state.show_own_presence(previous_presence, cx);
340 },
341 |_, _| {},
342 cx,
343 );
344 }
345
346 pub fn set_own_status_note(&mut self, note: Option<StatusNote>, cx: &mut Context<Self>) {
347 let Some(engine_or_demo) = self.own_status_engine(cx) else {
348 return;
349 };
350 let previous_status = self.own_status.clone();
351 self.own_status = with_note(&previous_status, note.clone());
352 cx.emit(AppEvent::Directory);
353 cx.notify();
354 let Some(engine) = engine_or_demo else {
355 return;
356 };
357 self.run_chat_action(
358 "Status message",
359 async move { engine.set_own_status_note(note).await },
360 move |state, cx| {
361 state.own_status = previous_status;
362 cx.emit(AppEvent::Directory);
363 cx.notify();
364 },
365 |_, _| {},
366 cx,
367 );
368 }
369
370 pub fn set_own_work_location(
371 &mut self,
372 kind: Option<WorkLocationKind>,
373 cx: &mut Context<Self>,
374 ) {
375 let Some(engine_or_demo) = self.own_status_engine(cx) else {
376 return;
377 };
378 let previous_status = self.own_status.clone();
379 let optimistic = kind.map(|kind| WorkLocation {
380 kind,
381 source: WorkLocationSource::Set,
382 });
383 self.own_status = with_work_location(&previous_status, optimistic);
384 cx.emit(AppEvent::Directory);
385 cx.notify();
386 let Some(engine) = engine_or_demo else {
387 return;
388 };
389 let location = kind.map(|kind| (kind, end_of_day(&chrono::Local::now())));
390 let receiver =
391 crate::runtime::spawn(async move { engine.set_own_work_location(location).await });
392 cx.spawn(async move |this, cx| {
393 let succeeded = matches!(receiver.await, Ok(Ok(())));
394 this.update(cx, |state, cx| {
395 if succeeded {
396 return;
397 }
398 state.own_status = previous_status;
399 state.raise_notice(WORK_LOCATION_FAILED.to_owned(), None, cx);
400 })
401 .ok();
402 })
403 .detach();
404 }
405
406 fn show_own_presence(&mut self, kind: PresenceKind, cx: &mut Context<Self>) {
407 if let Some(me) = self
408 .directory
409 .me
410 .clone()
411 .filter(|_| kind != PresenceKind::Unknown)
412 {
413 self.directory.set_presence(&me.user_id, kind);
414 }
415 cx.emit(AppEvent::Directory);
416 cx.notify();
417 }
418
419 fn own_status_engine(&mut self, cx: &mut Context<Self>) -> Option<Option<Arc<Engine>>> {
420 if self.mode.read_only {
421 self.raise_notice("Read-only mode: status not changed".to_owned(), None, cx);
422 return None;
423 }
424 match self.engine.clone() {
425 Some(engine) => Some(Some(engine)),
426 None if self.mode.demo => Some(None),
427 None => None,
428 }
429 }
430}
431
432#[cfg(test)]
433mod tests {
434 use chrono::{DateTime, Duration, FixedOffset, TimeZone, Utc};
435 use teams_core::{
436 ForcedAvailability, ForcedKind, PresenceStatus, WorkLocation, WorkLocationKind,
437 WorkLocationSource,
438 };
439
440 use super::{
441 NOTE_LIMIT, NoteDuration, STATUS_CHOICES, StateSummary, StatusDuration, choice_label,
442 clamp_note, duration_target, end_of_day, end_of_week, state_summary, until_label,
443 with_forced, work_location_label,
444 };
445 use crate::data::PresenceKind;
446
447 fn zone() -> FixedOffset {
448 FixedOffset::east_opt(2 * 3600).unwrap()
449 }
450
451 fn local(day: u32, hour: u32, minute: u32) -> DateTime<FixedOffset> {
452 zone()
453 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
454 .unwrap()
455 }
456
457 fn utc(day: u32, hour: u32, minute: u32, second: u32) -> DateTime<Utc> {
458 Utc.with_ymd_and_hms(2026, 10, day, hour, minute, second)
459 .unwrap()
460 }
461
462 #[test]
463 fn relative_durations_add_to_now() {
464 let now = local(9, 14, 0);
465 assert_eq!(StatusDuration::HalfHour.expires_at(now), utc(9, 12, 30, 0));
466 assert_eq!(StatusDuration::OneHour.expires_at(now), utc(9, 13, 0, 0));
467 assert_eq!(StatusDuration::TwoHours.expires_at(now), utc(9, 14, 0, 0));
468 assert_eq!(
469 NoteDuration::FourHours.expires_at(now),
470 Some(utc(9, 16, 0, 0))
471 );
472 assert_eq!(
473 NoteDuration::OneHour.expires_at(now),
474 Some(utc(9, 13, 0, 0))
475 );
476 assert_eq!(NoteDuration::Never.expires_at(now), None);
477 }
478
479 #[test]
480 fn today_ends_at_local_midnight() {
481 let expected = utc(9, 21, 59, 59) + Duration::milliseconds(999);
482 assert_eq!(StatusDuration::Today.expires_at(local(9, 14, 0)), expected);
483 assert_eq!(
484 NoteDuration::Today.expires_at(local(9, 0, 5)),
485 Some(expected)
486 );
487 }
488
489 #[test]
490 fn today_uses_the_local_date_not_the_utc_date() {
491 let now = local(10, 0, 30);
492 let expected = utc(10, 21, 59, 59) + Duration::milliseconds(999);
493 assert_eq!(end_of_day(&now), expected);
494 }
495
496 #[test]
497 fn week_ends_saturday_night_with_sunday_as_first_day() {
498 let saturday = utc(10, 21, 59, 59) + Duration::milliseconds(999);
499 let friday = local(9, 14, 0);
500 assert_eq!(StatusDuration::ThisWeek.expires_at(friday), saturday);
501 assert_eq!(end_of_week(&local(10, 8, 0)), saturday);
502 assert_eq!(end_of_week(&local(4, 8, 0)), saturday);
503 let next_saturday = utc(17, 21, 59, 59) + Duration::milliseconds(999);
504 assert_eq!(end_of_week(&local(11, 8, 0)), next_saturday);
505 }
506
507 #[test]
508 fn until_label_shows_the_time_today_and_the_day_later() {
509 let now = local(9, 14, 0);
510 assert_eq!(until_label(utc(9, 13, 30, 0), &now), "until 15:30");
511 assert_eq!(until_label(utc(10, 13, 30, 0), &now), "until Sat 15:30");
512 }
513
514 #[test]
515 fn forced_state_wins_over_the_live_presence_in_the_summary() {
516 let now = local(9, 14, 0);
517 let status = PresenceStatus {
518 forced: Some(ForcedAvailability {
519 kind: ForcedKind::DoNotDisturb,
520 expires_at: Some(utc(9, 13, 30, 0)),
521 }),
522 ..PresenceStatus::default()
523 };
524 assert_eq!(
525 state_summary(&status, PresenceKind::Available, &now),
526 StateSummary {
527 label: "Do not disturb",
528 presence: PresenceKind::DoNotDisturb,
529 until: Some("until 15:30".into()),
530 }
531 );
532 let automatic = state_summary(&PresenceStatus::default(), PresenceKind::Away, &now);
533 assert_eq!(automatic.label, "Away");
534 assert_eq!(automatic.until, None);
535 let unknown = state_summary(&PresenceStatus::default(), PresenceKind::Unknown, &now);
536 assert_eq!(unknown.label, "Set status");
537 }
538
539 #[test]
540 fn duration_needs_a_forced_state_other_than_available() {
541 let forced = |kind| PresenceStatus {
542 forced: Some(ForcedAvailability {
543 kind,
544 expires_at: None,
545 }),
546 ..PresenceStatus::default()
547 };
548 assert_eq!(duration_target(&PresenceStatus::default()), None);
549 assert_eq!(duration_target(&forced(ForcedKind::Available)), None);
550 assert_eq!(
551 duration_target(&forced(ForcedKind::Busy)),
552 Some(ForcedKind::Busy)
553 );
554 }
555
556 #[test]
557 fn optimistic_forced_state_sets_availability_and_reset_keeps_it() {
558 let busy = ForcedAvailability {
559 kind: ForcedKind::Busy,
560 expires_at: None,
561 };
562 let status = with_forced(&PresenceStatus::default(), Some(busy));
563 assert_eq!(status.availability, "Busy");
564 assert_eq!(status.forced, Some(busy));
565 let reset = with_forced(&status, None);
566 assert_eq!(reset.availability, "Busy");
567 assert_eq!(reset.forced, None);
568 }
569
570 #[test]
571 fn note_text_is_cut_at_the_limit_by_characters() {
572 let long = "ä".repeat(NOTE_LIMIT + 20);
573 assert_eq!(clamp_note(&long).chars().count(), NOTE_LIMIT);
574 assert_eq!(clamp_note("short"), "short");
575 }
576
577 #[test]
578 fn work_location_labels_follow_teams() {
579 let location = |kind, source| Some(WorkLocation { kind, source });
580 assert_eq!(work_location_label(None), "Set work location");
581 assert_eq!(
582 work_location_label(location(WorkLocationKind::Office, WorkLocationSource::Set)),
583 "In the office"
584 );
585 assert_eq!(
586 work_location_label(location(
587 WorkLocationKind::Office,
588 WorkLocationSource::Scheduled
589 )),
590 "Planned in the office"
591 );
592 assert_eq!(
593 work_location_label(location(WorkLocationKind::Remote, WorkLocationSource::Set)),
594 "Working remotely"
595 );
596 }
597
598 #[test]
599 fn labels_follow_the_teams_menu() {
600 let labels: Vec<&str> = STATUS_CHOICES
601 .iter()
602 .map(|kind| choice_label(*kind))
603 .collect();
604 assert_eq!(
605 labels,
606 [
607 "Available",
608 "Busy",
609 "Do not disturb",
610 "Be right back",
611 "Appear away",
612 "Appear offline"
613 ]
614 );
615 assert_eq!(NoteDuration::DEFAULT, NoteDuration::Today);
616 }
617}