| 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.get("content").and_then(Value::as_str).unwrap_or_default(); |
| 50 | let (initiator, kind) = match message.get("messagetype").and_then(Value::as_str)? { |
| 51 | MEMBER_JOINED => { |
| 52 | let detail: Value = serde_json::from_str(content).ok()?; |
| 53 | let member_ids: Vec<String> = detail["members"] |
| 54 | .as_array()? |
| 55 | .iter() |
| 56 | .filter_map(|member| member["id"].as_str().map(user_id)) |
| 57 | .collect(); |
| 58 | if member_ids.is_empty() { |
| 59 | return None; |
| 60 | } |
| 61 | let initiator = detail["initiator"].as_str().map(user_id); |
| 62 | (initiator, ThreadActivityKind::MembersJoined { member_ids }) |
| 63 | } |
| 64 | TOPIC_UPDATE => { |
| 65 | let topic = unescape(xml_value(content, "value")?.trim()); |
| 66 | let initiator = xml_value(content, "initiator").map(user_id); |
| 67 | (initiator, ThreadActivityKind::TopicUpdated { topic }) |
| 68 | } |
| 69 | _ => return None, |
| 70 | }; |
| 71 | let created_at = message |
| 72 | .get("composetime") |
| 73 | .and_then(Value::as_str) |
| 74 | .and_then(|time| DateTime::parse_from_rfc3339(time).ok())? |
| 75 | .with_timezone(&Utc); |
| 76 | Some(ThreadActivity { |
| 77 | message_id, |
| 78 | created_at, |
| 79 | initiator_id: initiator, |
| 80 | kind, |
| 81 | }) |
| 82 | } |
| 83 | |
| 84 | pub fn parse_thread_activities(body: &Value) -> Vec<ThreadActivity> { |
| 85 | body.get("messages") |
| 86 | .and_then(Value::as_array) |
| 87 | .into_iter() |
| 88 | .flatten() |
| 89 | .filter_map(parse_activity) |
| 90 | .collect() |
| 91 | } |
| 92 | |
| 93 | impl<T: MessageTransport> Messages<T> { |
| 94 | pub async fn thread_activities(&self, chat_id: &str) -> Result<Vec<ThreadActivity>> { |
| 95 | let url = format!( |
| 96 | "{}/{}/messages?view=msnp24Equivalent&pageSize={PAGE_SIZE}", |
| 97 | self.base_url, |
| 98 | encode(chat_id) |
| 99 | ); |
| 100 | let answer = self.transport.send(Request::get(url)).await?; |
| 101 | ensure_success(&answer)?; |
| 102 | Ok(parse_thread_activities(&answer.body)) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | #[cfg(test)] |
| 107 | mod tests { |
| 108 | use serde_json::json; |
| 109 | |
| 110 | use super::*; |
| 111 | |
| 112 | #[test] |
| 113 | fn meeting_invites_and_topic_updates_become_activities() { |
| 114 | let body = json!({"messages": [ |
| 115 | {"id": "3", "messagetype": "RichText/Html", "content": "hi", "composetime": "2026-11-09T16:26:16.078Z"}, |
| 116 | {"id": "2", "messagetype": "ThreadActivity/TopicUpdate", "composetime": "2026-10-30T09:26:48.2890000Z", |
| 117 | "content": "<topicupdate><eventtime>1</eventtime><initiator>8:orgid:boss</initiator><value>Tree & service</value></topicupdate>"}, |
| 118 | {"id": "1", "messagetype": "ThreadActivity/MemberJoined", "composetime": "2026-10-30T09:26:48.1380000Z", |
| 119 | "content": "{\"initiator\":\"8:orgid:boss\",\"members\":[{\"id\":\"8:orgid:ann\",\"friendlyname\":\"\"},{\"id\":\"8:orgid:bob\"}]}"}, |
| 120 | ]}); |
| 121 | let activities = parse_thread_activities(&body); |
| 122 | assert_eq!(activities.len(), 2); |
| 123 | assert_eq!(activities[0].message_id, "2"); |
| 124 | assert_eq!(activities[0].initiator_id.as_deref(), Some("boss")); |
| 125 | assert_eq!(activities[0].kind, ThreadActivityKind::TopicUpdated { topic: "Tree & service".into() }); |
| 126 | assert_eq!( |
| 127 | activities[1].kind, |
| 128 | ThreadActivityKind::MembersJoined { member_ids: vec!["ann".into(), "bob".into()] } |
| 129 | ); |
| 130 | assert_eq!(activities[1].created_at.timestamp_millis(), 1_793_352_408_138); |
| 131 | } |
| 132 | } |