BlueGit

ict rusty-teams

Files

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

feed.rs

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