BlueGit

ict rusty-teams

Files

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

feed.rs

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