BlueGit

ict rusty-teams

Files

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

rules.rs

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