BlueGit

ict rusty-teams

Files

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

feed.rs

feed.rs 7.6 KiB Download Raw
1use std::collections::HashMap;
2
3use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
4use serde::{Deserialize, Serialize};
5
6use crate::reaction_model::UNKNOWN_REACTOR;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9pub enum Kind {
10 Mention,
11 Reply,
12 Reaction,
13 MissedCall,
14 Call,
15 Posted,
16 Team,
17 App,
18 #[default]
19 Other,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub enum Filter {
24 #[default]
25 All,
26 Mentions,
27 Unread,
28}
29
30impl Filter {
31 pub const ALL: [Filter; 3] = [Filter::All, Filter::Mentions, Filter::Unread];
32
33 pub fn key(self) -> &'static str {
34 match self {
35 Filter::All => "all",
36 Filter::Mentions => "mentions",
37 Filter::Unread => "unread",
38 }
39 }
40
41 pub fn from_key(key: &str) -> Option<Filter> {
42 Filter::ALL.into_iter().find(|filter| filter.key() == key)
43 }
44
45 pub fn label(self) -> &'static str {
46 match self {
47 Filter::All => "All",
48 Filter::Mentions => "@Mentions",
49 Filter::Unread => "Unread",
50 }
51 }
52
53 pub fn empty_label(self) -> &'static str {
54 match self {
55 Filter::All => "No activity yet",
56 Filter::Mentions => "No mentions",
57 Filter::Unread => "Nothing unread",
58 }
59 }
60
61 fn admits(self, entry: &Entry) -> bool {
62 match self {
63 Filter::All => true,
64 Filter::Mentions => entry.kind == Kind::Mention,
65 Filter::Unread => !entry.read,
66 }
67 }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum Bucket {
72 Today,
73 Yesterday,
74 Earlier,
75}
76
77impl Bucket {
78 pub fn of(time: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> Bucket {
79 let days_ago = (today - time.with_timezone(&offset).date_naive()).num_days();
80 match days_ago {
81 ..=0 => Bucket::Today,
82 1 => Bucket::Yesterday,
83 _ => Bucket::Earlier,
84 }
85 }
86
87 pub fn label(self) -> &'static str {
88 match self {
89 Bucket::Today => "Today",
90 Bucket::Yesterday => "Yesterday",
91 Bucket::Earlier => "Earlier",
92 }
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97pub struct Actor {
98 pub user_id: Option<String>,
99 pub name: String,
100}
101
102impl Actor {
103 pub fn is_unresolved(&self) -> bool {
104 self.user_id.is_some() && (self.name.is_empty() || self.name == UNKNOWN_REACTOR)
105 }
106
107 pub fn display_name<'a>(&'a self, resolved: &'a HashMap<String, String>) -> &'a str {
108 if self.is_unresolved()
109 && let Some(name) = self
110 .user_id
111 .as_ref()
112 .and_then(|user_id| resolved.get(user_id))
113 {
114 return name;
115 }
116 &self.name
117 }
118}
119
120/// One Activity row. `id` is the Teams activity message id in `48:notifications`.
121#[derive(Debug, Clone, PartialEq, Default)]
122pub struct Entry {
123 pub id: String,
124 pub conversation_id: String,
125 pub kind: Kind,
126 pub activity_type: String,
127 pub subtype: String,
128 pub message_id: String,
129 pub actors: Vec<Actor>,
130 pub preview: String,
131 pub glyphs: Vec<String>,
132 pub count: u32,
133 pub updated_at: DateTime<Utc>,
134 pub read: bool,
135 pub counts_for_bell: bool,
136 pub source_label: Option<String>,
137}
138
139impl Entry {
140 pub fn unresolved_user_ids(&self) -> impl Iterator<Item = &String> {
141 self.actors
142 .iter()
143 .filter(|actor| actor.is_unresolved())
144 .filter_map(|actor| actor.user_id.as_ref())
145 }
146
147 pub fn latest_actor(&self) -> Option<&Actor> {
148 self.actors.last()
149 }
150
151 pub fn is_personal_mention(&self) -> bool {
152 self.kind == Kind::Mention && matches!(self.subtype.as_str(), "person" | "tag")
153 }
154}
155
156pub struct Section<'a> {
157 pub bucket: Bucket,
158 pub entries: Vec<&'a Entry>,
159}
160
161#[derive(Default)]
162pub struct Feed {
163 entries: Vec<Entry>,
164}
165
166impl Feed {
167 pub fn new(entries: Vec<Entry>) -> Feed {
168 Feed { entries }
169 }
170
171 pub fn get(&self, id: &str) -> Option<&Entry> {
172 self.entries.iter().find(|entry| entry.id == id)
173 }
174
175 pub fn entries(&self) -> &[Entry] {
176 &self.entries
177 }
178
179 pub fn unread_count(&self) -> usize {
180 self.unread_entries().count()
181 }
182
183 pub fn unread_entries(&self) -> impl Iterator<Item = &Entry> {
184 self.entries.iter().filter(|entry| !entry.read)
185 }
186
187 /// The Activity bell: unread rows newer than the last time the feed was opened.
188 pub fn bell_count(&self) -> usize {
189 self.entries
190 .iter()
191 .filter(|entry| entry.counts_for_bell)
192 .count()
193 }
194
195 pub fn sections(
196 &self,
197 filter: Filter,
198 today: NaiveDate,
199 offset: FixedOffset,
200 ) -> Vec<Section<'_>> {
201 let mut admitted: Vec<&Entry> = self
202 .entries
203 .iter()
204 .filter(|entry| filter.admits(entry))
205 .collect();
206 admitted.sort_by(|left, right| {
207 (right.updated_at, &right.id).cmp(&(left.updated_at, &left.id))
208 });
209 let mut sections: Vec<Section<'_>> = Vec::new();
210 for entry in admitted {
211 let bucket = Bucket::of(entry.updated_at, today, offset);
212 match sections.last_mut() {
213 Some(section) if section.bucket == bucket => section.entries.push(entry),
214 _ => sections.push(Section {
215 bucket,
216 entries: vec![entry],
217 }),
218 }
219 }
220 sections
221 }
222}
223
224#[cfg(test)]
225mod tests {
226 use chrono::TimeZone;
227
228 use super::*;
229
230 fn at(day: u32, hour: u32) -> DateTime<Utc> {
231 Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap()
232 }
233
234 fn entry(id: &str, kind: Kind, updated_at: DateTime<Utc>, read: bool) -> Entry {
235 Entry {
236 id: id.into(),
237 kind,
238 updated_at,
239 read,
240 counts_for_bell: !read,
241 ..Entry::default()
242 }
243 }
244
245 #[test]
246 fn filters_round_trip_through_their_key() {
247 for filter in Filter::ALL {
248 assert_eq!(Filter::from_key(filter.key()), Some(filter));
249 }
250 assert_eq!(Filter::from_key("other"), None);
251 }
252
253 #[test]
254 fn sections_group_newest_first_by_day_and_filter() {
255 let feed = Feed::new(vec![
256 entry("old", Kind::Reply, at(6, 9), true),
257 entry("today", Kind::Mention, at(8, 9), false),
258 entry("yesterday", Kind::Reaction, at(7, 9), false),
259 entry("later", Kind::Mention, at(8, 10), true),
260 ]);
261 let today = at(8, 12).date_naive();
262 let offset = FixedOffset::east_opt(0).unwrap();
263 let sections = feed.sections(Filter::All, today, offset);
264 let shape: Vec<(Bucket, Vec<&str>)> = sections
265 .iter()
266 .map(|section| {
267 (
268 section.bucket,
269 section.entries.iter().map(|entry| entry.id.as_str()).collect(),
270 )
271 })
272 .collect();
273 assert_eq!(
274 shape,
275 [
276 (Bucket::Today, vec!["later", "today"]),
277 (Bucket::Yesterday, vec!["yesterday"]),
278 (Bucket::Earlier, vec!["old"]),
279 ]
280 );
281 let mentions = feed.sections(Filter::Mentions, today, offset);
282 assert_eq!(mentions[0].entries.len(), 2);
283 let unread = feed.sections(Filter::Unread, today, offset);
284 assert_eq!(unread.iter().map(|section| section.entries.len()).sum::<usize>(), 2);
285 assert_eq!(feed.unread_count(), 2);
286 assert_eq!(feed.bell_count(), 2);
287 }
288}