BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / activity_feed.rs

activity_feed.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
activity_feed.rs 21.1 KiB Download Raw
1use std::collections::BTreeMap;
2
3use chrono::DateTime;
4use serde::{Deserialize, Serialize};
5use serde_json::{Value, json};
6use session::{Method, Request, Session};
7
8use crate::error::{Error, Result};
9use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
10use crate::pins::DEFAULT_REGION;
11
12pub const ACTIVITY_FEED_ID: &str = "48:notifications";
13const PAGE_SIZE: usize = 200;
14const MAX_PAGES: usize = 3;
15const READ_PROPERTY: &str = "isread";
16const SEEN_PROPERTY: &str = "consumptionhorizon";
17const BOOKMARK_PROPERTY: &str = "consumptionHorizonBookmark";
18const MEETING_THREAD_PREFIX: &str = "19:meeting_";
19const MEETING_THREAD_SUFFIX: &str = "@thread.v2";
20
21#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
22pub struct ActivityItem {
23 pub message_id: String,
24 pub activity_id: String,
25 pub activity_type: String,
26 pub activity_subtype: String,
27 pub source_thread_id: String,
28 pub source_message_id: Option<String>,
29 pub source_reply_chain_id: Option<String>,
30 pub source_user_id: Option<String>,
31 pub source_user_name: String,
32 pub source_app_name: Option<String>,
33 pub preview: String,
34 pub preview_template: String,
35 pub thread_topic: Option<String>,
36 pub thread_type: Option<String>,
37 pub count: u32,
38 pub timestamp_ms: i64,
39 pub version_ms: i64,
40 pub read_flag: bool,
41 pub tap_url: Option<String>,
42 pub meeting_thread_id: Option<String>,
43 #[serde(default)]
44 pub template_parameters: BTreeMap<String, String>,
45 pub event_start_ms: Option<i64>,
46 pub event_end_ms: Option<i64>,
47}
48
49/// `seen_ms`: the bell horizon (`consumptionhorizon`), `bookmark_ms`: Mark all as read (`consumptionHorizonBookmark`).
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
51pub struct ActivityHorizons {
52 pub seen_ms: i64,
53 pub bookmark_ms: i64,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
57pub struct ActivitySnapshot {
58 pub items: Vec<ActivityItem>,
59 pub horizons: ActivityHorizons,
60}
61
62impl ActivitySnapshot {
63 /// Teams `isActivityRead` (module 804106): the item flag, or the Mark all as read bookmark at or after its version.
64 pub fn is_read(&self, item: &ActivityItem) -> bool {
65 item.read_flag || self.horizons.bookmark_ms >= item.version_ms
66 }
67
68 /// Teams `getUnreadMetadataInfo`: unread and newer than the bell horizon.
69 pub fn counts_for_bell(&self, item: &ActivityItem) -> bool {
70 !self.is_read(item) && item.timestamp_ms > self.horizons.seen_ms
71 }
72
73 pub fn mark_read(&mut self, message_id: &str) -> bool {
74 let Some(item) = self
75 .items
76 .iter_mut()
77 .find(|item| item.message_id == message_id && !item.read_flag)
78 else {
79 return false;
80 };
81 item.read_flag = true;
82 true
83 }
84
85 pub fn mark_all_read(&mut self, now_ms: i64) {
86 self.horizons.bookmark_ms = self.horizons.bookmark_ms.max(now_ms);
87 }
88}
89
90pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> {
91 transport: T,
92 conversation_url: String,
93}
94
95impl ActivityFeed<SessionMessageTransport> {
96 pub fn new(session: &Session) -> Self {
97 ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
98 }
99}
100
101impl<T: MessageTransport> ActivityFeed<T> {
102 pub fn with_transport(transport: T, region: &str) -> Self {
103 ActivityFeed {
104 transport,
105 conversation_url: format!(
106 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations/{}",
107 encode(ACTIVITY_FEED_ID)
108 ),
109 }
110 }
111
112 pub fn first_page_url(&self) -> String {
113 format!(
114 "{}/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1",
115 self.conversation_url
116 )
117 }
118
119 pub async fn snapshot(&self) -> Result<ActivitySnapshot> {
120 let answer = self
121 .transport
122 .send(Request::get(&self.conversation_url))
123 .await?;
124 ensure_success(&answer)?;
125 let horizons = parse_horizons(&answer.body);
126 let mut items = Vec::new();
127 let mut next_url = Some(self.first_page_url());
128 for _ in 0..MAX_PAGES {
129 let Some(url) = next_url.take() else {
130 break;
131 };
132 let answer = self.transport.send(Request::get(&url)).await?;
133 ensure_success(&answer)?;
134 items.extend(parse_page(&answer.body)?);
135 next_url = answer
136 .body
137 .pointer("/_metadata/backwardLink")
138 .and_then(Value::as_str)
139 .filter(|link| !link.is_empty() && *link != url)
140 .map(str::to_owned);
141 }
142 items.sort_by_key(|item| std::cmp::Reverse(item.timestamp_ms));
143 Ok(ActivitySnapshot { items, horizons })
144 }
145
146 /// Teams `markReadStatus`: the `isread` property on the activity message.
147 pub async fn mark_read(&self, message_id: &str) -> Result<()> {
148 let url = format!(
149 "{}/messages/{}/properties?name={READ_PROPERTY}",
150 self.conversation_url,
151 encode(message_id)
152 );
153 let body = json!({ READ_PROPERTY: "true" });
154 let answer = self
155 .transport
156 .send(Request::with_body(Method::Put, url, body))
157 .await?;
158 ensure_success(&answer)
159 }
160
161 /// Teams `setConsumptionHorizonBookmark`: everything up to now counts as read.
162 pub async fn mark_all_read(&self, now_ms: i64) -> Result<()> {
163 let url = format!(
164 "{}/properties?name={BOOKMARK_PROPERTY}",
165 self.conversation_url
166 );
167 let body = json!({ BOOKMARK_PROPERTY: format!("0;{now_ms};0") });
168 let answer = self
169 .transport
170 .send(Request::with_body(Method::Put, url, body))
171 .await?;
172 ensure_success(&answer)
173 }
174}
175
176pub fn parse_horizons(conversation: &Value) -> ActivityHorizons {
177 let properties = &conversation["properties"];
178 let seen = horizon_parts(properties[SEEN_PROPERTY].as_str());
179 let bookmark = horizon_parts(properties[BOOKMARK_PROPERTY].as_str());
180 ActivityHorizons {
181 seen_ms: seen.map_or(0, |(arrival, _)| arrival),
182 bookmark_ms: bookmark.map_or(
183 0,
184 |(arrival, timestamp)| {
185 if arrival == 0 { timestamp } else { arrival }
186 },
187 ),
188 }
189}
190
191fn horizon_parts(text: Option<&str>) -> Option<(i64, i64)> {
192 let mut parts = text?.split(';');
193 let arrival = parts.next()?.trim().parse().ok()?;
194 let timestamp = parts.next()?.trim().parse().ok()?;
195 Some((arrival, timestamp))
196}
197
198pub fn parse_page(body: &Value) -> Result<Vec<ActivityItem>> {
199 let messages = body
200 .get("messages")
201 .and_then(Value::as_array)
202 .ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?;
203 Ok(messages.iter().filter_map(activity_item).collect())
204}
205
206fn activity_item(message: &Value) -> Option<ActivityItem> {
207 let properties = message.get("properties")?;
208 if properties
209 .get("deletetime")
210 .is_some_and(|value| !value.is_null())
211 {
212 return None;
213 }
214 let activity = object_property(properties, "activity")?;
215 let text = |key: &str| activity.get(key).and_then(text_of);
216 let context = activity.get("activityContext");
217 let location = context
218 .and_then(|context| object_property(context, "location"))
219 .and_then(|location| {
220 location
221 .get("Custom")
222 .and_then(Value::as_str)
223 .map(str::to_owned)
224 })
225 .unwrap_or_default();
226 let message_id = message.get("id").and_then(text_of)?;
227 let version_ms = message
228 .get("version")
229 .and_then(timestamp_ms)
230 .unwrap_or_default();
231 let timestamp_ms = activity
232 .get("activityTimestamp")
233 .and_then(timestamp_ms)
234 .or_else(|| message.get("originalarrivaltime").and_then(timestamp_ms))
235 .unwrap_or(version_ms);
236 Some(ActivityItem {
237 activity_id: text("activityId").unwrap_or_else(|| message_id.clone()),
238 message_id,
239 activity_type: text("activityType")?,
240 activity_subtype: text("activitySubtype").unwrap_or_default(),
241 source_thread_id: text("sourceThreadId").unwrap_or_default(),
242 source_message_id: text("sourceMessageId"),
243 source_reply_chain_id: text("sourceReplyChainId"),
244 source_user_id: text("sourceUserId"),
245 source_user_name: text("sourceUserImDisplayName").unwrap_or_default(),
246 source_app_name: text("sourceAppDisplayName"),
247 preview: text("messagePreview").unwrap_or_default(),
248 preview_template: text("messagePreviewTemplateOption").unwrap_or_default(),
249 thread_topic: text("sourceThreadTopic"),
250 thread_type: text("sourceThreadType"),
251 count: text("count")
252 .and_then(|count| count.parse().ok())
253 .unwrap_or(1),
254 timestamp_ms,
255 version_ms,
256 read_flag: flag(properties.get(READ_PROPERTY)),
257 tap_url: text("customTapAction"),
258 meeting_thread_id: meeting_thread_in(&activity.to_string()),
259 template_parameters: context
260 .and_then(|context| object_property(context, "templateParameters"))
261 .and_then(|parameters| parameters.as_object().cloned())
262 .map(|parameters| {
263 parameters
264 .iter()
265 .filter_map(|(key, value)| Some((key.clone(), text_of(value)?)))
266 .collect()
267 })
268 .unwrap_or_default(),
269 event_start_ms: tag_time(&location, "StartDateTime"),
270 event_end_ms: tag_time(&location, "EndDateTime"),
271 })
272}
273
274fn tag_time(text: &str, tag: &str) -> Option<i64> {
275 let open = format!("<{tag}>");
276 let start = text.find(&open)? + open.len();
277 let end = start + text[start..].find(&format!("</{tag}>"))?;
278 timestamp_ms(&Value::String(text[start..end].to_owned()))
279}
280
281fn meeting_thread_in(text: &str) -> Option<String> {
282 let decoded = text
283 .replace("%3a", ":")
284 .replace("%3A", ":")
285 .replace("%40", "@");
286 let start = decoded.find(MEETING_THREAD_PREFIX)?;
287 let rest = &decoded[start..];
288 let end = rest.find(MEETING_THREAD_SUFFIX)? + MEETING_THREAD_SUFFIX.len();
289 let thread_id = &rest[..end];
290 thread_id
291 .chars()
292 .all(|character| character.is_ascii_alphanumeric() || "_:@.-=".contains(character))
293 .then(|| thread_id.to_owned())
294}
295
296fn object_property(properties: &Value, key: &str) -> Option<Value> {
297 match properties.get(key)? {
298 Value::String(text) => serde_json::from_str::<Value>(text)
299 .ok()
300 .filter(Value::is_object),
301 other if other.is_object() => Some(other.clone()),
302 _ => None,
303 }
304}
305
306fn text_of(value: &Value) -> Option<String> {
307 crate::json_id::id_text(value)
308}
309
310fn flag(value: Option<&Value>) -> bool {
311 match value {
312 Some(Value::Bool(flag)) => *flag,
313 Some(Value::String(text)) => text.eq_ignore_ascii_case("true"),
314 _ => false,
315 }
316}
317
318fn timestamp_ms(value: &Value) -> Option<i64> {
319 match value {
320 Value::Number(number) => number.as_i64(),
321 Value::String(text) => text.parse::<i64>().ok().or_else(|| {
322 DateTime::parse_from_rfc3339(text)
323 .ok()
324 .map(|time| time.timestamp_millis())
325 }),
326 _ => None,
327 }
328}
329
330#[cfg(test)]
331mod tests {
332 use std::collections::VecDeque;
333 use std::sync::Mutex;
334
335 use session::ApiResponse;
336
337 use super::*;
338
339 const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/48%3Anotifications";
340
341 struct Canned {
342 answers: Mutex<VecDeque<(u16, Value)>>,
343 requests: Mutex<Vec<Request>>,
344 }
345
346 impl Canned {
347 fn new(answers: Vec<(u16, Value)>) -> Self {
348 Canned {
349 answers: Mutex::new(answers.into()),
350 requests: Mutex::new(Vec::new()),
351 }
352 }
353 }
354
355 impl MessageTransport for &Canned {
356 async fn send(&self, request: Request) -> Result<ApiResponse> {
357 self.requests.lock().unwrap().push(request);
358 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
359 Ok(ApiResponse {
360 status,
361 body,
362 retry_after: None,
363 })
364 }
365 }
366
367 fn message(id: &str, version: i64, activity: Value, isread: &str) -> Value {
368 json!({
369 "id": id,
370 "version": version.to_string(),
371 "originalarrivaltime": "2026-10-17T08:00:00.000Z",
372 "properties": {"activity": activity.to_string(), "isread": isread}
373 })
374 }
375
376 #[test]
377 fn maps_an_activity_message() {
378 let body = json!({"messages": [
379 message("1791368000001", 1791368000500, json!({
380 "activityId": 4711, "activityType": "reactionInChat", "activitySubtype": "heart",
381 "activityTimestamp": "1791368000000", "sourceThreadId": "19:a@thread.v2",
382 "sourceMessageId": 1791367000000.0, "sourceReplyChainId": "1791367000000",
383 "sourceUserId": "8:orgid:user-1", "sourceUserImDisplayName": "Ada Example",
384 "messagePreview": "Ship it", "messagePreviewTemplateOption": "hasText",
385 "sourceThreadTopic": "Release", "sourceThreadType": "chat", "count": "3"
386 }), "false"),
387 {"id": "2", "version": "1", "properties": {}},
388 {"id": "3", "version": "1", "properties": {"deletetime": "5", "activity": {"activityType": "mention"}}}
389 ]});
390 let items = parse_page(&body).unwrap();
391 assert_eq!(
392 items,
393 [ActivityItem {
394 message_id: "1791368000001".into(),
395 activity_id: "4711".into(),
396 activity_type: "reactionInChat".into(),
397 activity_subtype: "heart".into(),
398 source_thread_id: "19:a@thread.v2".into(),
399 source_message_id: Some("1791367000000".into()),
400 source_reply_chain_id: Some("1791367000000".into()),
401 source_user_id: Some("8:orgid:user-1".into()),
402 source_user_name: "Ada Example".into(),
403 source_app_name: None,
404 preview: "Ship it".into(),
405 preview_template: "hasText".into(),
406 thread_topic: Some("Release".into()),
407 thread_type: Some("chat".into()),
408 count: 3,
409 timestamp_ms: 1791368000000,
410 version_ms: 1791368000500,
411 read_flag: false,
412 tap_url: None,
413 meeting_thread_id: None,
414 ..ActivityItem::default()
415 }]
416 );
417 }
418
419 #[test]
420 fn an_app_activity_keeps_its_tap_link_and_the_meeting_it_names() {
421 let body = json!({"messages": [
422 message("1", 1, json!({
423 "activityType": "msGraph", "activitySubtype": "recapIsReadyV2",
424 "customTapAction": "https://teams.microsoft.com/l/entity/x?context=%7B%22threadId%22%3A%2219%3Ameeting_Zm9v%40thread.v2%22%7D",
425 }), "false"),
426 message("2", 1, json!({
427 "activityType": "msGraph", "activitySubtype": "recapIsReadyV2",
428 "activityContext": {"templateParameters": "{\"threadId\":\"19:meeting_YmFy@thread.v2\"}"},
429 }), "false"),
430 ]});
431 let items = parse_page(&body).unwrap();
432 assert!(
433 items[0]
434 .tap_url
435 .as_deref()
436 .unwrap()
437 .starts_with("https://teams.microsoft.com/l/entity/")
438 );
439 assert_eq!(
440 items[0].meeting_thread_id.as_deref(),
441 Some("19:meeting_Zm9v@thread.v2")
442 );
443 assert_eq!(items[1].tap_url, None);
444 assert_eq!(
445 items[1].meeting_thread_id.as_deref(),
446 Some("19:meeting_YmFy@thread.v2")
447 );
448 }
449
450 #[test]
451 fn an_app_activity_keeps_its_template_parameters_and_time_range() {
452 let body = json!({"messages": [message("1", 1, json!({
453 "activityType": "msGraph", "activitySubtype": "recapIsReadyForFollowedMeetingsV2",
454 "activityContext": {
455 "location": "{\"Custom\":\"<DateTimeRange><StartDateTime>2026-11-05T08:00:00.0000000Z</StartDateTime><EndDateTime>2026-11-05T09:00:00.0000000Z</EndDateTime></DateTimeRange>\"}",
456 "templateParameters": "{\"subject\":\"Following: Sprint Demo \"}",
457 },
458 }), "false")]});
459 let item = &parse_page(&body).unwrap()[0];
460 assert_eq!(
461 item.template_parameters.get("subject").map(String::as_str),
462 Some("Following: Sprint Demo ")
463 );
464 assert_eq!(item.event_start_ms, Some(1793865600000));
465 assert_eq!(item.event_end_ms, Some(1793869200000));
466 }
467
468 #[test]
469 fn reads_both_horizons_of_the_feed_conversation() {
470 let conversation = json!({"properties": {
471 "consumptionhorizon": "1791368000000;1791368005000;1791368000000",
472 "consumptionHorizonBookmark": "0;1791000000000;0"
473 }});
474 assert_eq!(
475 parse_horizons(&conversation),
476 ActivityHorizons {
477 seen_ms: 1791368000000,
478 bookmark_ms: 1791000000000
479 }
480 );
481 assert_eq!(parse_horizons(&json!({})), ActivityHorizons::default());
482 }
483
484 #[test]
485 fn read_and_bell_follow_the_teams_rules() {
486 let item = |version_ms: i64, read_flag: bool| ActivityItem {
487 version_ms,
488 timestamp_ms: version_ms,
489 read_flag,
490 ..ActivityItem::default()
491 };
492 let snapshot = ActivitySnapshot {
493 items: Vec::new(),
494 horizons: ActivityHorizons {
495 seen_ms: 300,
496 bookmark_ms: 200,
497 },
498 };
499 assert!(snapshot.is_read(&item(150, false)));
500 assert!(snapshot.is_read(&item(250, true)));
501 assert!(!snapshot.is_read(&item(250, false)));
502 assert!(!snapshot.counts_for_bell(&item(250, false)));
503 assert!(snapshot.counts_for_bell(&item(350, false)));
504 assert!(!snapshot.counts_for_bell(&item(350, true)));
505 }
506
507 #[tokio::test]
508 async fn snapshot_reads_the_horizons_then_pages_backward() {
509 let transport = Canned::new(vec![
510 (200, json!({"properties": {"consumptionhorizon": "5;6;7"}})),
511 (
512 200,
513 json!({"messages": [message("a", 10, json!({"activityType": "mention", "activityTimestamp": "10"}), "true")],
514 "_metadata": {"backwardLink": "https://next"}}),
515 ),
516 (
517 200,
518 json!({"messages": [message("b", 20, json!({"activityType": "call", "activityTimestamp": "20"}), "false")],
519 "_metadata": {"backwardLink": ""}}),
520 ),
521 ]);
522 let feed = ActivityFeed::with_transport(&transport, "emea");
523 let snapshot = feed.snapshot().await.unwrap();
524 let ids: Vec<&str> = snapshot
525 .items
526 .iter()
527 .map(|item| item.message_id.as_str())
528 .collect();
529 assert_eq!(ids, ["b", "a"]);
530 assert_eq!(snapshot.horizons.seen_ms, 5);
531 let requests = transport.requests.lock().unwrap();
532 assert_eq!(requests[0].url, BASE);
533 assert_eq!(
534 requests[1].url,
535 format!(
536 "{BASE}/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1"
537 )
538 );
539 assert_eq!(requests[2].url, "https://next");
540 assert_eq!(requests.len(), 3);
541 }
542
543 #[tokio::test]
544 async fn writes_like_teams() {
545 let transport = Canned::new(vec![(200, json!({})), (200, json!({}))]);
546 let feed = ActivityFeed::with_transport(&transport, "emea");
547 feed.mark_read("1791368000001").await.unwrap();
548 feed.mark_all_read(1791368009000).await.unwrap();
549 let requests = transport.requests.lock().unwrap();
550 assert_eq!(requests[0].method, Method::Put);
551 assert_eq!(
552 requests[0].url,
553 format!("{BASE}/messages/1791368000001/properties?name=isread")
554 );
555 assert_eq!(requests[0].body, Some(json!({"isread": "true"})));
556 assert_eq!(
557 requests[1].url,
558 format!("{BASE}/properties?name=consumptionHorizonBookmark")
559 );
560 assert_eq!(
561 requests[1].body,
562 Some(json!({"consumptionHorizonBookmark": "0;1791368009000;0"}))
563 );
564 }
565
566 #[test]
567 fn local_marks_follow_the_writes() {
568 let mut snapshot = ActivitySnapshot {
569 items: vec![ActivityItem {
570 message_id: "a".into(),
571 version_ms: 50,
572 ..ActivityItem::default()
573 }],
574 horizons: ActivityHorizons::default(),
575 };
576 assert!(!snapshot.is_read(&snapshot.items[0]));
577 assert!(snapshot.mark_read("a"));
578 assert!(!snapshot.mark_read("a"));
579 assert!(snapshot.is_read(&snapshot.items[0]));
580 snapshot.items[0].read_flag = false;
581 snapshot.mark_all_read(60);
582 assert!(snapshot.is_read(&snapshot.items[0]));
583 }
584}