BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / activity / feed.rs

feed.rs

feed.rs 29.8 KiB Download Raw
1use std::collections::{BTreeSet, HashMap};
2
3use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
4use serde::{Deserialize, Serialize};
5use store::ActivityRecord;
6
7use crate::notify::Incoming;
8use crate::reaction_model::{UNKNOWN_REACTOR, tooltip_text};
9
10pub const RETENTION_DAYS: i64 = 14;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Kind {
14 Messages,
15 Mention,
16 Reaction,
17 MissedCall,
18}
19
20impl Kind {
21 fn key(self) -> &'static str {
22 match self {
23 Kind::Messages => "messages",
24 Kind::Mention => "mention",
25 Kind::Reaction => "reaction",
26 Kind::MissedCall => "missed_call",
27 }
28 }
29
30 fn from_key(key: &str) -> Option<Kind> {
31 [
32 Kind::Messages,
33 Kind::Mention,
34 Kind::Reaction,
35 Kind::MissedCall,
36 ]
37 .into_iter()
38 .find(|kind| kind.key() == key)
39 }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43pub enum Filter {
44 #[default]
45 All,
46 Mentions,
47 Unread,
48}
49
50impl Filter {
51 pub const ALL: [Filter; 3] = [Filter::All, Filter::Mentions, Filter::Unread];
52
53 pub fn key(self) -> &'static str {
54 match self {
55 Filter::All => "all",
56 Filter::Mentions => "mentions",
57 Filter::Unread => "unread",
58 }
59 }
60
61 pub fn from_key(key: &str) -> Option<Filter> {
62 Filter::ALL.into_iter().find(|filter| filter.key() == key)
63 }
64
65 pub fn label(self) -> &'static str {
66 match self {
67 Filter::All => "All",
68 Filter::Mentions => "@Mentions",
69 Filter::Unread => "Unread",
70 }
71 }
72
73 pub fn empty_label(self) -> &'static str {
74 match self {
75 Filter::All => "No activity yet",
76 Filter::Mentions => "No mentions",
77 Filter::Unread => "Nothing unread",
78 }
79 }
80
81 fn admits(self, entry: &Entry) -> bool {
82 match self {
83 Filter::All => true,
84 Filter::Mentions => entry.kind == Kind::Mention,
85 Filter::Unread => !entry.read,
86 }
87 }
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum Bucket {
92 Today,
93 Yesterday,
94 Earlier,
95}
96
97impl Bucket {
98 pub fn of(time: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> Bucket {
99 let days_ago = (today - time.with_timezone(&offset).date_naive()).num_days();
100 match days_ago {
101 ..=0 => Bucket::Today,
102 1 => Bucket::Yesterday,
103 _ => Bucket::Earlier,
104 }
105 }
106
107 pub fn label(self) -> &'static str {
108 match self {
109 Bucket::Today => "Today",
110 Bucket::Yesterday => "Yesterday",
111 Bucket::Earlier => "Earlier",
112 }
113 }
114}
115
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117pub struct Actor {
118 pub user_id: Option<String>,
119 pub name: String,
120}
121
122impl Actor {
123 pub fn is_unresolved(&self) -> bool {
124 self.user_id.is_some() && (self.name.is_empty() || self.name == UNKNOWN_REACTOR)
125 }
126
127 pub fn display_name<'a>(&'a self, resolved: &'a HashMap<String, String>) -> &'a str {
128 if self.is_unresolved()
129 && let Some(name) = self
130 .user_id
131 .as_ref()
132 .and_then(|user_id| resolved.get(user_id))
133 {
134 return name;
135 }
136 &self.name
137 }
138}
139
140#[derive(Debug, Clone, PartialEq)]
141pub struct Entry {
142 pub id: i64,
143 pub conversation_id: String,
144 pub kind: Kind,
145 pub message_id: String,
146 pub actors: Vec<Actor>,
147 pub preview: String,
148 pub glyphs: Vec<String>,
149 pub count: u32,
150 pub updated_at: DateTime<Utc>,
151 pub read: bool,
152}
153
154impl Entry {
155 pub fn names(&self, resolved: &HashMap<String, String>) -> String {
156 let names: Vec<&str> = self
157 .actors
158 .iter()
159 .map(|actor| actor.display_name(resolved))
160 .collect();
161 tooltip_text(&names)
162 }
163
164 pub fn unresolved_user_ids(&self) -> impl Iterator<Item = &String> {
165 self.actors
166 .iter()
167 .filter(|actor| actor.is_unresolved())
168 .filter_map(|actor| actor.user_id.as_ref())
169 }
170
171 pub fn latest_actor(&self) -> Option<&Actor> {
172 self.actors.last()
173 }
174
175 pub fn to_record(&self) -> ActivityRecord {
176 ActivityRecord {
177 id: self.id,
178 conversation_id: self.conversation_id.clone(),
179 kind: self.kind.key().to_owned(),
180 message_id: self.message_id.clone(),
181 actors_json: serde_json::to_string(&self.actors).unwrap_or_else(|_| "[]".to_owned()),
182 preview: self.preview.clone(),
183 glyphs: serde_json::to_string(&self.glyphs).unwrap_or_else(|_| "[]".to_owned()),
184 count: self.count,
185 updated_at: self.updated_at,
186 read: self.read,
187 }
188 }
189
190 pub fn from_record(record: ActivityRecord) -> Option<Entry> {
191 Some(Entry {
192 id: record.id,
193 kind: Kind::from_key(&record.kind)?,
194 conversation_id: record.conversation_id,
195 message_id: record.message_id,
196 actors: serde_json::from_str(&record.actors_json).unwrap_or_default(),
197 preview: record.preview,
198 glyphs: serde_json::from_str(&record.glyphs).unwrap_or_default(),
199 count: record.count,
200 updated_at: record.updated_at,
201 read: record.read,
202 })
203 }
204}
205
206#[derive(Debug, Clone, PartialEq, Eq)]
207pub struct Sighting {
208 pub user_id: Option<String>,
209 pub name: String,
210 pub glyph: String,
211 pub created_at: Option<DateTime<Utc>>,
212}
213
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct ReactedMessage {
216 pub message_id: String,
217 pub preview: String,
218 pub sightings: Vec<Sighting>,
219}
220
221pub struct Section<'a> {
222 pub bucket: Bucket,
223 pub entries: Vec<&'a Entry>,
224}
225
226#[derive(Default)]
227pub struct Feed {
228 entries: Vec<Entry>,
229 next_id: i64,
230 dirty: BTreeSet<i64>,
231}
232
233pub fn start_time(saved: Option<DateTime<Utc>>, now: DateTime<Utc>) -> DateTime<Utc> {
234 saved
235 .unwrap_or(now)
236 .clamp(now - Duration::days(RETENTION_DAYS), now)
237}
238
239impl Feed {
240 pub fn load(records: Vec<ActivityRecord>) -> Feed {
241 let entries: Vec<Entry> = records.into_iter().filter_map(Entry::from_record).collect();
242 let next_id = entries.iter().map(|entry| entry.id).max().unwrap_or(0) + 1;
243 Feed {
244 entries,
245 next_id,
246 dirty: BTreeSet::new(),
247 }
248 }
249
250 pub fn add(&mut self, mut entry: Entry) -> i64 {
251 entry.id = self.next_id;
252 self.next_id += 1;
253 self.dirty.insert(entry.id);
254 let id = entry.id;
255 self.entries.push(entry);
256 id
257 }
258
259 pub fn get(&self, id: i64) -> Option<&Entry> {
260 self.entries.iter().find(|entry| entry.id == id)
261 }
262
263 pub fn unread_count(&self) -> usize {
264 self.unread_entries().count()
265 }
266
267 pub fn unread_entries(&self) -> impl Iterator<Item = &Entry> {
268 self.entries.iter().filter(|entry| !entry.read)
269 }
270
271 pub fn take_dirty(&mut self) -> Vec<Entry> {
272 let dirty = std::mem::take(&mut self.dirty);
273 self.entries
274 .iter()
275 .filter(|entry| dirty.contains(&entry.id))
276 .cloned()
277 .collect()
278 }
279
280 pub fn sections(
281 &self,
282 filter: Filter,
283 today: NaiveDate,
284 offset: FixedOffset,
285 ) -> Vec<Section<'_>> {
286 let mut admitted: Vec<&Entry> = self
287 .entries
288 .iter()
289 .filter(|entry| filter.admits(entry))
290 .collect();
291 admitted.sort_by_key(|entry| std::cmp::Reverse((entry.updated_at, entry.id)));
292 let mut sections: Vec<Section<'_>> = Vec::new();
293 for entry in admitted {
294 let bucket = Bucket::of(entry.updated_at, today, offset);
295 match sections.last_mut() {
296 Some(section) if section.bucket == bucket => section.entries.push(entry),
297 _ => sections.push(Section {
298 bucket,
299 entries: vec![entry],
300 }),
301 }
302 }
303 sections
304 }
305
306 pub fn record_message(&mut self, incoming: &Incoming, preview: String) {
307 let actor = Actor {
308 user_id: incoming.sender_id.clone(),
309 name: incoming.sender_name.clone(),
310 };
311 if incoming.mentions_me {
312 self.add(Entry {
313 id: 0,
314 conversation_id: incoming.conversation_id.clone(),
315 kind: Kind::Mention,
316 message_id: incoming.message_id.clone(),
317 actors: vec![actor],
318 preview,
319 glyphs: Vec::new(),
320 count: 1,
321 updated_at: incoming.created_at,
322 read: false,
323 });
324 return;
325 }
326 let open_row = self.entries.iter().position(|entry| {
327 entry.kind == Kind::Messages
328 && !entry.read
329 && entry.conversation_id == incoming.conversation_id
330 });
331 let Some(index) = open_row else {
332 self.add(Entry {
333 id: 0,
334 conversation_id: incoming.conversation_id.clone(),
335 kind: Kind::Messages,
336 message_id: incoming.message_id.clone(),
337 actors: vec![actor],
338 preview,
339 glyphs: Vec::new(),
340 count: 1,
341 updated_at: incoming.created_at,
342 read: false,
343 });
344 return;
345 };
346 let entry = &mut self.entries[index];
347 entry.count += 1;
348 entry.preview = preview;
349 entry.updated_at = incoming.created_at;
350 move_to_end(&mut entry.actors, actor);
351 self.dirty.insert(entry.id);
352 }
353
354 pub fn record_missed_call(&mut self, conversation_id: &str, actor: Actor, at: DateTime<Utc>) {
355 let open_row = self.entries.iter().position(|entry| {
356 entry.kind == Kind::MissedCall
357 && !entry.read
358 && entry
359 .actors
360 .first()
361 .is_some_and(|known| known.user_id == actor.user_id && known.name == actor.name)
362 });
363 match open_row {
364 Some(index) => {
365 let entry = &mut self.entries[index];
366 entry.count += 1;
367 entry.updated_at = at;
368 self.dirty.insert(entry.id);
369 }
370 None => {
371 self.add(Entry {
372 id: 0,
373 conversation_id: conversation_id.to_owned(),
374 kind: Kind::MissedCall,
375 message_id: String::new(),
376 actors: vec![actor],
377 preview: String::new(),
378 glyphs: Vec::new(),
379 count: 1,
380 updated_at: at,
381 read: false,
382 });
383 }
384 }
385 }
386
387 pub fn record_chat_preview(
388 &mut self,
389 conversation_id: &str,
390 actor: Actor,
391 preview: String,
392 at: DateTime<Utc>,
393 ) {
394 let known = self.entries.iter().any(|entry| {
395 entry.conversation_id == conversation_id
396 && entry.kind != Kind::Reaction
397 && entry.updated_at >= at
398 });
399 if known {
400 return;
401 }
402 let open_row = self.entries.iter().position(|entry| {
403 entry.kind == Kind::Messages && !entry.read && entry.conversation_id == conversation_id
404 });
405 match open_row {
406 Some(index) => {
407 let entry = &mut self.entries[index];
408 entry.count += 1;
409 entry.preview = preview;
410 entry.updated_at = at;
411 move_to_end(&mut entry.actors, actor);
412 self.dirty.insert(entry.id);
413 }
414 None => {
415 self.add(Entry {
416 id: 0,
417 conversation_id: conversation_id.to_owned(),
418 kind: Kind::Messages,
419 message_id: String::new(),
420 actors: vec![actor],
421 preview,
422 glyphs: Vec::new(),
423 count: 1,
424 updated_at: at,
425 read: false,
426 });
427 }
428 }
429 }
430
431 pub fn record_reactions(
432 &mut self,
433 conversation_id: &str,
434 message: &ReactedMessage,
435 my_user_id: &str,
436 cutoff: DateTime<Utc>,
437 now: DateTime<Utc>,
438 ) {
439 for sighting in &message.sightings {
440 let Some(user_id) = sighting.user_id.as_deref().filter(|id| *id != my_user_id) else {
441 continue;
442 };
443 let existing = self.entries.iter().position(|entry| {
444 entry.kind == Kind::Reaction
445 && entry.conversation_id == conversation_id
446 && entry.message_id == message.message_id
447 });
448 let known = existing.is_some_and(|index| {
449 self.entries[index]
450 .actors
451 .iter()
452 .any(|actor| actor.user_id.as_deref() == Some(user_id))
453 });
454 if known {
455 if let Some(index) = existing {
456 self.add_glyph(index, &sighting.glyph);
457 }
458 continue;
459 }
460 let fresh = match sighting.created_at {
461 Some(created_at) => created_at > cutoff,
462 None => existing.is_some(),
463 };
464 if !fresh {
465 continue;
466 }
467 let actor = Actor {
468 user_id: Some(user_id.to_owned()),
469 name: sighting.name.clone(),
470 };
471 let at = sighting.created_at.unwrap_or(now);
472 match existing {
473 Some(index) => {
474 let entry = &mut self.entries[index];
475 entry.actors.push(actor);
476 entry.count = entry.actors.len() as u32;
477 entry.read = false;
478 entry.updated_at = entry.updated_at.max(at);
479 self.dirty.insert(entry.id);
480 self.add_glyph(index, &sighting.glyph);
481 }
482 None => {
483 self.add(Entry {
484 id: 0,
485 conversation_id: conversation_id.to_owned(),
486 kind: Kind::Reaction,
487 message_id: message.message_id.clone(),
488 actors: vec![actor],
489 preview: message.preview.clone(),
490 glyphs: vec![sighting.glyph.clone()],
491 count: 1,
492 updated_at: at,
493 read: false,
494 });
495 }
496 }
497 }
498 }
499
500 fn add_glyph(&mut self, index: usize, glyph: &str) {
501 let entry = &mut self.entries[index];
502 if !glyph.is_empty() && !entry.glyphs.iter().any(|known| known == glyph) {
503 entry.glyphs.push(glyph.to_owned());
504 self.dirty.insert(entry.id);
505 }
506 }
507
508 pub fn mark_read(&mut self, id: i64) -> bool {
509 self.mark_where(|entry| entry.id == id)
510 }
511
512 pub fn mark_all_read(&mut self) -> bool {
513 self.mark_where(|_| true)
514 }
515
516 pub fn mark_conversation_read(&mut self, conversation_id: &str) -> bool {
517 self.mark_where(|entry| entry.conversation_id == conversation_id)
518 }
519
520 pub fn sync_read(&mut self, read_at: impl Fn(&str) -> Option<DateTime<Utc>>) -> bool {
521 self.mark_where(|entry| {
522 read_at(&entry.conversation_id).is_some_and(|read_at| entry.updated_at <= read_at)
523 })
524 }
525
526 fn mark_where(&mut self, matches: impl Fn(&Entry) -> bool) -> bool {
527 let mut changed = false;
528 for entry in self.entries.iter_mut().filter(|entry| !entry.read) {
529 if matches(entry) {
530 entry.read = true;
531 self.dirty.insert(entry.id);
532 changed = true;
533 }
534 }
535 changed
536 }
537}
538
539fn move_to_end(actors: &mut Vec<Actor>, actor: Actor) {
540 actors.retain(|known| match (&known.user_id, &actor.user_id) {
541 (Some(known_id), Some(id)) => known_id != id,
542 _ => known.name != actor.name,
543 });
544 actors.push(actor);
545}
546
547#[cfg(test)]
548mod tests {
549 use chrono::TimeZone;
550
551 use super::*;
552 use crate::notify::{ChatKind, Preview};
553
554 #[test]
555 fn filters_round_trip_through_their_key() {
556 for filter in Filter::ALL {
557 assert_eq!(Filter::from_key(filter.key()), Some(filter));
558 }
559 assert_eq!(Filter::from_key("other"), None);
560 }
561
562 fn at(hour: u32, minute: u32) -> DateTime<Utc> {
563 Utc.with_ymd_and_hms(2026, 10, 8, hour, minute, 0).unwrap()
564 }
565
566 fn incoming(conversation_id: &str, message_id: &str, sender: &str, minute: u32) -> Incoming {
567 Incoming {
568 conversation_id: conversation_id.into(),
569 message_id: message_id.into(),
570 kind: ChatKind::Direct,
571 chat_title: "Chat".into(),
572 sender_id: Some(format!("id-{sender}")),
573 sender_name: sender.into(),
574 preview: Preview::Text(format!("text {message_id}")),
575 mentions_me: false,
576 muted: false,
577 signals: Default::default(),
578 created_at: at(9, minute),
579 importance: Default::default(),
580 }
581 }
582
583 fn record(feed: &mut Feed, incoming: &Incoming) {
584 feed.record_message(incoming, format!("text {}", incoming.message_id));
585 }
586
587 fn sighting(user: &str, glyph: &str, created_at: Option<DateTime<Utc>>) -> Sighting {
588 Sighting {
589 user_id: Some(format!("id-{user}")),
590 name: user.into(),
591 glyph: glyph.into(),
592 created_at,
593 }
594 }
595
596 fn react(feed: &mut Feed, sightings: &[Sighting]) {
597 let message = ReactedMessage {
598 message_id: "mine".into(),
599 preview: "my text".into(),
600 sightings: sightings.to_vec(),
601 };
602 feed.record_reactions("chat", &message, "id-me", at(8, 0), at(10, 0));
603 }
604
605 fn all(feed: &Feed) -> Vec<&Entry> {
606 feed.sections(Filter::All, at(9, 0).date_naive(), offset())
607 .into_iter()
608 .flat_map(|section| section.entries)
609 .collect()
610 }
611
612 fn offset() -> FixedOffset {
613 FixedOffset::east_opt(0).unwrap()
614 }
615
616 #[test]
617 fn three_messages_share_one_row_and_keep_the_first_message_id() {
618 let mut feed = Feed::default();
619 for (index, message_id) in ["m1", "m2", "m3"].into_iter().enumerate() {
620 record(
621 &mut feed,
622 &incoming("chat", message_id, "Anna", index as u32),
623 );
624 }
625 let entries = all(&feed);
626 assert_eq!(entries.len(), 1);
627 assert_eq!(entries[0].count, 3);
628 assert_eq!(entries[0].message_id, "m1");
629 assert_eq!(entries[0].preview, "text m3");
630 assert_eq!(entries[0].updated_at, at(9, 2));
631 assert_eq!(feed.unread_count(), 1);
632 }
633
634 #[test]
635 fn latest_sender_moves_to_the_end() {
636 let mut feed = Feed::default();
637 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
638 record(&mut feed, &incoming("chat", "m2", "Ben", 2));
639 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
640 let entries = all(&feed);
641 let entry = entries[0];
642 assert_eq!(entry.names(&HashMap::new()), "Ben and Anna");
643 assert_eq!(entry.latest_actor().unwrap().name, "Anna");
644 }
645
646 #[test]
647 fn chat_preview_adds_a_row_only_when_newer_than_the_feed() {
648 let mut feed = Feed::default();
649 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
650 let anna = Actor {
651 user_id: Some("id-Anna".into()),
652 name: "Anna".into(),
653 };
654 feed.record_chat_preview("chat", anna.clone(), "text m1".into(), at(9, 1));
655 assert_eq!(all(&feed)[0].count, 1);
656 feed.record_chat_preview("chat", anna.clone(), "later".into(), at(9, 5));
657 assert_eq!(all(&feed)[0].count, 2);
658 assert_eq!(all(&feed)[0].preview, "later");
659 feed.record_chat_preview("other", anna, "offline".into(), at(9, 6));
660 let entries = all(&feed);
661 assert_eq!(entries.len(), 2);
662 assert_eq!(entries[0].message_id, "");
663 }
664
665 #[test]
666 fn message_after_read_opens_a_new_row() {
667 let mut feed = Feed::default();
668 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
669 feed.mark_conversation_read("chat");
670 record(&mut feed, &incoming("chat", "m2", "Anna", 2));
671 let entries = all(&feed);
672 assert_eq!(entries.len(), 2);
673 assert_eq!(entries[0].message_id, "m2");
674 assert!(!entries[0].read);
675 assert!(entries[1].read);
676 assert_eq!(entries[1].count, 1);
677 }
678
679 #[test]
680 fn mention_gets_its_own_row_and_is_not_counted_in_messages() {
681 let mut feed = Feed::default();
682 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
683 let mut mention = incoming("chat", "m2", "Ben", 2);
684 mention.mentions_me = true;
685 record(&mut feed, &mention);
686 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
687 let entries = all(&feed);
688 assert_eq!(entries.len(), 2);
689 let mention_row = entries
690 .iter()
691 .find(|entry| entry.kind == Kind::Mention)
692 .unwrap();
693 assert_eq!(mention_row.message_id, "m2");
694 let messages_row = entries
695 .iter()
696 .find(|entry| entry.kind == Kind::Messages)
697 .unwrap();
698 assert_eq!(messages_row.count, 2);
699 assert_eq!(messages_row.message_id, "m1");
700 }
701
702 #[test]
703 fn reactions_bundle_per_message_and_become_unread_again() {
704 let mut feed = Feed::default();
705 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
706 feed.mark_all_read();
707 assert_eq!(feed.unread_count(), 0);
708 react(
709 &mut feed,
710 &[
711 sighting("Anna", "A", Some(at(9, 1))),
712 sighting("Ben", "B", Some(at(9, 5))),
713 ],
714 );
715 let entries = all(&feed);
716 assert_eq!(entries.len(), 1);
717 assert_eq!(entries[0].names(&HashMap::new()), "Anna and Ben");
718 assert_eq!(entries[0].glyphs, vec!["A", "B"]);
719 assert_eq!(entries[0].count, 2);
720 assert_eq!(entries[0].updated_at, at(9, 5));
721 assert!(!entries[0].read);
722 assert_eq!(entries[0].preview, "my text");
723 }
724
725 #[test]
726 fn known_reactor_adding_a_glyph_does_not_reopen_the_row() {
727 let mut feed = Feed::default();
728 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
729 feed.mark_all_read();
730 react(&mut feed, &[sighting("Anna", "C", Some(at(9, 2)))]);
731 let entries = all(&feed);
732 assert_eq!(entries[0].glyphs, vec!["A", "C"]);
733 assert!(entries[0].read);
734 }
735
736 #[test]
737 fn own_and_anonymous_reactions_are_ignored() {
738 let mut feed = Feed::default();
739 let anonymous = Sighting {
740 user_id: None,
741 ..sighting("Anna", "A", Some(at(9, 1)))
742 };
743 react(&mut feed, &[sighting("me", "A", Some(at(9, 1))), anonymous]);
744 assert!(all(&feed).is_empty());
745 }
746
747 #[test]
748 fn old_reactions_on_first_sight_are_ignored() {
749 let mut feed = Feed::default();
750 react(
751 &mut feed,
752 &[
753 sighting("Anna", "A", Some(at(7, 0))),
754 sighting("Ben", "B", None),
755 ],
756 );
757 assert!(all(&feed).is_empty());
758 react(&mut feed, &[sighting("Cleo", "C", Some(at(9, 0)))]);
759 react(&mut feed, &[sighting("Dan", "D", None)]);
760 assert_eq!(all(&feed)[0].names(&HashMap::new()), "Cleo and Dan");
761 }
762
763 #[test]
764 fn reading_a_conversation_leaves_others_unread() {
765 let mut feed = Feed::default();
766 record(&mut feed, &incoming("a", "m1", "Anna", 1));
767 record(&mut feed, &incoming("b", "m2", "Ben", 2));
768 assert!(feed.mark_conversation_read("a"));
769 assert!(!feed.mark_conversation_read("a"));
770 assert_eq!(feed.unread_count(), 1);
771 let unread = all(&feed).into_iter().find(|entry| !entry.read).unwrap();
772 assert_eq!(unread.conversation_id, "b");
773 }
774
775 #[test]
776 fn read_sync_only_covers_rows_up_to_the_read_time() {
777 let mut feed = Feed::default();
778 record(&mut feed, &incoming("a", "m1", "Anna", 1));
779 feed.mark_conversation_read("a");
780 record(&mut feed, &incoming("a", "m2", "Anna", 30));
781 record(&mut feed, &incoming("b", "m3", "Ben", 1));
782 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 10)));
783 assert!(!changed);
784 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 45)));
785 assert!(changed);
786 assert_eq!(feed.unread_count(), 1);
787 }
788
789 #[test]
790 fn mark_all_read_clears_the_count_and_reports_change_once() {
791 let mut feed = Feed::default();
792 record(&mut feed, &incoming("a", "m1", "Anna", 1));
793 record(&mut feed, &incoming("b", "m2", "Ben", 2));
794 assert!(feed.mark_all_read());
795 assert_eq!(feed.unread_count(), 0);
796 assert!(!feed.mark_all_read());
797 }
798
799 #[test]
800 fn filters_pick_mentions_and_unread() {
801 let mut feed = Feed::default();
802 record(&mut feed, &incoming("a", "m1", "Anna", 1));
803 let mut mention = incoming("b", "m2", "Ben", 2);
804 mention.mentions_me = true;
805 record(&mut feed, &mention);
806 feed.mark_conversation_read("a");
807 let today = at(9, 0).date_naive();
808 let count = |filter| {
809 feed.sections(filter, today, offset())
810 .iter()
811 .map(|section| section.entries.len())
812 .sum::<usize>()
813 };
814 assert_eq!(count(Filter::All), 2);
815 assert_eq!(count(Filter::Mentions), 1);
816 assert_eq!(count(Filter::Unread), 1);
817 }
818
819 #[test]
820 fn buckets_follow_the_local_day() {
821 let today = at(12, 0).date_naive();
822 let utc = offset();
823 assert_eq!(Bucket::of(at(0, 5), today, utc), Bucket::Today);
824 assert_eq!(
825 Bucket::of(at(0, 5) - Duration::minutes(10), today, utc),
826 Bucket::Yesterday
827 );
828 assert_eq!(
829 Bucket::of(at(0, 5) - Duration::days(3), today, utc),
830 Bucket::Earlier
831 );
832 let east = FixedOffset::east_opt(2 * 3600).unwrap();
833 assert_eq!(
834 Bucket::of(at(23, 30) - Duration::days(1), today, east),
835 Bucket::Today
836 );
837 }
838
839 #[test]
840 fn sections_are_newest_first_and_grouped() {
841 let mut feed = Feed::default();
842 let mut old = incoming("a", "m1", "Anna", 1);
843 old.created_at = at(9, 0) - Duration::days(1);
844 record(&mut feed, &old);
845 record(&mut feed, &incoming("b", "m2", "Ben", 2));
846 record(&mut feed, &incoming("c", "m3", "Cleo", 3));
847 let today = at(9, 0).date_naive();
848 let sections = feed.sections(Filter::All, today, offset());
849 let labels: Vec<&str> = sections
850 .iter()
851 .map(|section| section.bucket.label())
852 .collect();
853 assert_eq!(labels, ["Today", "Yesterday"]);
854 assert_eq!(sections[0].entries[0].conversation_id, "c");
855 }
856
857 #[test]
858 fn dirty_rows_are_reported_once_and_survive_a_round_trip() {
859 let mut feed = Feed::default();
860 record(&mut feed, &incoming("a", "m1", "Anna", 1));
861 react(&mut feed, &[sighting("Ben", "B", Some(at(9, 1)))]);
862 let dirty = feed.take_dirty();
863 assert_eq!(dirty.len(), 2);
864 assert!(feed.take_dirty().is_empty());
865 let reloaded = Feed::load(dirty.iter().map(Entry::to_record).collect());
866 assert_eq!(all(&reloaded).len(), 2);
867 let mut reloaded = reloaded;
868 record(&mut reloaded, &incoming("c", "m9", "Cleo", 9));
869 let ids: BTreeSet<i64> = reloaded.take_dirty().iter().map(|entry| entry.id).collect();
870 assert_eq!(ids.len(), 1);
871 assert!(!dirty.iter().any(|entry| ids.contains(&entry.id)));
872 }
873
874 #[test]
875 fn start_time_defaults_to_now_and_is_clamped() {
876 let now = at(12, 0);
877 assert_eq!(start_time(None, now), now);
878 assert_eq!(start_time(Some(now + Duration::hours(1)), now), now);
879 assert_eq!(
880 start_time(Some(now - Duration::days(30)), now),
881 now - Duration::days(RETENTION_DAYS)
882 );
883 assert_eq!(start_time(Some(at(8, 0)), now), at(8, 0));
884 }
885 #[test]
886 fn a_missed_call_is_one_row_per_caller_until_it_is_read() {
887 let mut feed = Feed::load(Vec::new());
888 let caller = Actor {
889 user_id: Some("u1".into()),
890 name: "Cara".into(),
891 };
892 feed.record_missed_call("19:dm", caller.clone(), at(9, 0));
893 feed.record_missed_call("19:dm", caller.clone(), at(9, 5));
894 assert_eq!(feed.unread_count(), 1);
895 let entry = feed.get(1).unwrap();
896 assert_eq!(entry.kind, Kind::MissedCall);
897 assert_eq!(entry.count, 2);
898 assert_eq!(entry.updated_at, at(9, 5));
899 feed.mark_all_read();
900 feed.record_missed_call("19:dm", caller, at(10, 0));
901 assert_eq!(feed.unread_count(), 1);
902 feed.record_missed_call(
903 "19:other",
904 Actor {
905 user_id: Some("u2".into()),
906 name: "Dan".into(),
907 },
908 at(10, 1),
909 );
910 assert_eq!(feed.unread_count(), 2);
911 }
912
913 #[test]
914 fn missed_calls_survive_the_store_round_trip() {
915 let mut feed = Feed::load(Vec::new());
916 feed.record_missed_call(
917 "19:dm",
918 Actor {
919 user_id: Some("u1".into()),
920 name: "Cara".into(),
921 },
922 at(9, 0),
923 );
924 let record = feed.get(1).unwrap().to_record();
925 assert_eq!(record.kind, "missed_call");
926 let restored = Entry::from_record(record).unwrap();
927 assert_eq!(restored.kind, Kind::MissedCall);
928 }
929}