BlueGit

ict rusty-teams

Files

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

activity_feed.rs

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