| 1 | use chrono::{DateTime, Utc}; |
| 2 | use serde_json::Value; |
| 3 | use session::Request; |
| 4 | |
| 5 | use crate::error::Result; |
| 6 | use crate::messages::{MessageTransport, Messages, encode, ensure_success}; |
| 7 | |
| 8 | const MEMBER_JOINED: &str = "ThreadActivity/MemberJoined"; |
| 9 | const TOPIC_UPDATE: &str = "ThreadActivity/TopicUpdate"; |
| 10 | const ORGID_PREFIX: &str = "8:orgid:"; |
| 11 | const PAGE_SIZE: usize = 200; |
| 12 | |
| 13 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 14 | pub enum ThreadActivityKind { |
| 15 | MembersJoined { member_ids: Vec<String> }, |
| 16 | TopicUpdated { topic: String }, |
| 17 | } |
| 18 | |
| 19 | /// System events of a meeting chat that Graph leaves out of `chats/{id}/messages`. |
| 20 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 21 | pub struct ThreadActivity { |
| 22 | pub message_id: String, |
| 23 | pub created_at: DateTime<Utc>, |
| 24 | pub initiator_id: Option<String>, |
| 25 | pub kind: ThreadActivityKind, |
| 26 | } |
| 27 | |
| 28 | fn user_id(mri: &str) -> String { |
| 29 | mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned() |
| 30 | } |
| 31 | |
| 32 | fn xml_value<'a>(content: &'a str, tag: &str) -> Option<&'a str> { |
| 33 | let open = format!("<{tag}>"); |
| 34 | let start = content.find(&open)? + open.len(); |
| 35 | let end = start + content[start..].find(&format!("</{tag}>"))?; |
| 36 | Some(&content[start..end]) |
| 37 | } |
| 38 | |
| 39 | fn unescape(text: &str) -> String { |
| 40 | text.replace("<", "<") |
| 41 | .replace(">", ">") |
| 42 | .replace(""", "\"") |
| 43 | .replace("'", "'") |
| 44 | .replace("&", "&") |
| 45 | } |
| 46 | |
| 47 | fn parse_activity(message: &Value) -> Option<ThreadActivity> { |
| 48 | let message_id = crate::json_id::id_text(message.get("id")?)?; |
| 49 | let content = message |
| 50 | .get("content") |
| 51 | .and_then(Value::as_str) |
| 52 | .unwrap_or_default(); |
| 53 | let (initiator, kind) = match message.get("messagetype").and_then(Value::as_str)? { |
| 54 | MEMBER_JOINED => { |
| 55 | let detail: Value = serde_json::from_str(content).ok()?; |
| 56 | let member_ids: Vec<String> = detail["members"] |
| 57 | .as_array()? |
| 58 | .iter() |
| 59 | .filter_map(|member| member["id"].as_str().map(user_id)) |
| 60 | .collect(); |
| 61 | if member_ids.is_empty() { |
| 62 | return None; |
| 63 | } |
| 64 | let initiator = detail["initiator"].as_str().map(user_id); |
| 65 | (initiator, ThreadActivityKind::MembersJoined { member_ids }) |
| 66 | } |
| 67 | TOPIC_UPDATE => { |
| 68 | let topic = unescape(xml_value(content, "value")?.trim()); |
| 69 | let initiator = xml_value(content, "initiator").map(user_id); |
| 70 | (initiator, ThreadActivityKind::TopicUpdated { topic }) |
| 71 | } |
| 72 | _ => return None, |
| 73 | }; |
| 74 | let created_at = message |
| 75 | .get("composetime") |
| 76 | .and_then(Value::as_str) |
| 77 | .and_then(|time| DateTime::parse_from_rfc3339(time).ok())? |
| 78 | .with_timezone(&Utc); |
| 79 | Some(ThreadActivity { |
| 80 | message_id, |
| 81 | created_at, |
| 82 | initiator_id: initiator, |
| 83 | kind, |
| 84 | }) |
| 85 | } |
| 86 | |
| 87 | pub fn parse_thread_activities(body: &Value) -> Vec<ThreadActivity> { |
| 88 | body.get("messages") |
| 89 | .and_then(Value::as_array) |
| 90 | .into_iter() |
| 91 | .flatten() |
| 92 | .filter_map(parse_activity) |
| 93 | .collect() |
| 94 | } |
| 95 | |
| 96 | impl<T: MessageTransport> Messages<T> { |
| 97 | pub async fn thread_activities(&self, chat_id: &str) -> Result<Vec<ThreadActivity>> { |
| 98 | let url = format!( |
| 99 | "{}/{}/messages?view=msnp24Equivalent&pageSize={PAGE_SIZE}", |
| 100 | self.base_url, |
| 101 | encode(chat_id) |
| 102 | ); |
| 103 | let answer = self.transport.send(Request::get(url)).await?; |
| 104 | ensure_success(&answer)?; |
| 105 | Ok(parse_thread_activities(&answer.body)) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | #[cfg(test)] |
| 110 | mod tests { |
| 111 | use serde_json::json; |
| 112 | |
| 113 | use super::*; |
| 114 | |
| 115 | #[test] |
| 116 | fn meeting_invites_and_topic_updates_become_activities() { |
| 117 | let body = json!({"messages": [ |
| 118 | {"id": "3", "messagetype": "RichText/Html", "content": "hi", "composetime": "2026-11-09T16:26:16.078Z"}, |
| 119 | {"id": "2", "messagetype": "ThreadActivity/TopicUpdate", "composetime": "2026-10-30T09:26:48.2890000Z", |
| 120 | "content": "<topicupdate><eventtime>1</eventtime><initiator>8:orgid:boss</initiator><value>Tree & service</value></topicupdate>"}, |
| 121 | {"id": "1", "messagetype": "ThreadActivity/MemberJoined", "composetime": "2026-10-30T09:26:48.1380000Z", |
| 122 | "content": "{\"initiator\":\"8:orgid:boss\",\"members\":[{\"id\":\"8:orgid:ann\",\"friendlyname\":\"\"},{\"id\":\"8:orgid:bob\"}]}"}, |
| 123 | ]}); |
| 124 | let activities = parse_thread_activities(&body); |
| 125 | assert_eq!(activities.len(), 2); |
| 126 | assert_eq!(activities[0].message_id, "2"); |
| 127 | assert_eq!(activities[0].initiator_id.as_deref(), Some("boss")); |
| 128 | assert_eq!( |
| 129 | activities[0].kind, |
| 130 | ThreadActivityKind::TopicUpdated { |
| 131 | topic: "Tree & service".into() |
| 132 | } |
| 133 | ); |
| 134 | assert_eq!( |
| 135 | activities[1].kind, |
| 136 | ThreadActivityKind::MembersJoined { |
| 137 | member_ids: vec!["ann".into(), "bob".into()] |
| 138 | } |
| 139 | ); |
| 140 | assert_eq!( |
| 141 | activities[1].created_at.timestamp_millis(), |
| 142 | 1_793_352_408_138 |
| 143 | ); |
| 144 | } |
| 145 | } |