BlueGit

ict rusty-teams

Files

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

feed.rs

feed.rs 29.9 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 chat: Default::default(),
579 created_at: at(9, minute),
580 importance: Default::default(),
581 }
582 }
583
584 fn record(feed: &mut Feed, incoming: &Incoming) {
585 feed.record_message(incoming, format!("text {}", incoming.message_id));
586 }
587
588 fn sighting(user: &str, glyph: &str, created_at: Option<DateTime<Utc>>) -> Sighting {
589 Sighting {
590 user_id: Some(format!("id-{user}")),
591 name: user.into(),
592 glyph: glyph.into(),
593 created_at,
594 }
595 }
596
597 fn react(feed: &mut Feed, sightings: &[Sighting]) {
598 let message = ReactedMessage {
599 message_id: "mine".into(),
600 preview: "my text".into(),
601 sightings: sightings.to_vec(),
602 };
603 feed.record_reactions("chat", &message, "id-me", at(8, 0), at(10, 0));
604 }
605
606 fn all(feed: &Feed) -> Vec<&Entry> {
607 feed.sections(Filter::All, at(9, 0).date_naive(), offset())
608 .into_iter()
609 .flat_map(|section| section.entries)
610 .collect()
611 }
612
613 fn offset() -> FixedOffset {
614 FixedOffset::east_opt(0).unwrap()
615 }
616
617 #[test]
618 fn three_messages_share_one_row_and_keep_the_first_message_id() {
619 let mut feed = Feed::default();
620 for (index, message_id) in ["m1", "m2", "m3"].into_iter().enumerate() {
621 record(
622 &mut feed,
623 &incoming("chat", message_id, "Anna", index as u32),
624 );
625 }
626 let entries = all(&feed);
627 assert_eq!(entries.len(), 1);
628 assert_eq!(entries[0].count, 3);
629 assert_eq!(entries[0].message_id, "m1");
630 assert_eq!(entries[0].preview, "text m3");
631 assert_eq!(entries[0].updated_at, at(9, 2));
632 assert_eq!(feed.unread_count(), 1);
633 }
634
635 #[test]
636 fn latest_sender_moves_to_the_end() {
637 let mut feed = Feed::default();
638 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
639 record(&mut feed, &incoming("chat", "m2", "Ben", 2));
640 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
641 let entries = all(&feed);
642 let entry = entries[0];
643 assert_eq!(entry.names(&HashMap::new()), "Ben and Anna");
644 assert_eq!(entry.latest_actor().unwrap().name, "Anna");
645 }
646
647 #[test]
648 fn chat_preview_adds_a_row_only_when_newer_than_the_feed() {
649 let mut feed = Feed::default();
650 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
651 let anna = Actor {
652 user_id: Some("id-Anna".into()),
653 name: "Anna".into(),
654 };
655 feed.record_chat_preview("chat", anna.clone(), "text m1".into(), at(9, 1));
656 assert_eq!(all(&feed)[0].count, 1);
657 feed.record_chat_preview("chat", anna.clone(), "later".into(), at(9, 5));
658 assert_eq!(all(&feed)[0].count, 2);
659 assert_eq!(all(&feed)[0].preview, "later");
660 feed.record_chat_preview("other", anna, "offline".into(), at(9, 6));
661 let entries = all(&feed);
662 assert_eq!(entries.len(), 2);
663 assert_eq!(entries[0].message_id, "");
664 }
665
666 #[test]
667 fn message_after_read_opens_a_new_row() {
668 let mut feed = Feed::default();
669 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
670 feed.mark_conversation_read("chat");
671 record(&mut feed, &incoming("chat", "m2", "Anna", 2));
672 let entries = all(&feed);
673 assert_eq!(entries.len(), 2);
674 assert_eq!(entries[0].message_id, "m2");
675 assert!(!entries[0].read);
676 assert!(entries[1].read);
677 assert_eq!(entries[1].count, 1);
678 }
679
680 #[test]
681 fn mention_gets_its_own_row_and_is_not_counted_in_messages() {
682 let mut feed = Feed::default();
683 record(&mut feed, &incoming("chat", "m1", "Anna", 1));
684 let mut mention = incoming("chat", "m2", "Ben", 2);
685 mention.mentions_me = true;
686 record(&mut feed, &mention);
687 record(&mut feed, &incoming("chat", "m3", "Anna", 3));
688 let entries = all(&feed);
689 assert_eq!(entries.len(), 2);
690 let mention_row = entries
691 .iter()
692 .find(|entry| entry.kind == Kind::Mention)
693 .unwrap();
694 assert_eq!(mention_row.message_id, "m2");
695 let messages_row = entries
696 .iter()
697 .find(|entry| entry.kind == Kind::Messages)
698 .unwrap();
699 assert_eq!(messages_row.count, 2);
700 assert_eq!(messages_row.message_id, "m1");
701 }
702
703 #[test]
704 fn reactions_bundle_per_message_and_become_unread_again() {
705 let mut feed = Feed::default();
706 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
707 feed.mark_all_read();
708 assert_eq!(feed.unread_count(), 0);
709 react(
710 &mut feed,
711 &[
712 sighting("Anna", "A", Some(at(9, 1))),
713 sighting("Ben", "B", Some(at(9, 5))),
714 ],
715 );
716 let entries = all(&feed);
717 assert_eq!(entries.len(), 1);
718 assert_eq!(entries[0].names(&HashMap::new()), "Anna and Ben");
719 assert_eq!(entries[0].glyphs, vec!["A", "B"]);
720 assert_eq!(entries[0].count, 2);
721 assert_eq!(entries[0].updated_at, at(9, 5));
722 assert!(!entries[0].read);
723 assert_eq!(entries[0].preview, "my text");
724 }
725
726 #[test]
727 fn known_reactor_adding_a_glyph_does_not_reopen_the_row() {
728 let mut feed = Feed::default();
729 react(&mut feed, &[sighting("Anna", "A", Some(at(9, 1)))]);
730 feed.mark_all_read();
731 react(&mut feed, &[sighting("Anna", "C", Some(at(9, 2)))]);
732 let entries = all(&feed);
733 assert_eq!(entries[0].glyphs, vec!["A", "C"]);
734 assert!(entries[0].read);
735 }
736
737 #[test]
738 fn own_and_anonymous_reactions_are_ignored() {
739 let mut feed = Feed::default();
740 let anonymous = Sighting {
741 user_id: None,
742 ..sighting("Anna", "A", Some(at(9, 1)))
743 };
744 react(&mut feed, &[sighting("me", "A", Some(at(9, 1))), anonymous]);
745 assert!(all(&feed).is_empty());
746 }
747
748 #[test]
749 fn old_reactions_on_first_sight_are_ignored() {
750 let mut feed = Feed::default();
751 react(
752 &mut feed,
753 &[
754 sighting("Anna", "A", Some(at(7, 0))),
755 sighting("Ben", "B", None),
756 ],
757 );
758 assert!(all(&feed).is_empty());
759 react(&mut feed, &[sighting("Cleo", "C", Some(at(9, 0)))]);
760 react(&mut feed, &[sighting("Dan", "D", None)]);
761 assert_eq!(all(&feed)[0].names(&HashMap::new()), "Cleo and Dan");
762 }
763
764 #[test]
765 fn reading_a_conversation_leaves_others_unread() {
766 let mut feed = Feed::default();
767 record(&mut feed, &incoming("a", "m1", "Anna", 1));
768 record(&mut feed, &incoming("b", "m2", "Ben", 2));
769 assert!(feed.mark_conversation_read("a"));
770 assert!(!feed.mark_conversation_read("a"));
771 assert_eq!(feed.unread_count(), 1);
772 let unread = all(&feed).into_iter().find(|entry| !entry.read).unwrap();
773 assert_eq!(unread.conversation_id, "b");
774 }
775
776 #[test]
777 fn read_sync_only_covers_rows_up_to_the_read_time() {
778 let mut feed = Feed::default();
779 record(&mut feed, &incoming("a", "m1", "Anna", 1));
780 feed.mark_conversation_read("a");
781 record(&mut feed, &incoming("a", "m2", "Anna", 30));
782 record(&mut feed, &incoming("b", "m3", "Ben", 1));
783 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 10)));
784 assert!(!changed);
785 let changed = feed.sync_read(|conversation_id| (conversation_id == "a").then(|| at(9, 45)));
786 assert!(changed);
787 assert_eq!(feed.unread_count(), 1);
788 }
789
790 #[test]
791 fn mark_all_read_clears_the_count_and_reports_change_once() {
792 let mut feed = Feed::default();
793 record(&mut feed, &incoming("a", "m1", "Anna", 1));
794 record(&mut feed, &incoming("b", "m2", "Ben", 2));
795 assert!(feed.mark_all_read());
796 assert_eq!(feed.unread_count(), 0);
797 assert!(!feed.mark_all_read());
798 }
799
800 #[test]
801 fn filters_pick_mentions_and_unread() {
802 let mut feed = Feed::default();
803 record(&mut feed, &incoming("a", "m1", "Anna", 1));
804 let mut mention = incoming("b", "m2", "Ben", 2);
805 mention.mentions_me = true;
806 record(&mut feed, &mention);
807 feed.mark_conversation_read("a");
808 let today = at(9, 0).date_naive();
809 let count = |filter| {
810 feed.sections(filter, today, offset())
811 .iter()
812 .map(|section| section.entries.len())
813 .sum::<usize>()
814 };
815 assert_eq!(count(Filter::All), 2);
816 assert_eq!(count(Filter::Mentions), 1);
817 assert_eq!(count(Filter::Unread), 1);
818 }
819
820 #[test]
821 fn buckets_follow_the_local_day() {
822 let today = at(12, 0).date_naive();
823 let utc = offset();
824 assert_eq!(Bucket::of(at(0, 5), today, utc), Bucket::Today);
825 assert_eq!(
826 Bucket::of(at(0, 5) - Duration::minutes(10), today, utc),
827 Bucket::Yesterday
828 );
829 assert_eq!(
830 Bucket::of(at(0, 5) - Duration::days(3), today, utc),
831 Bucket::Earlier
832 );
833 let east = FixedOffset::east_opt(2 * 3600).unwrap();
834 assert_eq!(
835 Bucket::of(at(23, 30) - Duration::days(1), today, east),
836 Bucket::Today
837 );
838 }
839
840 #[test]
841 fn sections_are_newest_first_and_grouped() {
842 let mut feed = Feed::default();
843 let mut old = incoming("a", "m1", "Anna", 1);
844 old.created_at = at(9, 0) - Duration::days(1);
845 record(&mut feed, &old);
846 record(&mut feed, &incoming("b", "m2", "Ben", 2));
847 record(&mut feed, &incoming("c", "m3", "Cleo", 3));
848 let today = at(9, 0).date_naive();
849 let sections = feed.sections(Filter::All, today, offset());
850 let labels: Vec<&str> = sections
851 .iter()
852 .map(|section| section.bucket.label())
853 .collect();
854 assert_eq!(labels, ["Today", "Yesterday"]);
855 assert_eq!(sections[0].entries[0].conversation_id, "c");
856 }
857
858 #[test]
859 fn dirty_rows_are_reported_once_and_survive_a_round_trip() {
860 let mut feed = Feed::default();
861 record(&mut feed, &incoming("a", "m1", "Anna", 1));
862 react(&mut feed, &[sighting("Ben", "B", Some(at(9, 1)))]);
863 let dirty = feed.take_dirty();
864 assert_eq!(dirty.len(), 2);
865 assert!(feed.take_dirty().is_empty());
866 let reloaded = Feed::load(dirty.iter().map(Entry::to_record).collect());
867 assert_eq!(all(&reloaded).len(), 2);
868 let mut reloaded = reloaded;
869 record(&mut reloaded, &incoming("c", "m9", "Cleo", 9));
870 let ids: BTreeSet<i64> = reloaded.take_dirty().iter().map(|entry| entry.id).collect();
871 assert_eq!(ids.len(), 1);
872 assert!(!dirty.iter().any(|entry| ids.contains(&entry.id)));
873 }
874
875 #[test]
876 fn start_time_defaults_to_now_and_is_clamped() {
877 let now = at(12, 0);
878 assert_eq!(start_time(None, now), now);
879 assert_eq!(start_time(Some(now + Duration::hours(1)), now), now);
880 assert_eq!(
881 start_time(Some(now - Duration::days(30)), now),
882 now - Duration::days(RETENTION_DAYS)
883 );
884 assert_eq!(start_time(Some(at(8, 0)), now), at(8, 0));
885 }
886 #[test]
887 fn a_missed_call_is_one_row_per_caller_until_it_is_read() {
888 let mut feed = Feed::load(Vec::new());
889 let caller = Actor {
890 user_id: Some("u1".into()),
891 name: "Cara".into(),
892 };
893 feed.record_missed_call("19:dm", caller.clone(), at(9, 0));
894 feed.record_missed_call("19:dm", caller.clone(), at(9, 5));
895 assert_eq!(feed.unread_count(), 1);
896 let entry = feed.get(1).unwrap();
897 assert_eq!(entry.kind, Kind::MissedCall);
898 assert_eq!(entry.count, 2);
899 assert_eq!(entry.updated_at, at(9, 5));
900 feed.mark_all_read();
901 feed.record_missed_call("19:dm", caller, at(10, 0));
902 assert_eq!(feed.unread_count(), 1);
903 feed.record_missed_call(
904 "19:other",
905 Actor {
906 user_id: Some("u2".into()),
907 name: "Dan".into(),
908 },
909 at(10, 1),
910 );
911 assert_eq!(feed.unread_count(), 2);
912 }
913
914 #[test]
915 fn missed_calls_survive_the_store_round_trip() {
916 let mut feed = Feed::load(Vec::new());
917 feed.record_missed_call(
918 "19:dm",
919 Actor {
920 user_id: Some("u1".into()),
921 name: "Cara".into(),
922 },
923 at(9, 0),
924 );
925 let record = feed.get(1).unwrap().to_record();
926 assert_eq!(record.kind, "missed_call");
927 let restored = Entry::from_record(record).unwrap();
928 assert_eq!(restored.kind, Kind::MissedCall);
929 }
930}