BlueGit

ict rusty-teams

Files

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

server.rs

server.rs 11.4 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.clone(),
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_recap_activity_gets_the_app_title_and_meeting_time() {
181 let mut recap = item("msGraph", "recapIsReadyForFollowedMeetingsV2");
182 recap
183 .template_parameters
184 .insert("subject".into(), "Following: Sprint {Demo} ".into());
185 recap.event_start_ms = Some(1793865600000);
186 recap.event_end_ms = Some(1793869200000);
187 let entry = entry_of(&recap);
188 assert_eq!(entry.title.as_deref(), Some("Recap ready: Following: Sprint {Demo}"));
189 let (start, end) = entry.event_range.unwrap();
190 assert_eq!((end - start).num_minutes(), 60);
191 assert_eq!(entry_of(&item("msGraph", "recapIsReadyV2")).title, None);
192 assert_eq!(entry_of(&item("msGraph", "somethingElse")).title, None);
193 }
194
195 #[test]
196 fn maps_the_teams_activity_types() {
197 let cases = [
198 ("mention", "person", Kind::Mention),
199 ("mentionInChat", "everyone", Kind::Mention),
200 ("replyToReply", "", Kind::Reply),
201 ("reactionInChat", "heart", Kind::Reaction),
202 ("call", "missedCall", Kind::MissedCall),
203 ("call", "missedMeetingNudge", Kind::Call),
204 ("follow", "channelNewMessage", Kind::Posted),
205 ("teamMembershipChange", "addedToTeam", Kind::Team),
206 ("msGraph", "recapIsReadyV2", Kind::App),
207 ("unknownType", "", Kind::Other),
208 ];
209 for (activity_type, subtype, kind) in cases {
210 assert_eq!(kind_of(&item(activity_type, subtype)), kind, "{activity_type}");
211 }
212 }
213
214 #[test]
215 fn a_channel_reply_jumps_to_its_root_and_a_chat_to_the_message() {
216 let channel = entry_of(&item("replyToReply", ""));
217 assert_eq!(channel.message_id, "1791367000001");
218 assert_eq!(channel.reply_id.as_deref(), Some("1791367000002"));
219 let chat = entry_of(&ActivityItem {
220 thread_type: Some("chat".into()),
221 ..item("mentionInChat", "person")
222 });
223 assert_eq!(chat.message_id, "1791367000002");
224 assert_eq!(chat.reply_id, None);
225 assert_eq!(entry_of(&item("call", "missedCall")).message_id, "");
226 assert_eq!(chat.actors[0].user_id.as_deref(), Some("user-1"));
227 }
228
229 #[test]
230 fn a_recap_opens_the_meeting_chat_it_names() {
231 let recap = entry_of(&ActivityItem {
232 source_thread_id: String::new(),
233 meeting_thread_id: Some("19:meeting_Zm9v@thread.v2".into()),
234 tap_url: Some("https://teams.microsoft.com/l/entity/x".into()),
235 ..item("msGraph", "recapIsReadyV2")
236 });
237 assert_eq!(recap.conversation_id, "19:meeting_Zm9v@thread.v2");
238 assert_eq!(recap.message_id, "");
239 assert_eq!(recap.link.as_deref(), Some("https://teams.microsoft.com/l/entity/x"));
240 }
241
242 #[test]
243 fn previews_follow_the_teams_template() {
244 let file = entry_of(&ActivityItem {
245 preview_template: "sentAFile".into(),
246 ..item("mention", "person")
247 });
248 assert_eq!(file.preview, "Sent a file");
249 let recap = entry_of(&ActivityItem {
250 preview: "You're following this meeting".into(),
251 preview_template: "previewUnavailable".into(),
252 ..item("msGraph", "recapIsReadyV2")
253 });
254 assert_eq!(recap.preview, "You're following this meeting");
255 let unavailable = entry_of(&ActivityItem {
256 preview: String::new(),
257 preview_template: "previewUnavailable".into(),
258 ..item("mention", "person")
259 });
260 assert_eq!(unavailable.preview, "Preview Unavailable");
261 assert_eq!(entry_of(&item("mention", "person")).preview, "Ship it");
262 assert_eq!(entry_of(&item("reactionInChat", "like")).glyphs.len(), 1);
263 }
264
265 #[test]
266 fn read_and_bell_come_from_the_snapshot_and_the_local_seen_mark() {
267 let snapshot = ActivitySnapshot {
268 items: vec![
269 ActivityItem {
270 message_id: "old".into(),
271 timestamp_ms: 100,
272 version_ms: 100,
273 ..item("mention", "person")
274 },
275 ActivityItem {
276 message_id: "new".into(),
277 timestamp_ms: 300,
278 version_ms: 300,
279 ..item("mention", "person")
280 },
281 ActivityItem {
282 message_id: "flagged".into(),
283 timestamp_ms: 400,
284 version_ms: 400,
285 read_flag: true,
286 ..item("mention", "person")
287 },
288 ],
289 horizons: ActivityHorizons {
290 seen_ms: 50,
291 bookmark_ms: 150,
292 },
293 };
294 let feed = feed_of(&snapshot, 0);
295 let read: Vec<(&str, bool, bool)> = feed
296 .entries()
297 .iter()
298 .map(|entry| (entry.id.as_str(), entry.read, entry.counts_for_bell))
299 .collect();
300 assert_eq!(
301 read,
302 [("old", true, false), ("new", false, true), ("flagged", true, false)]
303 );
304 assert_eq!(feed_of(&snapshot, 300).bell_count(), 0);
305 }
306}