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