| 1 | use chrono::DateTime; |
| 2 | use serde_json::Value; |
| 3 | use session::{Request, Session}; |
| 4 | |
| 5 | use crate::error::{Error, Result}; |
| 6 | use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success}; |
| 7 | use crate::pins::DEFAULT_REGION; |
| 8 | |
| 9 | const PAGE_SIZE: usize = 200; |
| 10 | const MAX_PAGES: usize = 3; |
| 11 | const MENTION_TYPES: [&str; 2] = ["mention", "mentionInCommunity"]; |
| 12 | |
| 13 | /// Who an @mention addressed, as Teams splits them in `ChannelActivitiesPublisher`. |
| 14 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 15 | pub enum MentionKind { |
| 16 | Personal, |
| 17 | Channel, |
| 18 | Team, |
| 19 | } |
| 20 | |
| 21 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 22 | pub struct MentionActivity { |
| 23 | pub activity_id: String, |
| 24 | pub kind: MentionKind, |
| 25 | pub source_thread_id: String, |
| 26 | pub source_message_id: Option<String>, |
| 27 | pub timestamp_ms: i64, |
| 28 | pub is_read: bool, |
| 29 | } |
| 30 | |
| 31 | pub struct ActivityFeed<T: MessageTransport = SessionMessageTransport> { |
| 32 | transport: T, |
| 33 | stream_url: String, |
| 34 | } |
| 35 | |
| 36 | impl ActivityFeed<SessionMessageTransport> { |
| 37 | pub fn new(session: &Session) -> Self { |
| 38 | ActivityFeed::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | impl<T: MessageTransport> ActivityFeed<T> { |
| 43 | pub fn with_transport(transport: T, region: &str) -> Self { |
| 44 | ActivityFeed { |
| 45 | transport, |
| 46 | stream_url: format!( |
| 47 | "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/streams/notifications/messages" |
| 48 | ), |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | pub fn first_page_url(&self) -> String { |
| 53 | format!( |
| 54 | "{}?view=msnp24Equivalent|supportsMessageProperties&pageSize={PAGE_SIZE}&startTime=1", |
| 55 | self.stream_url |
| 56 | ) |
| 57 | } |
| 58 | |
| 59 | /// Newest activity pages, mentions only. |
| 60 | pub async fn mentions(&self) -> Result<Vec<MentionActivity>> { |
| 61 | let mut mentions = Vec::new(); |
| 62 | let mut next_url = Some(self.first_page_url()); |
| 63 | for _ in 0..MAX_PAGES { |
| 64 | let Some(url) = next_url.take() else { |
| 65 | break; |
| 66 | }; |
| 67 | let answer = self.transport.send(Request::get(&url)).await?; |
| 68 | ensure_success(&answer)?; |
| 69 | mentions.extend(parse_mention_page(&answer.body)?); |
| 70 | next_url = answer |
| 71 | .body |
| 72 | .pointer("/_metadata/backwardLink") |
| 73 | .and_then(Value::as_str) |
| 74 | .filter(|link| !link.is_empty() && *link != url) |
| 75 | .map(str::to_owned); |
| 76 | } |
| 77 | Ok(mentions) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | pub fn parse_mention_page(body: &Value) -> Result<Vec<MentionActivity>> { |
| 82 | let messages = body |
| 83 | .get("messages") |
| 84 | .and_then(Value::as_array) |
| 85 | .ok_or_else(|| Error::UnexpectedAnswer("activity messages missing".into()))?; |
| 86 | Ok(messages.iter().filter_map(mention_activity).collect()) |
| 87 | } |
| 88 | |
| 89 | fn object_property(properties: &Value, key: &str) -> Option<Value> { |
| 90 | match properties.get(key)? { |
| 91 | Value::String(text) => serde_json::from_str::<Value>(text) |
| 92 | .ok() |
| 93 | .filter(Value::is_object), |
| 94 | other if other.is_object() => Some(other.clone()), |
| 95 | _ => None, |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | fn text_of(value: &Value) -> Option<String> { |
| 100 | match value { |
| 101 | Value::String(text) if !text.is_empty() => Some(text.clone()), |
| 102 | Value::Number(number) => Some(number.to_string()), |
| 103 | _ => None, |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | fn flag(value: Option<&Value>) -> bool { |
| 108 | match value { |
| 109 | Some(Value::Bool(flag)) => *flag, |
| 110 | Some(Value::String(text)) => text.eq_ignore_ascii_case("true"), |
| 111 | _ => false, |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | fn timestamp_ms(value: &Value) -> Option<i64> { |
| 116 | match value { |
| 117 | Value::Number(number) => number.as_i64(), |
| 118 | Value::String(text) => text.parse::<i64>().ok().or_else(|| { |
| 119 | DateTime::parse_from_rfc3339(text) |
| 120 | .ok() |
| 121 | .map(|time| time.timestamp_millis()) |
| 122 | }), |
| 123 | _ => None, |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | fn mention_kind(subtype: &str) -> Option<MentionKind> { |
| 128 | match subtype.to_ascii_lowercase().as_str() { |
| 129 | "person" | "tag" => Some(MentionKind::Personal), |
| 130 | "channel" => Some(MentionKind::Channel), |
| 131 | "team" => Some(MentionKind::Team), |
| 132 | _ => None, |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | fn mention_activity(message: &Value) -> Option<MentionActivity> { |
| 137 | let properties = message.get("properties")?; |
| 138 | let activity = object_property(properties, "activity")?; |
| 139 | let activity_type = activity.get("activityType")?.as_str()?; |
| 140 | if !MENTION_TYPES.contains(&activity_type) { |
| 141 | return None; |
| 142 | } |
| 143 | let kind = mention_kind(activity.get("activitySubtype")?.as_str()?)?; |
| 144 | Some(MentionActivity { |
| 145 | activity_id: activity |
| 146 | .get("activityId") |
| 147 | .and_then(text_of) |
| 148 | .or_else(|| message.get("id").and_then(text_of))?, |
| 149 | kind, |
| 150 | source_thread_id: activity.get("sourceThreadId")?.as_str()?.to_owned(), |
| 151 | source_message_id: activity.get("sourceMessageId").and_then(text_of), |
| 152 | timestamp_ms: activity |
| 153 | .get("activityTimestamp") |
| 154 | .and_then(timestamp_ms) |
| 155 | .unwrap_or(0), |
| 156 | is_read: flag(properties.get("isread")), |
| 157 | }) |
| 158 | } |
| 159 | |
| 160 | #[cfg(test)] |
| 161 | mod tests { |
| 162 | use std::collections::VecDeque; |
| 163 | use std::sync::Mutex; |
| 164 | |
| 165 | use serde_json::json; |
| 166 | use session::ApiResponse; |
| 167 | |
| 168 | use super::*; |
| 169 | |
| 170 | struct Canned { |
| 171 | answers: Mutex<VecDeque<(u16, Value)>>, |
| 172 | requests: Mutex<Vec<Request>>, |
| 173 | } |
| 174 | |
| 175 | impl MessageTransport for &Canned { |
| 176 | async fn send(&self, request: Request) -> Result<ApiResponse> { |
| 177 | self.requests.lock().unwrap().push(request); |
| 178 | let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted"); |
| 179 | Ok(ApiResponse { |
| 180 | status, |
| 181 | body, |
| 182 | retry_after: None, |
| 183 | }) |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | fn activity_message(id: &str, activity: Value, isread: Option<&str>) -> Value { |
| 188 | let mut properties = json!({"activity": activity}); |
| 189 | if let Some(isread) = isread { |
| 190 | properties["isread"] = json!(isread); |
| 191 | } |
| 192 | json!({"id": id, "messagetype": "Text", "properties": properties}) |
| 193 | } |
| 194 | |
| 195 | #[test] |
| 196 | fn keeps_mentions_and_maps_the_subtypes() { |
| 197 | let body = json!({"messages": [ |
| 198 | activity_message("m1", json!({ |
| 199 | "activityId": 101, "activityType": "mention", "activitySubtype": "person", |
| 200 | "sourceThreadId": "19:a@thread.tacv2", "sourceMessageId": 1791368000000_i64, |
| 201 | "activityTimestamp": "2026-10-17T08:00:00.000Z" |
| 202 | }), Some("true")), |
| 203 | activity_message("m2", json!({ |
| 204 | "activityType": "mention", "activitySubtype": "tag", |
| 205 | "sourceThreadId": "19:a@thread.tacv2", "activityTimestamp": 1791368100000_i64 |
| 206 | }), None), |
| 207 | activity_message("m3", json!({ |
| 208 | "activityId": "103", "activityType": "mention", "activitySubtype": "channel", |
| 209 | "sourceThreadId": "19:b@thread.tacv2" |
| 210 | }), Some("false")), |
| 211 | activity_message("m4", json!({ |
| 212 | "activityId": "104", "activityType": "mentionInCommunity", "activitySubtype": "team", |
| 213 | "sourceThreadId": "19:b@thread.tacv2" |
| 214 | }), None), |
| 215 | activity_message("m5", json!({ |
| 216 | "activityId": "105", "activityType": "reply", "activitySubtype": "person", |
| 217 | "sourceThreadId": "19:b@thread.tacv2" |
| 218 | }), None), |
| 219 | activity_message("m6", json!({ |
| 220 | "activityId": "106", "activityType": "mention", "activitySubtype": "everyone", |
| 221 | "sourceThreadId": "19:b@thread.tacv2" |
| 222 | }), None), |
| 223 | {"id": "m7", "properties": {}} |
| 224 | ]}); |
| 225 | let mentions = parse_mention_page(&body).unwrap(); |
| 226 | let kinds: Vec<(&str, MentionKind)> = mentions |
| 227 | .iter() |
| 228 | .map(|mention| (mention.activity_id.as_str(), mention.kind)) |
| 229 | .collect(); |
| 230 | assert_eq!( |
| 231 | kinds, |
| 232 | [ |
| 233 | ("101", MentionKind::Personal), |
| 234 | ("m2", MentionKind::Personal), |
| 235 | ("103", MentionKind::Channel), |
| 236 | ("104", MentionKind::Team), |
| 237 | ] |
| 238 | ); |
| 239 | assert!(mentions[0].is_read); |
| 240 | assert!(!mentions[1].is_read); |
| 241 | assert_eq!( |
| 242 | mentions[0].source_message_id.as_deref(), |
| 243 | Some("1791368000000") |
| 244 | ); |
| 245 | assert_eq!(mentions[0].timestamp_ms, 1792224000000); |
| 246 | assert_eq!(mentions[1].timestamp_ms, 1791368100000); |
| 247 | assert_eq!(mentions[2].timestamp_ms, 0); |
| 248 | } |
| 249 | |
| 250 | #[test] |
| 251 | fn reads_the_activity_when_it_is_a_json_string() { |
| 252 | let activity = json!({ |
| 253 | "activityId": "7", "activityType": "mention", "activitySubtype": "person", |
| 254 | "sourceThreadId": "19:a@thread.tacv2" |
| 255 | }); |
| 256 | let body = json!({"messages": [ |
| 257 | activity_message("m1", Value::String(activity.to_string()), Some("True")) |
| 258 | ]}); |
| 259 | let mentions = parse_mention_page(&body).unwrap(); |
| 260 | assert_eq!(mentions.len(), 1); |
| 261 | assert!(mentions[0].is_read); |
| 262 | } |
| 263 | |
| 264 | #[test] |
| 265 | fn an_answer_without_messages_is_unexpected() { |
| 266 | assert!(parse_mention_page(&json!({})).is_err()); |
| 267 | } |
| 268 | |
| 269 | #[tokio::test] |
| 270 | async fn pages_backward_through_the_stream() { |
| 271 | let transport = Canned { |
| 272 | answers: Mutex::new( |
| 273 | vec![ |
| 274 | ( |
| 275 | 200, |
| 276 | json!({"messages": [], "_metadata": {"backwardLink": "https://next"}}), |
| 277 | ), |
| 278 | (200, json!({"messages": [], "_metadata": {"backwardLink": ""}})), |
| 279 | ] |
| 280 | .into(), |
| 281 | ), |
| 282 | requests: Mutex::new(Vec::new()), |
| 283 | }; |
| 284 | let feed = ActivityFeed::with_transport(&transport, "emea"); |
| 285 | assert!(feed.mentions().await.unwrap().is_empty()); |
| 286 | let requests = transport.requests.lock().unwrap(); |
| 287 | assert_eq!( |
| 288 | requests[0].url, |
| 289 | "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/streams/notifications/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=200&startTime=1" |
| 290 | ); |
| 291 | assert_eq!(requests[1].url, "https://next"); |
| 292 | assert_eq!(requests.len(), 2); |
| 293 | } |
| 294 | } |