BlueGit

ict rusty-teams

Files

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

feed.rs

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