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