BlueGit

ict rusty-teams

Files

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

rules.rs

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