BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / notify / rules.rs

rules.rs

rules.rs 22.5 KiB Download Raw
1use std::collections::HashMap;
2use std::time::{Duration, Instant};
3
4use calling::Progress;
5use chrono::{DateTime, Utc};
6use store::{ChannelNotificationLevel, ChannelNotifications, MessageImportance};
7
8use super::sound_settings::SoundSettings;
9use super::sounds::Ringtone;
10use crate::call::{CallKind, CallModel};
11
12pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum Corner {
16 TopLeft,
17 TopRight,
18 BottomLeft,
19 #[default]
20 BottomRight,
21}
22
23impl Corner {
24 pub const ALL: [Corner; 4] = [
25 Corner::TopLeft,
26 Corner::TopRight,
27 Corner::BottomLeft,
28 Corner::BottomRight,
29 ];
30
31 pub fn label(self) -> &'static str {
32 match self {
33 Corner::TopLeft => "Top left",
34 Corner::TopRight => "Top right",
35 Corner::BottomLeft => "Bottom left",
36 Corner::BottomRight => "Bottom right",
37 }
38 }
39
40 pub fn key(self) -> &'static str {
41 match self {
42 Corner::TopLeft => "top_left",
43 Corner::TopRight => "top_right",
44 Corner::BottomLeft => "bottom_left",
45 Corner::BottomRight => "bottom_right",
46 }
47 }
48
49 pub fn from_key(key: &str) -> Option<Corner> {
50 Corner::ALL.into_iter().find(|corner| corner.key() == key)
51 }
52
53 pub fn is_bottom(self) -> bool {
54 matches!(self, Corner::BottomLeft | Corner::BottomRight)
55 }
56
57 pub fn is_right(self) -> bool {
58 matches!(self, Corner::TopRight | Corner::BottomRight)
59 }
60
61 pub fn next(self) -> Corner {
62 let index = Corner::ALL
63 .iter()
64 .position(|corner| *corner == self)
65 .unwrap_or(0);
66 Corner::ALL[(index + 1) % Corner::ALL.len()]
67 }
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Settings {
72 pub mentions_only: bool,
73 pub preview: bool,
74 pub corner: Corner,
75 pub flash: bool,
76 pub close_to_tray: bool,
77 pub do_not_disturb: bool,
78 pub mute_in_calls: bool,
79 pub sounds: SoundSettings,
80}
81
82impl Default for Settings {
83 fn default() -> Self {
84 Settings {
85 mentions_only: false,
86 preview: true,
87 corner: Corner::BottomRight,
88 flash: true,
89 close_to_tray: true,
90 do_not_disturb: false,
91 mute_in_calls: false,
92 sounds: SoundSettings::default(),
93 }
94 }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum ChatKind {
99 Direct,
100 Group { member_count: usize },
101 Channel { team: String, channel: String },
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum Preview {
106 Text(String),
107 Image,
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
111pub struct ChannelSignals {
112 pub mentions_channel: bool,
113 pub in_my_thread: bool,
114 pub hidden: bool,
115 pub is_reply: bool,
116 pub notifications: ChannelNotifications,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct Incoming {
121 pub conversation_id: String,
122 pub message_id: String,
123 pub kind: ChatKind,
124 pub chat_title: String,
125 pub sender_id: Option<String>,
126 pub sender_name: String,
127 pub preview: Preview,
128 pub mentions_me: bool,
129 pub muted: bool,
130 pub signals: ChannelSignals,
131 pub created_at: DateTime<Utc>,
132 pub importance: MessageImportance,
133}
134
135impl Incoming {
136 pub fn is_direct(&self) -> bool {
137 self.kind == ChatKind::Direct
138 }
139
140 pub fn is_urgent(&self) -> bool {
141 self.importance == MessageImportance::Urgent
142 }
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
146pub struct Environment {
147 pub chat_in_foreground: bool,
148 pub system_quiet: bool,
149 pub own_do_not_disturb: bool,
150 pub own_busy: bool,
151 pub in_call: bool,
152}
153
154impl Environment {
155 pub fn busy(&self) -> bool {
156 self.in_call || self.own_busy
157 }
158}
159
160pub fn in_call(server_in_call: bool, native_call: Option<&CallModel>) -> bool {
161 server_in_call || native_call.is_some_and(CallModel::is_active)
162}
163
164pub fn should_ringback(native_call: Option<&CallModel>) -> bool {
165 native_call.is_some_and(|model| {
166 !model.incoming
167 && model.kind != CallKind::Meeting
168 && model.is_connecting()
169 && matches!(model.progress, Some(Progress::Calling | Progress::Ringing))
170 })
171}
172
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub struct Decision {
175 pub toast: bool,
176 pub sound: bool,
177 pub urgent_sound: bool,
178}
179
180pub fn alerts(incoming: &Incoming) -> bool {
181 channel_alerts(incoming) && (!incoming.muted || incoming.mentions_me)
182}
183
184fn channel_alerts(incoming: &Incoming) -> bool {
185 if !matches!(incoming.kind, ChatKind::Channel { .. }) || incoming.mentions_me {
186 return true;
187 }
188 let signals = incoming.signals;
189 if signals.hidden {
190 return false;
191 }
192 if signals.mentions_channel || signals.in_my_thread {
193 return true;
194 }
195 let notifications = signals.notifications;
196 notifications.level != ChannelNotificationLevel::Off
197 && (!signals.is_reply || notifications.include_replies)
198}
199
200fn channel_toasts(incoming: &Incoming) -> bool {
201 if !matches!(incoming.kind, ChatKind::Channel { .. }) || incoming.mentions_me {
202 return true;
203 }
204 let signals = incoming.signals;
205 signals.mentions_channel
206 || signals.in_my_thread
207 || signals.notifications.level == ChannelNotificationLevel::BannerAndFeed
208}
209
210const SILENT: Decision = Decision {
211 toast: false,
212 sound: false,
213 urgent_sound: false,
214};
215
216/// Teams lets urgent messages through Do not disturb ("You'll only get notifications for urgent messages and from your priority contacts").
217pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
218 let urgent = incoming.is_urgent();
219 let suppressed = !alerts(incoming)
220 || !channel_toasts(incoming)
221 || environment.chat_in_foreground
222 || environment.system_quiet
223 || (environment.own_do_not_disturb && !urgent)
224 || settings.do_not_disturb
225 || (settings.mute_in_calls && environment.in_call)
226 || (settings.mentions_only && !incoming.mentions_me && !incoming.is_direct() && !urgent);
227 if suppressed {
228 return SILENT;
229 }
230 let busy_allows = settings.sounds.sound_when_busy || !environment.busy();
231 let urgent_sound = urgent && settings.sounds.urgent_sound && busy_allows;
232 Decision {
233 toast: true,
234 sound: urgent_sound || (!urgent && settings.sounds.notification_sound && busy_allows),
235 urgent_sound,
236 }
237}
238
239fn busy_allows_sound(settings: &Settings, busy: bool) -> bool {
240 !busy || settings.sounds.sound_when_busy
241}
242
243pub fn ringtone_for(settings: &Settings, in_call: bool, busy: bool) -> Option<Ringtone> {
244 let audible = settings.sounds.call_and_meeting_sound && busy_allows_sound(settings, busy);
245 audible.then_some(if in_call {
246 Ringtone::Beep
247 } else {
248 settings.sounds.ringtones.regular
249 })
250}
251
252pub fn meeting_start_sound(settings: &Settings, busy: bool) -> bool {
253 settings.sounds.call_and_meeting_sound && busy_allows_sound(settings, busy)
254}
255
256#[derive(Default)]
257pub struct SoundThrottle {
258 last_played: HashMap<String, Instant>,
259}
260
261impl SoundThrottle {
262 pub fn allow(&mut self, conversation_id: &str, now: Instant) -> bool {
263 let allowed = self
264 .last_played
265 .get(conversation_id)
266 .is_none_or(|last| now.duration_since(*last) >= SOUND_THROTTLE);
267 if allowed {
268 self.last_played.insert(conversation_id.to_owned(), now);
269 }
270 allowed
271 }
272}
273
274pub fn should_flash(settings: &Settings, toast_shown: bool, window_active: bool) -> bool {
275 settings.flash && toast_shown && !window_active
276}
277
278#[cfg(test)]
279mod tests {
280 use calling::{CallState, EndReason};
281
282 use super::*;
283
284 fn incoming(kind: ChatKind) -> Incoming {
285 Incoming {
286 conversation_id: "chat".into(),
287 message_id: "1".into(),
288 kind,
289 chat_title: "Chat".into(),
290 sender_id: Some("u1".into()),
291 sender_name: "Mara".into(),
292 preview: Preview::Text("Hello".into()),
293 mentions_me: false,
294 muted: false,
295 signals: ChannelSignals::default(),
296 created_at: Utc::now(),
297 importance: Default::default(),
298 }
299 }
300
301 fn channel() -> Incoming {
302 incoming(ChatKind::Channel {
303 team: "Team".into(),
304 channel: "General".into(),
305 })
306 }
307
308 fn group() -> Incoming {
309 incoming(ChatKind::Group { member_count: 5 })
310 }
311
312 #[test]
313 fn plain_message_gets_toast_and_sound() {
314 let decision = decide(&Settings::default(), &group(), Environment::default());
315 assert_eq!(
316 decision,
317 Decision {
318 toast: true,
319 sound: true,
320 urgent_sound: false,
321 }
322 );
323 }
324
325 #[test]
326 fn foreground_chat_is_silent() {
327 let environment = Environment {
328 chat_in_foreground: true,
329 ..Default::default()
330 };
331 assert_eq!(decide(&Settings::default(), &group(), environment), SILENT);
332 }
333
334 #[test]
335 fn focus_assist_and_dnd_are_silent() {
336 for environment in [
337 Environment {
338 system_quiet: true,
339 ..Default::default()
340 },
341 Environment {
342 own_do_not_disturb: true,
343 ..Default::default()
344 },
345 ] {
346 assert_eq!(decide(&Settings::default(), &group(), environment), SILENT);
347 }
348 let settings = Settings {
349 do_not_disturb: true,
350 ..Default::default()
351 };
352 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
353 }
354
355 fn urgent() -> Incoming {
356 Incoming {
357 importance: MessageImportance::Urgent,
358 ..group()
359 }
360 }
361
362 #[test]
363 fn urgent_passes_do_not_disturb_and_mentions_only_with_the_urgent_sound() {
364 let dnd = Environment {
365 own_do_not_disturb: true,
366 ..Default::default()
367 };
368 assert_eq!(
369 decide(&Settings::default(), &urgent(), dnd),
370 Decision {
371 toast: true,
372 sound: true,
373 urgent_sound: true,
374 }
375 );
376 let mentions_only = Settings {
377 mentions_only: true,
378 ..Default::default()
379 };
380 assert!(decide(&mentions_only, &urgent(), Environment::default()).toast);
381 let foreground = Environment {
382 chat_in_foreground: true,
383 ..Default::default()
384 };
385 assert_eq!(decide(&Settings::default(), &urgent(), foreground), SILENT);
386 }
387
388 #[test]
389 fn urgent_sound_follows_its_own_setting() {
390 let mut settings = Settings::default();
391 settings.sounds.urgent_sound = false;
392 let decision = decide(&settings, &urgent(), Environment::default());
393 assert!(decision.toast && !decision.sound && !decision.urgent_sound);
394 settings.sounds.urgent_sound = true;
395 settings.sounds.notification_sound = false;
396 let decision = decide(&settings, &urgent(), Environment::default());
397 assert!(decision.sound && decision.urgent_sound);
398 let important = Incoming {
399 importance: MessageImportance::High,
400 ..group()
401 };
402 assert!(!decide(&settings, &important, Environment::default()).sound);
403 }
404
405 #[test]
406 fn in_call_follows_server_presence_or_a_live_native_call() {
407 let model = |state| {
408 let mut model = CallModel::incoming("Bea", "8:orgid:b", "Bea");
409 model.state = state;
410 model
411 };
412 let since = std::time::Instant::now();
413 assert!(!in_call(false, None));
414 assert!(in_call(true, None));
415 assert!(in_call(false, Some(&model(CallState::Connecting))));
416 assert!(in_call(false, Some(&model(CallState::Connected { since }))));
417 assert!(in_call(
418 false,
419 Some(&model(CallState::Reconnecting { since }))
420 ));
421 assert!(!in_call(false, Some(&model(CallState::Idle))));
422 assert!(!in_call(
423 false,
424 Some(&model(CallState::Ended {
425 reason: EndReason::LocalHangup
426 }))
427 ));
428 }
429
430 #[test]
431 fn ringback_plays_only_while_an_outgoing_non_meeting_call_is_connecting() {
432 let callees = [("8:orgid:a".to_owned(), "Ana".to_owned())];
433 let outgoing = |progress: Option<Progress>, state: CallState| {
434 let mut model = CallModel::people("Ana", &callees);
435 model.progress = progress;
436 model.state = state;
437 model
438 };
439 let since = std::time::Instant::now();
440 assert!(!should_ringback(None));
441 assert!(!should_ringback(Some(&outgoing(
442 None,
443 CallState::Connecting
444 ))));
445 assert!(should_ringback(Some(&outgoing(
446 Some(Progress::Calling),
447 CallState::Connecting
448 ))));
449 assert!(should_ringback(Some(&outgoing(
450 Some(Progress::Ringing),
451 CallState::Connecting
452 ))));
453 assert!(!should_ringback(Some(&outgoing(
454 Some(Progress::Ringing),
455 CallState::Connected { since }
456 ))));
457 let ended = CallState::Ended {
458 reason: EndReason::LocalHangup,
459 };
460 assert!(!should_ringback(Some(&outgoing(
461 Some(Progress::Ringing),
462 ended
463 ))));
464 let mut meeting = CallModel::meeting("Standup", false);
465 meeting.progress = Some(Progress::Calling);
466 assert!(!should_ringback(Some(&meeting)));
467 let mut incoming = CallModel::incoming("Bea", "8:orgid:b", "Bea");
468 incoming.progress = Some(Progress::Ringing);
469 assert!(!should_ringback(Some(&incoming)));
470 }
471
472 #[test]
473 fn calls_and_busy_keep_the_sound_unless_the_busy_setting_is_off() {
474 let busy_environments = [
475 Environment {
476 in_call: true,
477 ..Default::default()
478 },
479 Environment {
480 own_busy: true,
481 ..Default::default()
482 },
483 ];
484 let quiet_when_busy = Settings {
485 sounds: SoundSettings {
486 sound_when_busy: false,
487 ..Default::default()
488 },
489 ..Default::default()
490 };
491 for environment in busy_environments {
492 assert!(decide(&Settings::default(), &group(), environment).sound);
493 assert_eq!(
494 decide(&quiet_when_busy, &group(), environment),
495 Decision {
496 toast: true,
497 sound: false,
498 urgent_sound: false,
499 }
500 );
501 }
502 assert!(decide(&quiet_when_busy, &group(), Environment::default()).sound);
503 }
504
505 #[test]
506 fn incoming_calls_ring_the_chosen_tone_and_beep_during_a_call() {
507 let mut settings = Settings::default();
508 settings.sounds.ringtones.regular = Ringtone::Bop;
509 assert_eq!(ringtone_for(&settings, false, false), Some(Ringtone::Bop));
510 assert_eq!(ringtone_for(&settings, true, true), Some(Ringtone::Beep));
511 settings.sounds.sound_when_busy = false;
512 assert_eq!(ringtone_for(&settings, false, true), None);
513 assert_eq!(ringtone_for(&settings, false, false), Some(Ringtone::Bop));
514 settings.sounds.call_and_meeting_sound = false;
515 assert_eq!(ringtone_for(&settings, false, false), None);
516 assert!(!meeting_start_sound(&settings, false));
517 }
518
519 #[test]
520 fn meeting_start_sound_follows_the_call_and_busy_settings() {
521 let mut settings = Settings::default();
522 assert!(meeting_start_sound(&settings, false));
523 assert!(meeting_start_sound(&settings, true));
524 settings.sounds.sound_when_busy = false;
525 assert!(!meeting_start_sound(&settings, true));
526 }
527
528 #[test]
529 fn mute_in_calls_drops_the_toast_only_while_in_a_call() {
530 let settings = Settings {
531 mute_in_calls: true,
532 ..Default::default()
533 };
534 let in_call = Environment {
535 in_call: true,
536 ..Default::default()
537 };
538 assert_eq!(decide(&settings, &group(), in_call), SILENT);
539 assert!(decide(&settings, &group(), Environment::default()).toast);
540 }
541
542 #[test]
543 fn muted_chat_only_alerts_and_notifies_for_mentions() {
544 let mut muted = group();
545 muted.muted = true;
546 assert!(!alerts(&muted));
547 assert_eq!(
548 decide(&Settings::default(), &muted, Environment::default()),
549 SILENT
550 );
551 muted.mentions_me = true;
552 assert!(alerts(&muted));
553 assert!(decide(&Settings::default(), &muted, Environment::default()).toast);
554 }
555
556 #[test]
557 fn mentions_only_keeps_direct_and_mentions() {
558 let settings = Settings {
559 mentions_only: true,
560 ..Default::default()
561 };
562 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
563 assert!(
564 decide(
565 &settings,
566 &incoming(ChatKind::Direct),
567 Environment::default()
568 )
569 .toast
570 );
571 let mut mention = group();
572 mention.mentions_me = true;
573 assert!(decide(&settings, &mention, Environment::default()).toast);
574 }
575
576 fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {
577 let mut message = channel();
578 message.signals.notifications = ChannelNotifications {
579 level,
580 include_replies,
581 };
582 message
583 }
584
585 fn toast_of(incoming: &Incoming) -> bool {
586 decide(&Settings::default(), incoming, Environment::default()).toast
587 }
588
589 #[test]
590 fn banner_and_activity_posts_toast_and_feed() {
591 let post = channel_with(ChannelNotificationLevel::BannerAndFeed, false);
592 assert!(channel_alerts(&post));
593 assert!(toast_of(&post));
594 }
595
596 #[test]
597 fn activity_only_posts_feed_without_a_toast() {
598 let post = channel_with(ChannelNotificationLevel::Feed, false);
599 assert!(channel_alerts(&post));
600 assert_eq!(
601 decide(&Settings::default(), &post, Environment::default()),
602 SILENT
603 );
604 assert!(channel_alerts(&channel()));
605 }
606
607 #[test]
608 fn off_channel_stays_silent_except_for_mentions_and_my_threads() {
609 let mut post = channel_with(ChannelNotificationLevel::Off, true);
610 assert!(!channel_alerts(&post));
611 assert_eq!(
612 decide(&Settings::default(), &post, Environment::default()),
613 SILENT
614 );
615 post.signals.is_reply = true;
616 assert!(!channel_alerts(&post));
617 let triggers: [fn(&mut Incoming); 3] = [
618 |incoming| incoming.mentions_me = true,
619 |incoming| incoming.signals.mentions_channel = true,
620 |incoming| incoming.signals.in_my_thread = true,
621 ];
622 for trigger in triggers {
623 let mut mention = channel_with(ChannelNotificationLevel::Off, false);
624 trigger(&mut mention);
625 assert!(channel_alerts(&mention));
626 assert!(toast_of(&mention));
627 }
628 }
629
630 #[test]
631 fn replies_need_include_replies_or_my_thread() {
632 for level in [
633 ChannelNotificationLevel::Feed,
634 ChannelNotificationLevel::BannerAndFeed,
635 ] {
636 let mut reply = channel_with(level, false);
637 reply.signals.is_reply = true;
638 assert!(!channel_alerts(&reply));
639 reply.signals.in_my_thread = true;
640 assert!(channel_alerts(&reply));
641 let mut included = channel_with(level, true);
642 included.signals.is_reply = true;
643 assert!(channel_alerts(&included));
644 }
645 let mut banner_reply = channel_with(ChannelNotificationLevel::BannerAndFeed, true);
646 banner_reply.signals.is_reply = true;
647 assert!(toast_of(&banner_reply));
648 let mut feed_reply = channel_with(ChannelNotificationLevel::Feed, true);
649 feed_reply.signals.is_reply = true;
650 assert!(!toast_of(&feed_reply));
651 }
652
653 #[test]
654 fn hidden_channel_only_alerts_for_mentions_of_me() {
655 let triggers: [fn(&mut Incoming); 3] = [
656 |incoming| incoming.signals.mentions_channel = true,
657 |incoming| incoming.signals.in_my_thread = true,
658 |incoming| {
659 incoming.signals.notifications.level = ChannelNotificationLevel::BannerAndFeed
660 },
661 ];
662 for trigger in triggers {
663 let mut message = channel();
664 trigger(&mut message);
665 message.signals.hidden = true;
666 assert!(!channel_alerts(&message));
667 }
668 let mut mention = channel();
669 mention.signals.hidden = true;
670 mention.mentions_me = true;
671 assert!(channel_alerts(&mention));
672 }
673
674 #[test]
675 fn chats_ignore_channel_signals() {
676 assert!(channel_alerts(&group()));
677 assert!(channel_alerts(&incoming(ChatKind::Direct)));
678 }
679
680 #[test]
681 fn sound_setting_off_keeps_toast() {
682 let settings = Settings {
683 sounds: SoundSettings {
684 notification_sound: false,
685 ..Default::default()
686 },
687 ..Default::default()
688 };
689 let decision = decide(&settings, &group(), Environment::default());
690 assert_eq!(
691 decision,
692 Decision {
693 toast: true,
694 sound: false,
695 urgent_sound: false,
696 }
697 );
698 }
699
700 #[test]
701 fn throttle_allows_once_per_window_per_chat() {
702 let mut throttle = SoundThrottle::default();
703 let start = Instant::now();
704 assert!(throttle.allow("a", start));
705 assert!(!throttle.allow("a", start + Duration::from_secs(9)));
706 assert!(throttle.allow("b", start + Duration::from_secs(9)));
707 assert!(throttle.allow("a", start + Duration::from_secs(10)));
708 }
709
710 #[test]
711 fn flash_needs_toast_inactive_window_and_setting() {
712 let settings = Settings::default();
713 assert!(should_flash(&settings, true, false));
714 assert!(!should_flash(&settings, true, true));
715 assert!(!should_flash(&settings, false, false));
716 let off = Settings {
717 flash: false,
718 ..Default::default()
719 };
720 assert!(!should_flash(&off, true, false));
721 }
722
723 #[test]
724 fn corner_keys_round_trip() {
725 for corner in Corner::ALL {
726 assert_eq!(Corner::from_key(corner.key()), Some(corner));
727 }
728 assert_eq!(Corner::BottomRight.next(), Corner::TopLeft);
729 }
730}