BlueGit

ict rusty-teams

Files

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

feed.rs

feed.rs 9.4 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}
162
163impl Entry {
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 is_personal_mention(&self) -> bool {
176 self.kind == Kind::Mention && matches!(self.subtype.as_str(), "person" | "tag")
177 }
178}
179
180pub struct Section<'a> {
181 pub bucket: Bucket,
182 pub entries: Vec<&'a Entry>,
183}
184
185#[derive(Default)]
186pub struct Feed {
187 entries: Vec<Entry>,
188}
189
190impl Feed {
191 pub fn new(entries: Vec<Entry>) -> Feed {
192 Feed { entries }
193 }
194
195 pub fn get(&self, id: &str) -> Option<&Entry> {
196 self.entries.iter().find(|entry| entry.id == id)
197 }
198
199 pub fn entries(&self) -> &[Entry] {
200 &self.entries
201 }
202
203 pub fn unread_count(&self) -> usize {
204 self.unread_entries().count()
205 }
206
207 pub fn unread_entries(&self) -> impl Iterator<Item = &Entry> {
208 self.entries.iter().filter(|entry| !entry.read)
209 }
210
211 /// The Activity bell: unread rows newer than the last time the feed was opened.
212 pub fn bell_count(&self) -> usize {
213 self.entries
214 .iter()
215 .filter(|entry| entry.counts_for_bell)
216 .count()
217 }
218
219 pub fn sections(
220 &self,
221 filter: Filter,
222 today: NaiveDate,
223 offset: FixedOffset,
224 ) -> Vec<Section<'_>> {
225 let mut admitted: Vec<&Entry> = self
226 .entries
227 .iter()
228 .filter(|entry| filter.admits(entry))
229 .collect();
230 admitted.sort_by(|left, right| {
231 (right.updated_at, &right.id).cmp(&(left.updated_at, &left.id))
232 });
233 let mut sections: Vec<Section<'_>> = Vec::new();
234 for entry in admitted {
235 let bucket = Bucket::of(entry.updated_at, today, offset);
236 match sections.last_mut() {
237 Some(section) if section.bucket == bucket => section.entries.push(entry),
238 _ => sections.push(Section {
239 bucket,
240 entries: vec![entry],
241 }),
242 }
243 }
244 sections
245 }
246}
247
248#[cfg(test)]
249mod tests {
250 use chrono::TimeZone;
251
252 use super::*;
253
254 fn at(day: u32, hour: u32) -> DateTime<Utc> {
255 Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap()
256 }
257
258 fn entry(id: &str, kind: Kind, updated_at: DateTime<Utc>, read: bool) -> Entry {
259 Entry {
260 id: id.into(),
261 kind,
262 updated_at,
263 read,
264 counts_for_bell: !read,
265 ..Entry::default()
266 }
267 }
268
269 #[test]
270 fn filters_round_trip_through_their_key() {
271 for filter in Filter::ALL {
272 assert_eq!(Filter::from_key(filter.key()), Some(filter));
273 }
274 assert_eq!(Filter::from_key("other"), None);
275 }
276
277 #[test]
278 fn sections_group_newest_first_by_day_and_filter() {
279 let feed = Feed::new(vec![
280 entry("old", Kind::Reply, at(6, 9), true),
281 entry("today", Kind::Mention, at(8, 9), false),
282 entry("yesterday", Kind::Reaction, at(7, 9), false),
283 entry("later", Kind::Mention, at(8, 10), true),
284 ]);
285 let today = at(8, 12).date_naive();
286 let offset = FixedOffset::east_opt(0).unwrap();
287 let sections = feed.sections(Filter::All, today, offset);
288 let shape: Vec<(Bucket, Vec<&str>)> = sections
289 .iter()
290 .map(|section| {
291 (
292 section.bucket,
293 section.entries.iter().map(|entry| entry.id.as_str()).collect(),
294 )
295 })
296 .collect();
297 assert_eq!(
298 shape,
299 [
300 (Bucket::Today, vec!["later", "today"]),
301 (Bucket::Yesterday, vec!["yesterday"]),
302 (Bucket::Earlier, vec!["old"]),
303 ]
304 );
305 let mentions = feed.sections(Filter::Mentions, today, offset);
306 assert_eq!(mentions[0].entries.len(), 2);
307 let unread = feed.sections(Filter::Unread, today, offset);
308 assert_eq!(unread.iter().map(|section| section.entries.len()).sum::<usize>(), 2);
309 assert_eq!(feed.unread_count(), 2);
310 assert_eq!(feed.bell_count(), 2);
311 }
312
313 #[test]
314 fn kind_filters_keep_only_their_kind() {
315 let feed = Feed::new(vec![
316 entry("reply", Kind::Reply, at(8, 9), true),
317 entry("reaction", Kind::Reaction, at(8, 9), false),
318 entry("missed", Kind::MissedCall, at(8, 9), false),
319 entry("call", Kind::Call, at(8, 9), false),
320 ]);
321 let today = at(8, 12).date_naive();
322 let offset = FixedOffset::east_opt(0).unwrap();
323 let ids = |filter| -> Vec<String> {
324 feed.sections(filter, today, offset)
325 .iter()
326 .flat_map(|section| section.entries.iter().map(|entry| entry.id.clone()))
327 .collect()
328 };
329 assert_eq!(ids(Filter::Replies), ["reply"]);
330 assert_eq!(ids(Filter::Reactions), ["reaction"]);
331 assert_eq!(ids(Filter::MissedCalls), ["missed"]);
332 }
333}