BlueGit

ict rusty-teams

Files

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

server.rs

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