BlueGit

ict rusty-teams

Files

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

rules.rs

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