BlueGit

ict rusty-teams

Files

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

own_status.rs

own_status.rs 19.4 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 open_notification_settings(&mut self, cx: &mut Context<Self>) {
302 cx.emit(AppEvent::NotificationSettings);
303 }
304
305 pub fn refresh_own_status(&mut self, cx: &mut Context<Self>) {
306 let Some(engine) = self.engine.clone().filter(|_| !self.mode.demo) else {
307 return;
308 };
309 drop(crate::runtime::spawn(async move {
310 engine.refresh_own_status().await
311 }));
312 cx.notify();
313 }
314
315 pub fn apply_own_status(&mut self, status: PresenceStatus, cx: &mut Context<Self>) {
316 self.own_status = status;
317 cx.emit(AppEvent::Directory);
318 cx.notify();
319 }
320
321 pub fn set_own_availability(
322 &mut self,
323 forced: Option<ForcedAvailability>,
324 cx: &mut Context<Self>,
325 ) {
326 let Some(engine_or_demo) = self.own_status_engine(cx) else {
327 return;
328 };
329 let previous_status = self.own_status.clone();
330 let previous_presence = self.own_presence_kind();
331 self.own_status = with_forced(&previous_status, forced);
332 if let Some(forced) = forced {
333 self.show_own_presence(presence_kind_for(forced.kind), cx);
334 }
335 let Some(engine) = engine_or_demo else {
336 return;
337 };
338 self.run_chat_action(
339 "Status",
340 async move { engine.set_own_availability(forced).await },
341 move |state, cx| {
342 state.own_status = previous_status;
343 state.show_own_presence(previous_presence, cx);
344 },
345 |_, _| {},
346 cx,
347 );
348 }
349
350 pub fn set_own_status_note(&mut self, note: Option<StatusNote>, cx: &mut Context<Self>) {
351 let Some(engine_or_demo) = self.own_status_engine(cx) else {
352 return;
353 };
354 let previous_status = self.own_status.clone();
355 self.own_status = with_note(&previous_status, note.clone());
356 cx.emit(AppEvent::Directory);
357 cx.notify();
358 let Some(engine) = engine_or_demo else {
359 return;
360 };
361 self.run_chat_action(
362 "Status message",
363 async move { engine.set_own_status_note(note).await },
364 move |state, cx| {
365 state.own_status = previous_status;
366 cx.emit(AppEvent::Directory);
367 cx.notify();
368 },
369 |_, _| {},
370 cx,
371 );
372 }
373
374 pub fn set_own_work_location(
375 &mut self,
376 kind: Option<WorkLocationKind>,
377 cx: &mut Context<Self>,
378 ) {
379 let Some(engine_or_demo) = self.own_status_engine(cx) else {
380 return;
381 };
382 let previous_status = self.own_status.clone();
383 let optimistic = kind.map(|kind| WorkLocation {
384 kind,
385 source: WorkLocationSource::Set,
386 });
387 self.own_status = with_work_location(&previous_status, optimistic);
388 cx.emit(AppEvent::Directory);
389 cx.notify();
390 let Some(engine) = engine_or_demo else {
391 return;
392 };
393 let location = kind.map(|kind| (kind, end_of_day(&chrono::Local::now())));
394 let receiver =
395 crate::runtime::spawn(async move { engine.set_own_work_location(location).await });
396 cx.spawn(async move |this, cx| {
397 let succeeded = matches!(receiver.await, Ok(Ok(())));
398 this.update(cx, |state, cx| {
399 if succeeded {
400 return;
401 }
402 state.own_status = previous_status;
403 state.raise_notice(WORK_LOCATION_FAILED.to_owned(), None, cx);
404 })
405 .ok();
406 })
407 .detach();
408 }
409
410 fn show_own_presence(&mut self, kind: PresenceKind, cx: &mut Context<Self>) {
411 if let Some(me) = self
412 .directory
413 .me
414 .clone()
415 .filter(|_| kind != PresenceKind::Unknown)
416 {
417 self.directory.set_presence(&me.user_id, kind);
418 }
419 cx.emit(AppEvent::Directory);
420 cx.notify();
421 }
422
423 fn own_status_engine(&mut self, cx: &mut Context<Self>) -> Option<Option<Arc<Engine>>> {
424 if self.mode.read_only {
425 self.raise_notice("Read-only mode: status not changed".to_owned(), None, cx);
426 return None;
427 }
428 match self.engine.clone() {
429 Some(engine) => Some(Some(engine)),
430 None if self.mode.demo => Some(None),
431 None => None,
432 }
433 }
434}
435
436#[cfg(test)]
437mod tests {
438 use chrono::{DateTime, Duration, FixedOffset, TimeZone, Utc};
439 use teams_core::{
440 ForcedAvailability, ForcedKind, PresenceStatus, WorkLocation, WorkLocationKind,
441 WorkLocationSource,
442 };
443
444 use super::{
445 NOTE_LIMIT, NoteDuration, STATUS_CHOICES, StateSummary, StatusDuration, choice_label,
446 clamp_note, duration_target, end_of_day, end_of_week, state_summary, until_label,
447 with_forced, work_location_label,
448 };
449 use crate::data::PresenceKind;
450
451 fn zone() -> FixedOffset {
452 FixedOffset::east_opt(2 * 3600).unwrap()
453 }
454
455 fn local(day: u32, hour: u32, minute: u32) -> DateTime<FixedOffset> {
456 zone()
457 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
458 .unwrap()
459 }
460
461 fn utc(day: u32, hour: u32, minute: u32, second: u32) -> DateTime<Utc> {
462 Utc.with_ymd_and_hms(2026, 10, day, hour, minute, second)
463 .unwrap()
464 }
465
466 #[test]
467 fn relative_durations_add_to_now() {
468 let now = local(9, 14, 0);
469 assert_eq!(StatusDuration::HalfHour.expires_at(now), utc(9, 12, 30, 0));
470 assert_eq!(StatusDuration::OneHour.expires_at(now), utc(9, 13, 0, 0));
471 assert_eq!(StatusDuration::TwoHours.expires_at(now), utc(9, 14, 0, 0));
472 assert_eq!(
473 NoteDuration::FourHours.expires_at(now),
474 Some(utc(9, 16, 0, 0))
475 );
476 assert_eq!(
477 NoteDuration::OneHour.expires_at(now),
478 Some(utc(9, 13, 0, 0))
479 );
480 assert_eq!(NoteDuration::Never.expires_at(now), None);
481 }
482
483 #[test]
484 fn today_ends_at_local_midnight() {
485 let expected = utc(9, 21, 59, 59) + Duration::milliseconds(999);
486 assert_eq!(StatusDuration::Today.expires_at(local(9, 14, 0)), expected);
487 assert_eq!(
488 NoteDuration::Today.expires_at(local(9, 0, 5)),
489 Some(expected)
490 );
491 }
492
493 #[test]
494 fn today_uses_the_local_date_not_the_utc_date() {
495 let now = local(10, 0, 30);
496 let expected = utc(10, 21, 59, 59) + Duration::milliseconds(999);
497 assert_eq!(end_of_day(&now), expected);
498 }
499
500 #[test]
501 fn week_ends_saturday_night_with_sunday_as_first_day() {
502 let saturday = utc(10, 21, 59, 59) + Duration::milliseconds(999);
503 let friday = local(9, 14, 0);
504 assert_eq!(StatusDuration::ThisWeek.expires_at(friday), saturday);
505 assert_eq!(end_of_week(&local(10, 8, 0)), saturday);
506 assert_eq!(end_of_week(&local(4, 8, 0)), saturday);
507 let next_saturday = utc(17, 21, 59, 59) + Duration::milliseconds(999);
508 assert_eq!(end_of_week(&local(11, 8, 0)), next_saturday);
509 }
510
511 #[test]
512 fn until_label_shows_the_time_today_and_the_day_later() {
513 let now = local(9, 14, 0);
514 assert_eq!(until_label(utc(9, 13, 30, 0), &now), "until 15:30");
515 assert_eq!(until_label(utc(10, 13, 30, 0), &now), "until Sat 15:30");
516 }
517
518 #[test]
519 fn forced_state_wins_over_the_live_presence_in_the_summary() {
520 let now = local(9, 14, 0);
521 let status = PresenceStatus {
522 forced: Some(ForcedAvailability {
523 kind: ForcedKind::DoNotDisturb,
524 expires_at: Some(utc(9, 13, 30, 0)),
525 }),
526 ..PresenceStatus::default()
527 };
528 assert_eq!(
529 state_summary(&status, PresenceKind::Available, &now),
530 StateSummary {
531 label: "Do not disturb",
532 presence: PresenceKind::DoNotDisturb,
533 until: Some("until 15:30".into()),
534 }
535 );
536 let automatic = state_summary(&PresenceStatus::default(), PresenceKind::Away, &now);
537 assert_eq!(automatic.label, "Away");
538 assert_eq!(automatic.until, None);
539 let unknown = state_summary(&PresenceStatus::default(), PresenceKind::Unknown, &now);
540 assert_eq!(unknown.label, "Set status");
541 }
542
543 #[test]
544 fn duration_needs_a_forced_state_other_than_available() {
545 let forced = |kind| PresenceStatus {
546 forced: Some(ForcedAvailability {
547 kind,
548 expires_at: None,
549 }),
550 ..PresenceStatus::default()
551 };
552 assert_eq!(duration_target(&PresenceStatus::default()), None);
553 assert_eq!(duration_target(&forced(ForcedKind::Available)), None);
554 assert_eq!(
555 duration_target(&forced(ForcedKind::Busy)),
556 Some(ForcedKind::Busy)
557 );
558 }
559
560 #[test]
561 fn optimistic_forced_state_sets_availability_and_reset_keeps_it() {
562 let busy = ForcedAvailability {
563 kind: ForcedKind::Busy,
564 expires_at: None,
565 };
566 let status = with_forced(&PresenceStatus::default(), Some(busy));
567 assert_eq!(status.availability, "Busy");
568 assert_eq!(status.forced, Some(busy));
569 let reset = with_forced(&status, None);
570 assert_eq!(reset.availability, "Busy");
571 assert_eq!(reset.forced, None);
572 }
573
574 #[test]
575 fn note_text_is_cut_at_the_limit_by_characters() {
576 let long = "ä".repeat(NOTE_LIMIT + 20);
577 assert_eq!(clamp_note(&long).chars().count(), NOTE_LIMIT);
578 assert_eq!(clamp_note("short"), "short");
579 }
580
581 #[test]
582 fn work_location_labels_follow_teams() {
583 let location = |kind, source| Some(WorkLocation { kind, source });
584 assert_eq!(work_location_label(None), "Set work location");
585 assert_eq!(
586 work_location_label(location(WorkLocationKind::Office, WorkLocationSource::Set)),
587 "In the office"
588 );
589 assert_eq!(
590 work_location_label(location(
591 WorkLocationKind::Office,
592 WorkLocationSource::Scheduled
593 )),
594 "Planned in the office"
595 );
596 assert_eq!(
597 work_location_label(location(WorkLocationKind::Remote, WorkLocationSource::Set)),
598 "Working remotely"
599 );
600 }
601
602 #[test]
603 fn labels_follow_the_teams_menu() {
604 let labels: Vec<&str> = STATUS_CHOICES
605 .iter()
606 .map(|kind| choice_label(*kind))
607 .collect();
608 assert_eq!(
609 labels,
610 [
611 "Available",
612 "Busy",
613 "Do not disturb",
614 "Be right back",
615 "Appear away",
616 "Appear offline"
617 ]
618 );
619 assert_eq!(NoteDuration::DEFAULT, NoteDuration::Today);
620 }
621}