BlueGit

ict rusty-teams

Files

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

feed.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
feed.rs 9.7 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
235 .sort_by(|left, right| (right.updated_at, &right.id).cmp(&(left.updated_at, &left.id)));
236 let mut sections: Vec<Section<'_>> = Vec::new();
237 for entry in admitted {
238 let bucket = Bucket::of(entry.updated_at, today, offset);
239 match sections.last_mut() {
240 Some(section) if section.bucket == bucket => section.entries.push(entry),
241 _ => sections.push(Section {
242 bucket,
243 entries: vec![entry],
244 }),
245 }
246 }
247 sections
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use chrono::TimeZone;
254
255 use super::*;
256
257 fn at(day: u32, hour: u32) -> DateTime<Utc> {
258 Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap()
259 }
260
261 fn entry(id: &str, kind: Kind, updated_at: DateTime<Utc>, read: bool) -> Entry {
262 Entry {
263 id: id.into(),
264 kind,
265 updated_at,
266 read,
267 counts_for_bell: !read,
268 ..Entry::default()
269 }
270 }
271
272 #[test]
273 fn filters_round_trip_through_their_key() {
274 for filter in Filter::ALL {
275 assert_eq!(Filter::from_key(filter.key()), Some(filter));
276 }
277 assert_eq!(Filter::from_key("other"), None);
278 }
279
280 #[test]
281 fn sections_group_newest_first_by_day_and_filter() {
282 let feed = Feed::new(vec![
283 entry("old", Kind::Reply, at(6, 9), true),
284 entry("today", Kind::Mention, at(8, 9), false),
285 entry("yesterday", Kind::Reaction, at(7, 9), false),
286 entry("later", Kind::Mention, at(8, 10), true),
287 ]);
288 let today = at(8, 12).date_naive();
289 let offset = FixedOffset::east_opt(0).unwrap();
290 let sections = feed.sections(Filter::All, today, offset);
291 let shape: Vec<(Bucket, Vec<&str>)> = sections
292 .iter()
293 .map(|section| {
294 (
295 section.bucket,
296 section
297 .entries
298 .iter()
299 .map(|entry| entry.id.as_str())
300 .collect(),
301 )
302 })
303 .collect();
304 assert_eq!(
305 shape,
306 [
307 (Bucket::Today, vec!["later", "today"]),
308 (Bucket::Yesterday, vec!["yesterday"]),
309 (Bucket::Earlier, vec!["old"]),
310 ]
311 );
312 let mentions = feed.sections(Filter::Mentions, today, offset);
313 assert_eq!(mentions[0].entries.len(), 2);
314 let unread = feed.sections(Filter::Unread, today, offset);
315 assert_eq!(
316 unread
317 .iter()
318 .map(|section| section.entries.len())
319 .sum::<usize>(),
320 2
321 );
322 assert_eq!(feed.unread_count(), 2);
323 assert_eq!(feed.bell_count(), 2);
324 }
325
326 #[test]
327 fn kind_filters_keep_only_their_kind() {
328 let feed = Feed::new(vec![
329 entry("reply", Kind::Reply, at(8, 9), true),
330 entry("reaction", Kind::Reaction, at(8, 9), false),
331 entry("missed", Kind::MissedCall, at(8, 9), false),
332 entry("call", Kind::Call, at(8, 9), false),
333 ]);
334 let today = at(8, 12).date_naive();
335 let offset = FixedOffset::east_opt(0).unwrap();
336 let ids = |filter| -> Vec<String> {
337 feed.sections(filter, today, offset)
338 .iter()
339 .flat_map(|section| section.entries.iter().map(|entry| entry.id.clone()))
340 .collect()
341 };
342 assert_eq!(ids(Filter::Replies), ["reply"]);
343 assert_eq!(ids(Filter::Reactions), ["reaction"]);
344 assert_eq!(ids(Filter::MissedCalls), ["missed"]);
345 }
346}