BlueGit

ict rusty-teams

Files

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

feed.rs

feed.rs 9.5 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 Replies,
29 Reactions,
30 MissedCalls,
31}
32
33impl Filter {
34 pub const PRIMARY: [Filter; 3] = [Filter::All, Filter::Mentions, Filter::Unread];
35 pub const OVERFLOW: [Filter; 3] = [Filter::Replies, Filter::Reactions, Filter::MissedCalls];
36 pub const ALL: [Filter; 6] = [
37 Filter::All,
38 Filter::Mentions,
39 Filter::Unread,
40 Filter::Replies,
41 Filter::Reactions,
42 Filter::MissedCalls,
43 ];
44
45 pub fn key(self) -> &'static str {
46 match self {
47 Filter::All => "all",
48 Filter::Mentions => "mentions",
49 Filter::Unread => "unread",
50 Filter::Replies => "replies",
51 Filter::Reactions => "reactions",
52 Filter::MissedCalls => "missed_calls",
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 Filter::Replies => "Replies",
66 Filter::Reactions => "Reactions",
67 Filter::MissedCalls => "Missed calls",
68 }
69 }
70
71 pub fn empty_label(self) -> &'static str {
72 match self {
73 Filter::All => "No activity yet",
74 Filter::Mentions => "No mentions",
75 Filter::Unread => "Nothing unread",
76 Filter::Replies => "No replies",
77 Filter::Reactions => "No reactions",
78 Filter::MissedCalls => "No missed calls",
79 }
80 }
81
82 fn admits(self, entry: &Entry) -> bool {
83 match self {
84 Filter::All => true,
85 Filter::Mentions => entry.kind == Kind::Mention,
86 Filter::Unread => !entry.read,
87 Filter::Replies => entry.kind == Kind::Reply,
88 Filter::Reactions => entry.kind == Kind::Reaction,
89 Filter::MissedCalls => entry.kind == Kind::MissedCall,
90 }
91 }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum Bucket {
96 Today,
97 Yesterday,
98 Earlier,
99}
100
101impl Bucket {
102 pub fn of(time: DateTime<Utc>, today: NaiveDate, offset: FixedOffset) -> Bucket {
103 let days_ago = (today - time.with_timezone(&offset).date_naive()).num_days();
104 match days_ago {
105 ..=0 => Bucket::Today,
106 1 => Bucket::Yesterday,
107 _ => Bucket::Earlier,
108 }
109 }
110
111 pub fn label(self) -> &'static str {
112 match self {
113 Bucket::Today => "Today",
114 Bucket::Yesterday => "Yesterday",
115 Bucket::Earlier => "Earlier",
116 }
117 }
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub struct Actor {
122 pub user_id: Option<String>,
123 pub name: String,
124}
125
126impl Actor {
127 pub fn is_unresolved(&self) -> bool {
128 self.user_id.is_some() && (self.name.is_empty() || self.name == UNKNOWN_REACTOR)
129 }
130
131 pub fn display_name<'a>(&'a self, resolved: &'a HashMap<String, String>) -> &'a str {
132 if self.is_unresolved()
133 && let Some(name) = self
134 .user_id
135 .as_ref()
136 .and_then(|user_id| resolved.get(user_id))
137 {
138 return name;
139 }
140 &self.name
141 }
142}
143
144/// One Activity row. `id` is the Teams activity message id in `48:notifications`.
145#[derive(Debug, Clone, PartialEq, Default)]
146pub struct Entry {
147 pub id: String,
148 pub conversation_id: String,
149 pub kind: Kind,
150 pub activity_type: String,
151 pub subtype: String,
152 pub message_id: String,
153 pub actors: Vec<Actor>,
154 pub preview: String,
155 pub glyphs: Vec<String>,
156 pub count: u32,
157 pub updated_at: DateTime<Utc>,
158 pub read: bool,
159 pub counts_for_bell: bool,
160 pub source_label: Option<String>,
161 pub link: Option<String>,
162 pub reply_id: Option<String>,
163 pub title: Option<String>,
164 pub event_range: Option<(DateTime<Utc>, DateTime<Utc>)>,
165}
166
167impl Entry {
168 pub fn unresolved_user_ids(&self) -> impl Iterator<Item = &String> {
169 self.actors
170 .iter()
171 .filter(|actor| actor.is_unresolved())
172 .filter_map(|actor| actor.user_id.as_ref())
173 }
174
175 pub fn latest_actor(&self) -> Option<&Actor> {
176 self.actors.last()
177 }
178
179 pub fn is_personal_mention(&self) -> bool {
180 self.kind == Kind::Mention && matches!(self.subtype.as_str(), "person" | "tag")
181 }
182}
183
184pub struct Section<'a> {
185 pub bucket: Bucket,
186 pub entries: Vec<&'a Entry>,
187}
188
189#[derive(Default)]
190pub struct Feed {
191 entries: Vec<Entry>,
192}
193
194impl Feed {
195 pub fn new(entries: Vec<Entry>) -> Feed {
196 Feed { entries }
197 }
198
199 pub fn get(&self, id: &str) -> Option<&Entry> {
200 self.entries.iter().find(|entry| entry.id == id)
201 }
202
203 pub fn entries(&self) -> &[Entry] {
204 &self.entries
205 }
206
207 pub fn unread_count(&self) -> usize {
208 self.unread_entries().count()
209 }
210
211 pub fn unread_entries(&self) -> impl Iterator<Item = &Entry> {
212 self.entries.iter().filter(|entry| !entry.read)
213 }
214
215 /// The Activity bell: unread rows newer than the last time the feed was opened.
216 pub fn bell_count(&self) -> usize {
217 self.entries
218 .iter()
219 .filter(|entry| entry.counts_for_bell)
220 .count()
221 }
222
223 pub fn sections(
224 &self,
225 filter: Filter,
226 today: NaiveDate,
227 offset: FixedOffset,
228 ) -> Vec<Section<'_>> {
229 let mut admitted: Vec<&Entry> = self
230 .entries
231 .iter()
232 .filter(|entry| filter.admits(entry))
233 .collect();
234 admitted.sort_by(|left, right| {
235 (right.updated_at, &right.id).cmp(&(left.updated_at, &left.id))
236 });
237 let mut sections: Vec<Section<'_>> = Vec::new();
238 for entry in admitted {
239 let bucket = Bucket::of(entry.updated_at, today, offset);
240 match sections.last_mut() {
241 Some(section) if section.bucket == bucket => section.entries.push(entry),
242 _ => sections.push(Section {
243 bucket,
244 entries: vec![entry],
245 }),
246 }
247 }
248 sections
249 }
250}
251
252#[cfg(test)]
253mod tests {
254 use chrono::TimeZone;
255
256 use super::*;
257
258 fn at(day: u32, hour: u32) -> DateTime<Utc> {
259 Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap()
260 }
261
262 fn entry(id: &str, kind: Kind, updated_at: DateTime<Utc>, read: bool) -> Entry {
263 Entry {
264 id: id.into(),
265 kind,
266 updated_at,
267 read,
268 counts_for_bell: !read,
269 ..Entry::default()
270 }
271 }
272
273 #[test]
274 fn filters_round_trip_through_their_key() {
275 for filter in Filter::ALL {
276 assert_eq!(Filter::from_key(filter.key()), Some(filter));
277 }
278 assert_eq!(Filter::from_key("other"), None);
279 }
280
281 #[test]
282 fn sections_group_newest_first_by_day_and_filter() {
283 let feed = Feed::new(vec![
284 entry("old", Kind::Reply, at(6, 9), true),
285 entry("today", Kind::Mention, at(8, 9), false),
286 entry("yesterday", Kind::Reaction, at(7, 9), false),
287 entry("later", Kind::Mention, at(8, 10), true),
288 ]);
289 let today = at(8, 12).date_naive();
290 let offset = FixedOffset::east_opt(0).unwrap();
291 let sections = feed.sections(Filter::All, today, offset);
292 let shape: Vec<(Bucket, Vec<&str>)> = sections
293 .iter()
294 .map(|section| {
295 (
296 section.bucket,
297 section.entries.iter().map(|entry| entry.id.as_str()).collect(),
298 )
299 })
300 .collect();
301 assert_eq!(
302 shape,
303 [
304 (Bucket::Today, vec!["later", "today"]),
305 (Bucket::Yesterday, vec!["yesterday"]),
306 (Bucket::Earlier, vec!["old"]),
307 ]
308 );
309 let mentions = feed.sections(Filter::Mentions, today, offset);
310 assert_eq!(mentions[0].entries.len(), 2);
311 let unread = feed.sections(Filter::Unread, today, offset);
312 assert_eq!(unread.iter().map(|section| section.entries.len()).sum::<usize>(), 2);
313 assert_eq!(feed.unread_count(), 2);
314 assert_eq!(feed.bell_count(), 2);
315 }
316
317 #[test]
318 fn kind_filters_keep_only_their_kind() {
319 let feed = Feed::new(vec![
320 entry("reply", Kind::Reply, at(8, 9), true),
321 entry("reaction", Kind::Reaction, at(8, 9), false),
322 entry("missed", Kind::MissedCall, at(8, 9), false),
323 entry("call", Kind::Call, at(8, 9), false),
324 ]);
325 let today = at(8, 12).date_naive();
326 let offset = FixedOffset::east_opt(0).unwrap();
327 let ids = |filter| -> Vec<String> {
328 feed.sections(filter, today, offset)
329 .iter()
330 .flat_map(|section| section.entries.iter().map(|entry| entry.id.clone()))
331 .collect()
332 };
333 assert_eq!(ids(Filter::Replies), ["reply"]);
334 assert_eq!(ids(Filter::Reactions), ["reaction"]);
335 assert_eq!(ids(Filter::MissedCalls), ["missed"]);
336 }
337}