BlueGit

ict rusty-teams

Files

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

server.rs

server.rs 11.7 KiB Download Raw
1use chrono::{DateTime, Utc};
2use teams_core::{ActivityItem, ActivitySnapshot};
3
4use super::feed::{Actor, Entry, Feed, Kind};
5use crate::rows::reaction_glyph;
6
7const ORG_USER_PREFIX: &str = "8:orgid:";
8const CHANNEL_THREAD_TYPES: [&str; 2] = ["topic", "space"];
9const APP_TEMPLATES: [(&str, &str); 4] = [
10 ("recapIsReady", "Meeting recap is ready"),
11 ("recapIsReadyForFollowedMeetings", "Meeting recap is ready"),
12 ("recapIsReadyV2", "Recap ready: {subject}"),
13 ("recapIsReadyForFollowedMeetingsV2", "Recap ready: {subject}"),
14];
15
16pub fn feed_of(snapshot: &ActivitySnapshot, seen_locally_ms: i64) -> Feed {
17 Feed::new(
18 snapshot
19 .items
20 .iter()
21 .map(|item| {
22 let read = snapshot.is_read(item);
23 Entry {
24 read,
25 counts_for_bell: snapshot.counts_for_bell(item)
26 && item.timestamp_ms > seen_locally_ms,
27 ..entry_of(item)
28 }
29 })
30 .collect(),
31 )
32}
33
34fn entry_of(item: &ActivityItem) -> Entry {
35 let kind = kind_of(item);
36 let conversation_id = match (&item.meeting_thread_id, item.source_thread_id.is_empty()) {
37 (Some(meeting_thread_id), true) => meeting_thread_id.clone(),
38 _ => item.source_thread_id.clone(),
39 };
40 Entry {
41 id: item.message_id.clone(),
42 conversation_id,
43 kind,
44 activity_type: item.activity_type.clone(),
45 subtype: item.activity_subtype.clone(),
46 message_id: jump_target(item, kind),
47 actors: vec![Actor {
48 user_id: item
49 .source_user_id
50 .as_deref()
51 .and_then(|user_id| user_id.strip_prefix(ORG_USER_PREFIX))
52 .map(str::to_owned),
53 name: item.source_user_name.clone(),
54 }],
55 preview: preview_of(item),
56 glyphs: match kind {
57 Kind::Reaction if !item.activity_subtype.is_empty() => {
58 vec![reaction_glyph(&item.activity_subtype)]
59 }
60 _ => Vec::new(),
61 },
62 count: item.count.max(1),
63 updated_at: DateTime::from_timestamp_millis(item.timestamp_ms).unwrap_or_else(Utc::now),
64 read: false,
65 counts_for_bell: false,
66 source_label: item.source_app_name.clone().or_else(|| item.thread_topic.clone()),
67 link: item.tap_url.clone(),
68 reply_id: channel_reply(item, kind),
69 title: app_title(item),
70 event_range: item
71 .event_start_ms
72 .zip(item.event_end_ms)
73 .and_then(|(start_ms, end_ms)| {
74 Some((
75 DateTime::from_timestamp_millis(start_ms)?,
76 DateTime::from_timestamp_millis(end_ms)?,
77 ))
78 }),
79 }
80}
81
82fn app_title(item: &ActivityItem) -> Option<String> {
83 let (_, template) = APP_TEMPLATES
84 .iter()
85 .find(|(subtype, _)| *subtype == item.activity_subtype)?;
86 let mut title = String::new();
87 let mut rest = *template;
88 while let Some(open) = rest.find('{') {
89 let close = open + rest[open..].find('}')?;
90 title.push_str(&rest[..open]);
91 title.push_str(item.template_parameters.get(&rest[open + 1..close])?.trim());
92 rest = &rest[close + 1..];
93 }
94 title.push_str(rest);
95 Some(title.trim().to_owned())
96}
97
98pub fn kind_of(item: &ActivityItem) -> Kind {
99 match item.activity_type.as_str() {
100 "mention" | "mentionInChat" | "mentionInCommunity" | "mentionInSubCommunity"
101 | "communityMention" => Kind::Mention,
102 "reply" | "replyToReply" | "replyInChat" | "communityReply" | "communityReplyToReply" => {
103 Kind::Reply
104 }
105 "reaction" | "reactionInChat" | "like" | "likeInChat" | "reactionInCommunity"
106 | "reactionInSubCommunity" => Kind::Reaction,
107 "call" if item.activity_subtype == "missedCall" => Kind::MissedCall,
108 "call" | "voicemail" | "callOrMeetup" => Kind::Call,
109 "follow" => Kind::Posted,
110 "teamMembershipChange" => Kind::Team,
111 "msGraph" | "thirdParty" => Kind::App,
112 _ => Kind::Other,
113 }
114}
115
116fn channel_reply(item: &ActivityItem, kind: Kind) -> Option<String> {
117 let target = jump_target(item, kind);
118 item.source_message_id
119 .clone()
120 .filter(|reply_id| !target.is_empty() && *reply_id != target)
121}
122
123fn jump_target(item: &ActivityItem, kind: Kind) -> String {
124 if matches!(kind, Kind::MissedCall | Kind::Call | Kind::Team | Kind::App) {
125 return String::new();
126 }
127 let in_channel = item
128 .thread_type
129 .as_deref()
130 .is_some_and(|thread_type| CHANNEL_THREAD_TYPES.contains(&thread_type));
131 let root = item.source_reply_chain_id.as_ref().filter(|_| in_channel);
132 root.or(item.source_message_id.as_ref())
133 .cloned()
134 .unwrap_or_default()
135}
136
137fn preview_of(item: &ActivityItem) -> String {
138 let fixed = match item.preview_template.as_str() {
139 "sentAFile" => "Sent a file",
140 "sentAnImage" => "Sent an image",
141 "sentACard" => "Sent a card",
142 "previewUnavailable" if item.preview.is_empty() => "Preview Unavailable",
143 "deleted" => "This message has been deleted.",
144 "forwardedMessage" => "Forwarded message",
145 "isMeeting" => "Teams Meeting",
146 "replyWithQuote" if item.preview.is_empty() => "Replied with quote",
147 _ => return item.preview.split_whitespace().collect::<Vec<_>>().join(" "),
148 };
149 fixed.to_owned()
150}
151
152#[cfg(test)]
153mod tests {
154 use teams_core::ActivityHorizons;
155
156 use super::*;
157
158 fn item(activity_type: &str, subtype: &str) -> ActivityItem {
159 ActivityItem {
160 message_id: "1791368000001".into(),
161 activity_id: "1".into(),
162 activity_type: activity_type.into(),
163 activity_subtype: subtype.into(),
164 source_thread_id: "19:a@thread.tacv2".into(),
165 source_message_id: Some("1791367000002".into()),
166 source_reply_chain_id: Some("1791367000001".into()),
167 source_user_id: Some("8:orgid:user-1".into()),
168 source_user_name: "Ada Example".into(),
169 preview: "Ship it".into(),
170 preview_template: "hasText".into(),
171 thread_type: Some("topic".into()),
172 count: 1,
173 timestamp_ms: 1791368000000,
174 version_ms: 1791368000000,
175 ..ActivityItem::default()
176 }
177 }
178
179 #[test]
180 fn a_preview_with_line_breaks_becomes_one_line() {
181 let multiline = ActivityItem { preview: "Menu 09.11.-13.11. -\nPlease order\r\n until 9:30".into(), ..item("mention", "person") };
182 assert_eq!(preview_of(&multiline), "Menu 09.11.-13.11. - Please order until 9:30");
183 }
184
185 #[test]
186 fn a_recap_activity_gets_the_app_title_and_meeting_time() {
187 let mut recap = item("msGraph", "recapIsReadyForFollowedMeetingsV2");
188 recap
189 .template_parameters
190 .insert("subject".into(), "Following: Sprint {Demo} ".into());
191 recap.event_start_ms = Some(1793865600000);
192 recap.event_end_ms = Some(1793869200000);
193 let entry = entry_of(&recap);
194 assert_eq!(entry.title.as_deref(), Some("Recap ready: Following: Sprint {Demo}"));
195 let (start, end) = entry.event_range.unwrap();
196 assert_eq!((end - start).num_minutes(), 60);
197 assert_eq!(entry_of(&item("msGraph", "recapIsReadyV2")).title, None);
198 assert_eq!(entry_of(&item("msGraph", "somethingElse")).title, None);
199 }
200
201 #[test]
202 fn maps_the_teams_activity_types() {
203 let cases = [
204 ("mention", "person", Kind::Mention),
205 ("mentionInChat", "everyone", Kind::Mention),
206 ("replyToReply", "", Kind::Reply),
207 ("reactionInChat", "heart", Kind::Reaction),
208 ("call", "missedCall", Kind::MissedCall),
209 ("call", "missedMeetingNudge", Kind::Call),
210 ("follow", "channelNewMessage", Kind::Posted),
211 ("teamMembershipChange", "addedToTeam", Kind::Team),
212 ("msGraph", "recapIsReadyV2", Kind::App),
213 ("unknownType", "", Kind::Other),
214 ];
215 for (activity_type, subtype, kind) in cases {
216 assert_eq!(kind_of(&item(activity_type, subtype)), kind, "{activity_type}");
217 }
218 }
219
220 #[test]
221 fn a_channel_reply_jumps_to_its_root_and_a_chat_to_the_message() {
222 let channel = entry_of(&item("replyToReply", ""));
223 assert_eq!(channel.message_id, "1791367000001");
224 assert_eq!(channel.reply_id.as_deref(), Some("1791367000002"));
225 let chat = entry_of(&ActivityItem {
226 thread_type: Some("chat".into()),
227 ..item("mentionInChat", "person")
228 });
229 assert_eq!(chat.message_id, "1791367000002");
230 assert_eq!(chat.reply_id, None);
231 assert_eq!(entry_of(&item("call", "missedCall")).message_id, "");
232 assert_eq!(chat.actors[0].user_id.as_deref(), Some("user-1"));
233 }
234
235 #[test]
236 fn a_recap_opens_the_meeting_chat_it_names() {
237 let recap = entry_of(&ActivityItem {
238 source_thread_id: String::new(),
239 meeting_thread_id: Some("19:meeting_Zm9v@thread.v2".into()),
240 tap_url: Some("https://teams.microsoft.com/l/entity/x".into()),
241 ..item("msGraph", "recapIsReadyV2")
242 });
243 assert_eq!(recap.conversation_id, "19:meeting_Zm9v@thread.v2");
244 assert_eq!(recap.message_id, "");
245 assert_eq!(recap.link.as_deref(), Some("https://teams.microsoft.com/l/entity/x"));
246 }
247
248 #[test]
249 fn previews_follow_the_teams_template() {
250 let file = entry_of(&ActivityItem {
251 preview_template: "sentAFile".into(),
252 ..item("mention", "person")
253 });
254 assert_eq!(file.preview, "Sent a file");
255 let recap = entry_of(&ActivityItem {
256 preview: "You're following this meeting".into(),
257 preview_template: "previewUnavailable".into(),
258 ..item("msGraph", "recapIsReadyV2")
259 });
260 assert_eq!(recap.preview, "You're following this meeting");
261 let unavailable = entry_of(&ActivityItem {
262 preview: String::new(),
263 preview_template: "previewUnavailable".into(),
264 ..item("mention", "person")
265 });
266 assert_eq!(unavailable.preview, "Preview Unavailable");
267 assert_eq!(entry_of(&item("mention", "person")).preview, "Ship it");
268 assert_eq!(entry_of(&item("reactionInChat", "like")).glyphs.len(), 1);
269 }
270
271 #[test]
272 fn read_and_bell_come_from_the_snapshot_and_the_local_seen_mark() {
273 let snapshot = ActivitySnapshot {
274 items: vec![
275 ActivityItem {
276 message_id: "old".into(),
277 timestamp_ms: 100,
278 version_ms: 100,
279 ..item("mention", "person")
280 },
281 ActivityItem {
282 message_id: "new".into(),
283 timestamp_ms: 300,
284 version_ms: 300,
285 ..item("mention", "person")
286 },
287 ActivityItem {
288 message_id: "flagged".into(),
289 timestamp_ms: 400,
290 version_ms: 400,
291 read_flag: true,
292 ..item("mention", "person")
293 },
294 ],
295 horizons: ActivityHorizons {
296 seen_ms: 50,
297 bookmark_ms: 150,
298 },
299 };
300 let feed = feed_of(&snapshot, 0);
301 let read: Vec<(&str, bool, bool)> = feed
302 .entries()
303 .iter()
304 .map(|entry| (entry.id.as_str(), entry.read, entry.counts_for_bell))
305 .collect();
306 assert_eq!(
307 read,
308 [("old", true, false), ("new", false, true), ("flagged", true, false)]
309 );
310 assert_eq!(feed_of(&snapshot, 300).bell_count(), 0);
311 }
312}