BlueGit

ict rusty-teams

Files

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

incoming.rs

incoming.rs 15.5 KiB Download Raw
1use std::collections::HashMap;
2
3use chrono::{DateTime, Utc};
4use store::{ChannelNotifications, MessageRecord, Sidebar, Store};
5
6use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};
7use crate::app_state::chat_title;
8
9const RECENT_WINDOW: usize = 20;
10const FILE_FALLBACK: &str = "File";
11
12pub struct IncomingTracker {
13 started: DateTime<Utc>,
14 watermarks: HashMap<String, DateTime<Utc>>,
15}
16
17impl IncomingTracker {
18 pub fn new(started: DateTime<Utc>) -> Self {
19 IncomingTracker {
20 started,
21 watermarks: HashMap::new(),
22 }
23 }
24
25 pub fn collect(
26 &mut self,
27 store: &Store,
28 sidebar: &Sidebar,
29 my_user_id: Option<&str>,
30 conversation_id: &str,
31 ) -> Vec<Incoming> {
32 let Ok(records) = store.messages(conversation_id, None, RECENT_WINDOW) else {
33 return Vec::new();
34 };
35 self.fresh(records, store, sidebar, my_user_id)
36 }
37
38 fn fresh(
39 &mut self,
40 records: Vec<MessageRecord>,
41 store: &Store,
42 sidebar: &Sidebar,
43 my_user_id: Option<&str>,
44 ) -> Vec<Incoming> {
45 let mut incoming = Vec::new();
46 for record in records {
47 let watermark = self
48 .watermarks
49 .get(&record.conversation_id)
50 .copied()
51 .unwrap_or(self.started)
52 .max(self.started);
53 if record.created_at <= watermark {
54 continue;
55 }
56 self.watermarks
57 .insert(record.conversation_id.clone(), record.created_at);
58 if record.deleted || is_own(&record, my_user_id) {
59 continue;
60 }
61 if let Some(entry) = build_incoming(&record, store, sidebar, my_user_id) {
62 incoming.push(entry);
63 }
64 }
65 incoming
66 }
67}
68
69fn is_own(record: &MessageRecord, my_user_id: Option<&str>) -> bool {
70 matches!((record.sender_id.as_deref(), my_user_id), (Some(sender), Some(me)) if sender == me)
71}
72
73pub fn build_incoming(
74 record: &MessageRecord,
75 store: &Store,
76 sidebar: &Sidebar,
77 my_user_id: Option<&str>,
78) -> Option<Incoming> {
79 let (kind, chat_name) = chat_context(sidebar, &record.conversation_id)?;
80 let signals = match kind {
81 ChatKind::Channel { .. } => channel_signals(record, store, sidebar, my_user_id),
82 _ => ChannelSignals::default(),
83 };
84 Some(Incoming {
85 conversation_id: record.conversation_id.clone(),
86 message_id: record.message_id.clone(),
87 kind,
88 chat_title: chat_name,
89 sender_id: record.sender_id.clone(),
90 sender_name: record.sender_name.clone().unwrap_or_default(),
91 preview: preview_of(record),
92 mentions_me: mentions_me(record, my_user_id),
93 muted: is_muted_chat(sidebar, &record.conversation_id),
94 signals,
95 created_at: record.created_at,
96 })
97}
98
99fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {
100 sidebar
101 .chats
102 .iter()
103 .any(|chat| chat.id == conversation_id && chat.muted)
104}
105
106fn chat_context(sidebar: &Sidebar, conversation_id: &str) -> Option<(ChatKind, String)> {
107 if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
108 let kind = if chat.kind.eq_ignore_ascii_case("oneOnOne") {
109 ChatKind::Direct
110 } else {
111 ChatKind::Group {
112 member_count: chat.members.len().max(2),
113 }
114 };
115 return Some((kind, chat_title(chat)));
116 }
117 sidebar.teams.iter().find_map(|team| {
118 team.channels
119 .iter()
120 .find(|channel| channel.id == conversation_id)
121 .map(|channel| {
122 (
123 ChatKind::Channel {
124 team: team.team.name.clone(),
125 channel: channel.name.clone(),
126 },
127 channel.name.clone(),
128 )
129 })
130 })
131}
132
133fn channel_signals(
134 record: &MessageRecord,
135 store: &Store,
136 sidebar: &Sidebar,
137 my_user_id: Option<&str>,
138) -> ChannelSignals {
139 let in_my_thread = match (record.reply_to_id.as_deref(), my_user_id) {
140 (Some(root_id), Some(me)) => store
141 .thread_has_sender(&record.conversation_id, root_id, me)
142 .unwrap_or(false),
143 _ => false,
144 };
145 ChannelSignals {
146 mentions_channel: teams_core::mentions(record)
147 .iter()
148 .any(|mention| mention.group),
149 in_my_thread,
150 hidden: channel_hidden(sidebar, &record.conversation_id),
151 is_reply: record.reply_to_id.is_some(),
152 notifications: channel_notifications(sidebar, &record.conversation_id),
153 }
154}
155
156fn channel_notifications(sidebar: &Sidebar, conversation_id: &str) -> ChannelNotifications {
157 sidebar
158 .teams
159 .iter()
160 .find(|team| {
161 team.channels
162 .iter()
163 .any(|channel| channel.id == conversation_id)
164 })
165 .map(|team| team.channel_notifications(conversation_id))
166 .unwrap_or_default()
167}
168
169fn channel_hidden(sidebar: &Sidebar, conversation_id: &str) -> bool {
170 sidebar.teams.iter().any(|team| {
171 team.channels
172 .iter()
173 .any(|channel| channel.id == conversation_id)
174 && (team.hidden
175 || team
176 .hidden_channel_ids
177 .iter()
178 .any(|channel_id| channel_id == conversation_id))
179 })
180}
181
182fn mentions_me(record: &MessageRecord, my_user_id: Option<&str>) -> bool {
183 let Some(me) = my_user_id else {
184 return false;
185 };
186 teams_core::mentions(record)
187 .iter()
188 .any(|mention| mention.user_id.as_deref() == Some(me))
189}
190
191pub fn preview_of(record: &MessageRecord) -> Preview {
192 if let Some(text) = teams_core::preview_text(&record.body_html) {
193 return Preview::Text(text);
194 }
195 if !teams_core::images(record).is_empty() {
196 return Preview::Image;
197 }
198 let file_name = teams_core::attachments(record)
199 .into_iter()
200 .find_map(|attachment| attachment.name);
201 Preview::Text(file_name.unwrap_or_else(|| FILE_FALLBACK.to_owned()))
202}
203
204#[cfg(test)]
205mod tests {
206 use chrono::Duration;
207 use store::{
208 ChannelNotificationLevel, ChannelRecord, ChatRecord, MemberRecord, SidebarTeam, TeamRecord,
209 };
210
211 use super::*;
212
213 fn sidebar() -> Sidebar {
214 Sidebar {
215 chats: vec![
216 ChatRecord {
217 id: "direct".into(),
218 kind: "oneOnOne".into(),
219 title: "Mara".into(),
220 ..Default::default()
221 },
222 ChatRecord {
223 id: "group".into(),
224 kind: "group".into(),
225 title: "Team".into(),
226 members: vec![MemberRecord::default(); 5],
227 ..Default::default()
228 },
229 ],
230 teams: vec![
231 team("team-open", false, &["channel-open"], &[]),
232 team("team-hidden", true, &["channel-in-hidden-team"], &[]),
233 team(
234 "team-partial",
235 false,
236 &["channel-hidden", "channel-shown"],
237 &["channel-hidden"],
238 ),
239 ],
240 }
241 }
242
243 fn team(
244 team_id: &str,
245 hidden: bool,
246 channel_ids: &[&str],
247 hidden_channel_ids: &[&str],
248 ) -> SidebarTeam {
249 SidebarTeam {
250 team: TeamRecord {
251 id: team_id.into(),
252 name: "Team".into(),
253 },
254 channels: channel_ids
255 .iter()
256 .map(|id| ChannelRecord {
257 id: (*id).into(),
258 team_id: team_id.into(),
259 name: "General".into(),
260 membership_type: None,
261 last_message_at: None,
262 unread: false,
263 })
264 .collect(),
265 hidden,
266 hidden_channel_ids: hidden_channel_ids
267 .iter()
268 .map(|id| (*id).to_owned())
269 .collect(),
270 notifications: HashMap::new(),
271 }
272 }
273
274 fn collect_one(message: MessageRecord, store: &Store) -> Incoming {
275 build_incoming(&message, store, &sidebar(), Some("me")).unwrap()
276 }
277
278 fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {
279 MessageRecord {
280 subject: None,
281 conversation_id: conversation.into(),
282 message_id: format!("{conversation}-{}", at.timestamp_millis()),
283 reply_to_id: None,
284 sender_id: Some(sender.into()),
285 sender_name: Some("Sender".into()),
286 sender_application_id: None,
287 links_json: "[]".to_owned(),
288 created_at: at,
289 edited_at: None,
290 deleted: false,
291 body_html: html.into(),
292 attachments_json: "[]".into(),
293 reactions_json: "[]".into(),
294 mentions_json: "[]".into(),
295 }
296 }
297
298 #[test]
299 fn incoming_in_a_muted_chat_is_marked_muted() {
300 let mut quiet = sidebar();
301 quiet.chats[1].muted = true;
302 let message = record("group", "u1", Utc::now(), "hi");
303 let store = Store::open_in_memory().unwrap();
304 let build =
305 |sidebar: &Sidebar| build_incoming(&message, &store, sidebar, Some("me")).unwrap();
306 assert!(build(&quiet).muted);
307 assert!(!build(&sidebar()).muted);
308 }
309
310 #[test]
311 fn history_before_start_is_ignored() {
312 let start = Utc::now();
313 let mut tracker = IncomingTracker::new(start);
314 let old = record("direct", "u1", start - Duration::minutes(5), "alt");
315 let new = record("direct", "u1", start + Duration::seconds(5), "neu");
316 let found = tracker.fresh(
317 vec![old, new],
318 &Store::open_in_memory().unwrap(),
319 &sidebar(),
320 Some("me"),
321 );
322 assert_eq!(found.len(), 1);
323 assert_eq!(found[0].preview, Preview::Text("neu".into()));
324 }
325
326 #[test]
327 fn same_message_is_not_reported_twice() {
328 let start = Utc::now();
329 let mut tracker = IncomingTracker::new(start);
330 let message = record("direct", "u1", start + Duration::seconds(5), "neu");
331 let store = Store::open_in_memory().unwrap();
332 let sidebar = sidebar();
333 let first = tracker.fresh(vec![message.clone()], &store, &sidebar, None);
334 assert_eq!(first.len(), 1);
335 assert!(
336 tracker
337 .fresh(vec![message], &store, &sidebar, None)
338 .is_empty()
339 );
340 }
341
342 #[test]
343 fn own_messages_from_other_devices_are_skipped() {
344 let start = Utc::now();
345 let mut tracker = IncomingTracker::new(start);
346 let own = record("direct", "me", start + Duration::seconds(5), "ich");
347 let store = Store::open_in_memory().unwrap();
348 let found = tracker.fresh(vec![own], &store, &sidebar(), Some("me"));
349 assert!(found.is_empty());
350 }
351
352 #[test]
353 fn detects_mention_of_me_and_group_size() {
354 let start = Utc::now();
355 let mut message = record(
356 "group",
357 "u1",
358 start + Duration::seconds(5),
359 "<at>Me</at> hi",
360 );
361 message.mentions_json = r#"[{"user_id":"me","name":"Me"}]"#.into();
362 let found = collect_one(message.clone(), &Store::open_in_memory().unwrap());
363 assert!(found.mentions_me);
364 assert_eq!(found.kind, ChatKind::Group { member_count: 5 });
365 let other = build_incoming(
366 &message,
367 &Store::open_in_memory().unwrap(),
368 &sidebar(),
369 Some("other"),
370 );
371 assert!(!other.unwrap().mentions_me);
372 }
373
374 #[test]
375 fn unknown_conversation_yields_nothing() {
376 let message = record("nowhere", "u1", Utc::now(), "x");
377 assert!(
378 build_incoming(
379 &message,
380 &Store::open_in_memory().unwrap(),
381 &sidebar(),
382 None
383 )
384 .is_none()
385 );
386 }
387
388 #[test]
389 fn empty_body_without_image_falls_back_to_file_label() {
390 let message = record("direct", "u1", Utc::now(), "");
391 let found = build_incoming(
392 &message,
393 &Store::open_in_memory().unwrap(),
394 &sidebar(),
395 None,
396 )
397 .unwrap();
398 assert_eq!(found.preview, Preview::Text(FILE_FALLBACK.into()));
399 }
400
401 #[test]
402 fn group_mention_sets_channel_signal() {
403 let store = Store::open_in_memory().unwrap();
404 let mut message = record("channel-open", "u1", Utc::now(), "<at>channel</at>");
405 message.mentions_json =
406 r#"[{"user_id":null,"name":"channel","target_id":"channel-open","group":true}]"#.into();
407 assert!(
408 collect_one(message.clone(), &store)
409 .signals
410 .mentions_channel
411 );
412 message.mentions_json = r#"[{"user_id":null,"name":"bot","target_id":"bot-1"}]"#.into();
413 assert!(!collect_one(message, &store).signals.mentions_channel);
414 }
415
416 #[test]
417 fn reply_in_my_thread_sets_signal() {
418 let store = Store::open_in_memory().unwrap();
419 let start = Utc::now();
420 let mut root = record("channel-open", "me", start, "root");
421 root.message_id = "root".into();
422 store.upsert_messages(&[root]).unwrap();
423 let mut reply = record("channel-open", "u1", start + Duration::seconds(1), "reply");
424 reply.reply_to_id = Some("root".into());
425 assert!(collect_one(reply.clone(), &store).signals.in_my_thread);
426 reply.reply_to_id = Some("unknown-root".into());
427 assert!(!collect_one(reply, &store).signals.in_my_thread);
428 let top_level = record("channel-open", "u1", start, "post");
429 assert!(!collect_one(top_level, &store).signals.in_my_thread);
430 }
431
432 #[test]
433 fn hidden_channels_are_flagged() {
434 let store = Store::open_in_memory().unwrap();
435 let signals =
436 |channel: &str| collect_one(record(channel, "u1", Utc::now(), "x"), &store).signals;
437 assert!(!signals("channel-open").hidden);
438 assert!(signals("channel-in-hidden-team").hidden);
439 assert!(signals("channel-hidden").hidden);
440 assert!(!signals("channel-shown").hidden);
441 }
442
443 #[test]
444 fn channel_notifications_and_reply_flag_come_from_the_sidebar() {
445 let store = Store::open_in_memory().unwrap();
446 let banner = ChannelNotifications {
447 level: ChannelNotificationLevel::BannerAndFeed,
448 include_replies: true,
449 };
450 let mut configured = sidebar();
451 configured.teams[0]
452 .notifications
453 .insert("channel-open".into(), banner);
454 let mut reply = record("channel-open", "u1", Utc::now(), "x");
455 let build = |message: &MessageRecord| {
456 build_incoming(message, &store, &configured, Some("me"))
457 .unwrap()
458 .signals
459 };
460 assert_eq!(build(&reply).notifications, banner);
461 assert!(!build(&reply).is_reply);
462 reply.reply_to_id = Some("root".into());
463 assert!(build(&reply).is_reply);
464 let other = record("channel-shown", "u1", Utc::now(), "x");
465 assert_eq!(build(&other).notifications, ChannelNotifications::default());
466 }
467
468 #[test]
469 fn chats_carry_no_channel_signals() {
470 let store = Store::open_in_memory().unwrap();
471 let found = collect_one(record("group", "u1", Utc::now(), "x"), &store);
472 assert_eq!(found.signals, ChannelSignals::default());
473 }
474}