BlueGit

ict rusty-teams

Files

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

rules.rs

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