BlueGit

ict rusty-teams

Files

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

feed.rs

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