| 1 | use chrono::{DateTime, Utc}; |
| 2 | use serde_json::{Value, json}; |
| 3 | |
| 4 | const STARTED_TYPE: &str = "#microsoft.graph.callStartedEventMessageDetail"; |
| 5 | const ENDED_TYPE: &str = "#microsoft.graph.callEndedEventMessageDetail"; |
| 6 | const RECORDING_TYPE: &str = "#microsoft.graph.callRecordingEventMessageDetail"; |
| 7 | const TRANSCRIPT_TYPE: &str = "#microsoft.graph.callTranscriptEventMessageDetail"; |
| 8 | const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail"; |
| 9 | const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail"; |
| 10 | const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail"; |
| 11 | const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail"; |
| 12 | const MEETING_CHAT_PREFIX: &str = "19:meeting_"; |
| 13 | const ALL_HISTORY: &str = "0001-01-01T00:00:00Z"; |
| 14 | |
| 15 | /// The Graph `eventDetail` of a chat service system message; `None` for events Graph does not list. |
| 16 | pub fn event_detail( |
| 17 | message_type: &str, |
| 18 | content: &str, |
| 19 | conversation_id: &str, |
| 20 | sender_id: Option<&str>, |
| 21 | ) -> Option<Value> { |
| 22 | match message_type { |
| 23 | "Event/Call" => call_detail(content, conversation_id, sender_id), |
| 24 | "RichText/Media_CallRecording" => recording_detail(content), |
| 25 | "RichText/Media_CallTranscript" => transcript_detail(content), |
| 26 | "ThreadActivity/AddMember" => added_detail(content), |
| 27 | "ThreadActivity/DeleteMember" => Some(json!({ |
| 28 | "@odata.type": MEMBERS_DELETED_TYPE, |
| 29 | "members": targets(content), |
| 30 | "initiator": user(tag_text(content, "initiator")), |
| 31 | })), |
| 32 | "ThreadActivity/MemberLeft" => left_detail(content), |
| 33 | "ThreadActivity/TopicUpdate" if !conversation_id.starts_with(MEETING_CHAT_PREFIX) => { |
| 34 | Some(json!({ |
| 35 | "@odata.type": CHAT_RENAMED_TYPE, |
| 36 | "chatDisplayName": tag_text(content, "value").map(|topic| unescape(topic.trim())), |
| 37 | "initiator": user(tag_text(content, "initiator")), |
| 38 | })) |
| 39 | } |
| 40 | _ => None, |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | /// The recording and call events of a chat service message page, as a Graph `{"value": [...]}` page. |
| 45 | pub fn graph_event_page(conversation_id: &str, chatsvc_page: &Value) -> Value { |
| 46 | let events: Vec<Value> = chatsvc_page["messages"] |
| 47 | .as_array() |
| 48 | .into_iter() |
| 49 | .flatten() |
| 50 | .filter_map(|message| { |
| 51 | let message_type = message["messagetype"].as_str()?; |
| 52 | if !is_event(message_type) { |
| 53 | return None; |
| 54 | } |
| 55 | let sender_id = message["from"] |
| 56 | .as_str() |
| 57 | .map(|from| user_id(from.rsplit('/').next().unwrap_or(from))); |
| 58 | let detail = event_detail( |
| 59 | message_type, |
| 60 | message["content"].as_str().unwrap_or_default(), |
| 61 | conversation_id, |
| 62 | sender_id, |
| 63 | )?; |
| 64 | let created = ["originalarrivaltime", "composetime"] |
| 65 | .iter() |
| 66 | .find_map(|key| message[*key].as_str()) |
| 67 | .and_then(|stamp| DateTime::parse_from_rfc3339(stamp).ok()) |
| 68 | .map(|stamp| stamp.with_timezone(&Utc).to_rfc3339()); |
| 69 | Some(json!({ |
| 70 | "id": crate::json_id::id_text(&message["id"])?, |
| 71 | "createdDateTime": created, |
| 72 | "eventDetail": detail, |
| 73 | })) |
| 74 | }) |
| 75 | .collect(); |
| 76 | json!({"value": events}) |
| 77 | } |
| 78 | |
| 79 | pub fn is_event(message_type: &str) -> bool { |
| 80 | message_type == "Event/Call" |
| 81 | || message_type.starts_with("ThreadActivity/") |
| 82 | || message_type == "RichText/Media_CallRecording" |
| 83 | || message_type == "RichText/Media_CallTranscript" |
| 84 | } |
| 85 | |
| 86 | fn call_detail(content: &str, conversation_id: &str, sender_id: Option<&str>) -> Option<Value> { |
| 87 | let kind = if has_flag(content, "ended") { |
| 88 | ENDED_TYPE |
| 89 | } else { |
| 90 | STARTED_TYPE |
| 91 | }; |
| 92 | let parts: Vec<&str> = content.split("<part ").skip(1).collect(); |
| 93 | let participants: Vec<Value> = parts |
| 94 | .iter() |
| 95 | .filter_map(|part| { |
| 96 | let identity = attribute(&format!(" {part}"), "identity")?.to_owned(); |
| 97 | let name = tag_text(part, "displayName") |
| 98 | .map(|name| unescape(name.trim())) |
| 99 | .filter(|name| !name.is_empty()); |
| 100 | Some(json!({"participant": {"user": {"id": user_id(&identity), "displayName": name}}})) |
| 101 | }) |
| 102 | .collect(); |
| 103 | let longest = parts |
| 104 | .iter() |
| 105 | .filter_map(|part| tag_text(part, "duration")?.trim().parse::<f64>().ok()) |
| 106 | .fold(None, |longest: Option<f64>, seconds| { |
| 107 | Some(longest.map_or(seconds, |known| known.max(seconds))) |
| 108 | }); |
| 109 | let event_type = tag_text(content, "callEventType").unwrap_or_default(); |
| 110 | let meeting = event_type.to_ascii_lowercase().contains("meeting") |
| 111 | || conversation_id.starts_with(MEETING_CHAT_PREFIX) |
| 112 | || tag_text(content, "meetingType").is_some_and(|kind| !kind.trim().is_empty()); |
| 113 | Some(json!({ |
| 114 | "@odata.type": kind, |
| 115 | "callId": tag_text(content, "callId")?.trim(), |
| 116 | "callDuration": longest.map(|seconds| format!("PT{}S", seconds.round() as u64)), |
| 117 | "callEventType": if meeting { "meeting" } else { "call" }, |
| 118 | "callParticipants": participants, |
| 119 | "initiator": user(sender_id), |
| 120 | })) |
| 121 | } |
| 122 | |
| 123 | fn recording_detail(content: &str) -> Option<Value> { |
| 124 | let status = element_attribute(content, "RecordingStatus", "status")?; |
| 125 | let status = match status.to_ascii_lowercase().as_str() { |
| 126 | "started" | "initial" => "initial", |
| 127 | "chunkfinished" => "chunkFinished", |
| 128 | "success" => "success", |
| 129 | _ => return None, |
| 130 | }; |
| 131 | let name = element_attribute(content, "OriginalName", "v") |
| 132 | .map(unescape) |
| 133 | .or_else(|| tag_text(content, "Title").map(unescape)); |
| 134 | Some(json!({ |
| 135 | "@odata.type": RECORDING_TYPE, |
| 136 | "callId": identifier(content, "callId")?, |
| 137 | "callRecordingStatus": status, |
| 138 | "callRecordingDisplayName": name, |
| 139 | "callRecordingUrl": element_attribute(content, "a", "href").map(unescape), |
| 140 | "callRecordingDuration": element_attribute(content, "RecordingContent", "duration").and_then(iso_duration), |
| 141 | "meetingOrganizer": user(element_attribute(content, "MeetingOrganizerId", "value")), |
| 142 | "initiator": user(element_attribute(content, "RecordingInitiatorId", "value")), |
| 143 | })) |
| 144 | } |
| 145 | |
| 146 | fn transcript_detail(content: &str) -> Option<Value> { |
| 147 | let call_id = |
| 148 | identifier(content, "callId").or_else(|| tag_text(content, "callId").map(str::trim))?; |
| 149 | Some(json!({ |
| 150 | "@odata.type": TRANSCRIPT_TYPE, |
| 151 | "callId": call_id, |
| 152 | "meetingOrganizer": user(element_attribute(content, "MeetingOrganizerId", "value")), |
| 153 | })) |
| 154 | } |
| 155 | |
| 156 | fn added_detail(content: &str) -> Option<Value> { |
| 157 | let members = targets(content); |
| 158 | if members.as_array().is_none_or(Vec::is_empty) { |
| 159 | return None; |
| 160 | } |
| 161 | let visible_from = tag_text(content, "sharehistorytime") |
| 162 | .and_then(|time| time.trim().parse::<i64>().ok()) |
| 163 | .and_then(|millis| match millis { |
| 164 | 0 => Some(ALL_HISTORY.to_owned()), |
| 165 | millis if millis > 0 => { |
| 166 | DateTime::<Utc>::from_timestamp_millis(millis).map(|time| time.to_rfc3339()) |
| 167 | } |
| 168 | _ => None, |
| 169 | }); |
| 170 | Some(json!({ |
| 171 | "@odata.type": MEMBERS_ADDED_TYPE, |
| 172 | "members": members, |
| 173 | "initiator": user(tag_text(content, "initiator")), |
| 174 | "visibleHistoryStartDateTime": visible_from, |
| 175 | })) |
| 176 | } |
| 177 | |
| 178 | fn left_detail(content: &str) -> Option<Value> { |
| 179 | let detail: Value = serde_json::from_str(content).ok()?; |
| 180 | let members: Vec<Value> = detail["members"] |
| 181 | .as_array()? |
| 182 | .iter() |
| 183 | .filter_map(|member| { |
| 184 | let id = member["id"].as_str()?; |
| 185 | let name = member["friendlyname"] |
| 186 | .as_str() |
| 187 | .filter(|name| !name.is_empty()); |
| 188 | Some(json!({"id": user_id(id), "displayName": name})) |
| 189 | }) |
| 190 | .collect(); |
| 191 | (!members.is_empty()).then(|| { |
| 192 | json!({ |
| 193 | "@odata.type": MEMBERS_LEFT_TYPE, |
| 194 | "members": members, |
| 195 | "initiator": user(detail["initiator"].as_str()), |
| 196 | }) |
| 197 | }) |
| 198 | } |
| 199 | |
| 200 | fn targets(content: &str) -> Value { |
| 201 | Value::Array( |
| 202 | tag_texts(content, "target") |
| 203 | .into_iter() |
| 204 | .map(str::trim) |
| 205 | .filter(|target| target.starts_with("8:")) |
| 206 | .map(|target| json!({"id": user_id(target), "displayName": null})) |
| 207 | .collect(), |
| 208 | ) |
| 209 | } |
| 210 | |
| 211 | fn user(mri: Option<&str>) -> Value { |
| 212 | match mri.map(str::trim).filter(|mri| !mri.is_empty()) { |
| 213 | Some(mri) => json!({"user": {"id": user_id(mri), "displayName": null}}), |
| 214 | None => Value::Null, |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | /// Graph names people and bots by the id after the last `:` of the MRI (`8:orgid:`, `28:`, `8:teamsvisitor:`). |
| 219 | pub fn user_id(mri: &str) -> &str { |
| 220 | mri.rsplit(':').next().unwrap_or(mri) |
| 221 | } |
| 222 | |
| 223 | fn has_flag(content: &str, name: &str) -> bool { |
| 224 | content.contains(&format!("<{name}/>")) || content.contains(&format!("<{name} />")) |
| 225 | } |
| 226 | |
| 227 | fn iso_duration(text: &str) -> Option<String> { |
| 228 | let mut parts = text.split(':').rev(); |
| 229 | let seconds: f64 = parts.next()?.parse().ok()?; |
| 230 | let minutes: u64 = parts.next().map_or(Some(0), |part| part.parse().ok())?; |
| 231 | let hours: u64 = parts.next().map_or(Some(0), |part| part.parse().ok())?; |
| 232 | Some(format!("PT{hours}H{minutes}M{}S", seconds.round() as u64)) |
| 233 | } |
| 234 | |
| 235 | pub fn tag_text<'a>(content: &'a str, tag: &str) -> Option<&'a str> { |
| 236 | tag_texts(content, tag).into_iter().next() |
| 237 | } |
| 238 | |
| 239 | fn tag_texts<'a>(content: &'a str, tag: &str) -> Vec<&'a str> { |
| 240 | let open = format!("<{tag}>"); |
| 241 | let close = format!("</{tag}>"); |
| 242 | let mut found = Vec::new(); |
| 243 | let mut rest = content; |
| 244 | while let Some(start) = rest.find(&open) { |
| 245 | let after = &rest[start + open.len()..]; |
| 246 | let Some(end) = after.find(&close) else { |
| 247 | break; |
| 248 | }; |
| 249 | found.push(&after[..end]); |
| 250 | rest = &after[end + close.len()..]; |
| 251 | } |
| 252 | found |
| 253 | } |
| 254 | |
| 255 | fn element_attribute<'a>(content: &'a str, element: &str, name: &str) -> Option<&'a str> { |
| 256 | let open = format!("<{element} "); |
| 257 | let start = content.find(&open)?; |
| 258 | let tag_end = content[start..].find('>')? + start; |
| 259 | attribute(&content[start..tag_end], name) |
| 260 | } |
| 261 | |
| 262 | fn identifier<'a>(content: &'a str, kind: &str) -> Option<&'a str> { |
| 263 | let marker = format!("type=\"{kind}\""); |
| 264 | let mut rest = content; |
| 265 | while let Some(start) = rest.find("<Id ") { |
| 266 | let tag_end = rest[start..].find('>')? + start; |
| 267 | let tag = &rest[start..tag_end]; |
| 268 | if tag.contains(&marker) { |
| 269 | return attribute(tag, "value").filter(|value| !value.is_empty()); |
| 270 | } |
| 271 | rest = &rest[tag_end..]; |
| 272 | } |
| 273 | None |
| 274 | } |
| 275 | |
| 276 | pub fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> { |
| 277 | let mut search = 0; |
| 278 | while let Some(found) = tag[search..].find(name) { |
| 279 | let start = search + found; |
| 280 | let before = tag[..start].chars().last(); |
| 281 | let after = &tag[start + name.len()..]; |
| 282 | if before.is_some_and(char::is_whitespace) |
| 283 | && let Some(value) = after.strip_prefix("=\"") |
| 284 | { |
| 285 | return value.find('"').map(|end| &value[..end]); |
| 286 | } |
| 287 | search = start + name.len(); |
| 288 | } |
| 289 | None |
| 290 | } |
| 291 | |
| 292 | pub fn unescape(text: &str) -> String { |
| 293 | text.replace("<", "<") |
| 294 | .replace(">", ">") |
| 295 | .replace(""", "\"") |
| 296 | .replace("'", "'") |
| 297 | .replace("'", "'") |
| 298 | .replace(" ", " ") |
| 299 | .replace("&", "&") |
| 300 | } |
| 301 | |
| 302 | #[cfg(test)] |
| 303 | mod tests { |
| 304 | use serde_json::json; |
| 305 | |
| 306 | use super::*; |
| 307 | |
| 308 | #[test] |
| 309 | fn a_recording_page_reads_like_a_graph_page() { |
| 310 | let content = r#"<URIObject type="Video.2/CallRecording.1"><RecordingStatus status="Success" code="200"></RecordingStatus><a href="https://contoso.sharepoint.com/:v:/rec">Play</a><OriginalName v="Daily.mp4" /><Identifiers><Id type="callId" value="call-1" /></Identifiers></URIObject>"#; |
| 311 | let page = json!({"messages": [ |
| 312 | {"id": "1751975663649", "messagetype": "RichText/Media_CallRecording", "content": content, "originalarrivaltime": "2026-11-04T10:32:30.000Z", "from": "https://x/contacts/8:orgid:ann"}, |
| 313 | {"id": "1751975663650", "messagetype": "RichText/Html", "content": "<p>hi</p>"}, |
| 314 | ]}); |
| 315 | let graph = graph_event_page("19:a@thread.v2", &page); |
| 316 | let events = graph["value"].as_array().unwrap(); |
| 317 | assert_eq!(events.len(), 1); |
| 318 | assert_eq!(events[0]["id"], "1751975663649"); |
| 319 | assert_eq!( |
| 320 | events[0]["eventDetail"]["callRecordingUrl"], |
| 321 | "https://contoso.sharepoint.com/:v:/rec" |
| 322 | ); |
| 323 | assert_eq!(events[0]["createdDateTime"], "2026-11-04T10:32:30+00:00"); |
| 324 | } |
| 325 | |
| 326 | #[test] |
| 327 | fn pins_and_file_events_are_left_out() { |
| 328 | assert!( |
| 329 | event_detail( |
| 330 | "ThreadActivity/PinnedItemsUpdate", |
| 331 | "{}", |
| 332 | "19:a@thread.v2", |
| 333 | None |
| 334 | ) |
| 335 | .is_none() |
| 336 | ); |
| 337 | assert_eq!(json!(null), user(Some(" "))); |
| 338 | } |
| 339 | } |