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