| 1 | use base64::Engine; |
| 2 | use base64::engine::general_purpose::STANDARD; |
| 3 | use chrono::{DateTime, Utc}; |
| 4 | use graph::Message; |
| 5 | use serde_json::{Value, json}; |
| 6 | |
| 7 | use super::markup::graph_body; |
| 8 | use crate::forwarded::FORWARDED_CONTENT_TYPE; |
| 9 | use chatsvc::graph_events::{event_detail, is_event, user_id}; |
| 10 | |
| 11 | const BOT_PREFIX: &str = "28:"; |
| 12 | const FORWARD_CONTEXT: &str = "originalMessageContext"; |
| 13 | const ANNOTATION_KEYS: [&str; 3] = ["follow", "star", "acks"]; |
| 14 | const SWIFT_MARKER: &str = "<Swift b64=\""; |
| 15 | |
| 16 | /// A chat service message as Graph would serve it, so the record mapping stays the same for both sources. |
| 17 | pub fn graph_message(conversation_id: &str, native: &Value) -> Option<Message> { |
| 18 | serde_json::from_value(graph_message_json(conversation_id, native)?).ok() |
| 19 | } |
| 20 | |
| 21 | pub(crate) fn graph_message_json(conversation_id: &str, native: &Value) -> Option<Value> { |
| 22 | let message_type = text(native, &["messagetype", "messageType"])?; |
| 23 | let id = chatsvc::id_text(native.get("id")?)?; |
| 24 | let properties = &native["properties"]; |
| 25 | let created = time( |
| 26 | native, |
| 27 | &[ |
| 28 | "originalarrivaltime", |
| 29 | "originalArrivalTime", |
| 30 | "composetime", |
| 31 | "composeTime", |
| 32 | ], |
| 33 | )?; |
| 34 | let content = text(native, &["content"]).unwrap_or_default(); |
| 35 | let sender = sender(native); |
| 36 | let sender_user_id = sender |
| 37 | .pointer("/user/id") |
| 38 | .and_then(Value::as_str) |
| 39 | .map(str::to_owned); |
| 40 | let mut message = json!({ |
| 41 | "id": id, |
| 42 | "createdDateTime": created, |
| 43 | "lastModifiedDateTime": millis(&native["version"]).map(|time| time.to_rfc3339()).unwrap_or_else(|| created.clone()), |
| 44 | "lastEditedDateTime": millis(&properties["edittime"]).map(|time| time.to_rfc3339()), |
| 45 | "deletedDateTime": millis(&properties["deletetime"]).map(|time| time.to_rfc3339()), |
| 46 | "from": sender, |
| 47 | "importance": text(properties, &["importance"]), |
| 48 | "subject": text(properties, &["subject"]), |
| 49 | "reactions": reactions(native), |
| 50 | }); |
| 51 | if is_event(message_type) { |
| 52 | message["messageType"] = json!("systemEventMessage"); |
| 53 | message["eventDetail"] = event_detail( |
| 54 | message_type, |
| 55 | content, |
| 56 | conversation_id, |
| 57 | sender_user_id.as_deref(), |
| 58 | )?; |
| 59 | message["from"] = Value::Null; |
| 60 | message["body"] = json!({"contentType": "html", "content": ""}); |
| 61 | return Some(message); |
| 62 | } |
| 63 | if !is_user_message(message_type) { |
| 64 | return None; |
| 65 | } |
| 66 | message["messageType"] = json!("message"); |
| 67 | let forwards = forward_contexts(properties); |
| 68 | let forward_ids: Vec<String> = forwards.iter().map(|context| context.id.clone()).collect(); |
| 69 | let body = graph_body(&content.replace("\r\n", "\n"), &forward_ids); |
| 70 | let mut attachments = file_attachments(properties); |
| 71 | attachments.extend(card_attachments(properties)); |
| 72 | if message_type == "RichText/Media_Card" { |
| 73 | attachments.extend(swift_attachments(content)); |
| 74 | } |
| 75 | attachments.extend(body.quotes.iter().map(|quote| { |
| 76 | json!({ |
| 77 | "id": quote.message_id, |
| 78 | "contentType": "messageReference", |
| 79 | "content": json!({ |
| 80 | "messageId": quote.message_id, |
| 81 | "messagePreview": quote.preview, |
| 82 | "messageSender": quote.sender_mri.as_deref().map(|mri| json!({"user": {"id": user_id(mri), "displayName": quote.sender_name}})), |
| 83 | }).to_string(), |
| 84 | }) |
| 85 | })); |
| 86 | attachments.extend( |
| 87 | forwards |
| 88 | .iter() |
| 89 | .zip(&body.forwards) |
| 90 | .map(|(context, inner)| context.attachment(inner)), |
| 91 | ); |
| 92 | let mut html = if message_type == "RichText/Media_Card" { |
| 93 | String::new() |
| 94 | } else { |
| 95 | body.html |
| 96 | }; |
| 97 | for marker in &attachments { |
| 98 | let Some(attachment_id) = marker["id"].as_str() else { |
| 99 | continue; |
| 100 | }; |
| 101 | let tag = format!("<attachment id=\"{attachment_id}\"></attachment>"); |
| 102 | if !html.contains(&tag) { |
| 103 | html.push_str(&tag); |
| 104 | } |
| 105 | } |
| 106 | message["body"] = json!({ |
| 107 | "contentType": if message_type == "Text" { "text" } else { "html" }, |
| 108 | "content": html, |
| 109 | }); |
| 110 | message["mentions"] = mentions(properties, &body.mention_texts); |
| 111 | message["attachments"] = Value::Array(attachments); |
| 112 | Some(message) |
| 113 | } |
| 114 | |
| 115 | fn is_user_message(message_type: &str) -> bool { |
| 116 | message_type == "Text" || message_type.starts_with("RichText") |
| 117 | } |
| 118 | |
| 119 | fn sender(native: &Value) -> Value { |
| 120 | let Some(mri) = text(native, &["from"]).and_then(|from| from.rsplit('/').next()) else { |
| 121 | return Value::Null; |
| 122 | }; |
| 123 | let name = text(native, &["imdisplayname", "imDisplayName"]) |
| 124 | .map(str::trim) |
| 125 | .filter(|name| !name.is_empty()); |
| 126 | if let Some(bot_id) = mri.strip_prefix(BOT_PREFIX) { |
| 127 | return json!({"application": {"id": bot_id, "displayName": name}}); |
| 128 | } |
| 129 | if mri.starts_with("8:") { |
| 130 | return json!({"user": {"id": user_id(mri), "displayName": name}}); |
| 131 | } |
| 132 | Value::Null |
| 133 | } |
| 134 | |
| 135 | fn reactions(native: &Value) -> Value { |
| 136 | let emotions = chatsvc::parse_message_emotions(&json!({"messages": [native]})); |
| 137 | Value::Array( |
| 138 | emotions |
| 139 | .into_iter() |
| 140 | .flat_map(|message| message.reactions) |
| 141 | .filter(|reaction| !ANNOTATION_KEYS.contains(&reaction.key.as_str())) |
| 142 | .map(|reaction| { |
| 143 | json!({ |
| 144 | "reactionType": chatsvc::reaction_glyph_for_key(&reaction.key).unwrap_or(reaction.key), |
| 145 | "createdDateTime": reaction.time_ms.and_then(DateTime::<Utc>::from_timestamp_millis).map(|time| time.to_rfc3339()), |
| 146 | "user": {"user": {"id": reaction.user_id, "displayName": null}}, |
| 147 | }) |
| 148 | }) |
| 149 | .collect(), |
| 150 | ) |
| 151 | } |
| 152 | |
| 153 | fn mentions(properties: &Value, texts: &std::collections::HashMap<String, String>) -> Value { |
| 154 | Value::Array( |
| 155 | json_list(&properties["mentions"]) |
| 156 | .iter() |
| 157 | .filter_map(|mention| { |
| 158 | let item_id = chatsvc::id_text(mention.get("itemid")?)?; |
| 159 | let mri = mention["mri"].as_str().unwrap_or_default(); |
| 160 | let name = mention["displayName"].as_str().map(str::to_owned); |
| 161 | let identity = json!({"id": user_id(mri), "displayName": name}); |
| 162 | let mentioned = match mention["mentionType"].as_str().unwrap_or("person") { |
| 163 | _ if mri.starts_with("19:") => json!({"conversation": {"id": mri, "displayName": name, "conversationIdentityType": "chat"}}), |
| 164 | "tag" => json!({"tag": identity}), |
| 165 | "channel" | "team" => json!({"conversation": identity}), |
| 166 | _ if mri.starts_with(BOT_PREFIX) => json!({"application": {"id": &mri[BOT_PREFIX.len()..], "displayName": name}}), |
| 167 | _ => json!({"user": identity}), |
| 168 | }; |
| 169 | Some(json!({ |
| 170 | "id": item_id.parse::<i64>().ok()?, |
| 171 | "mentionText": texts.get(&item_id).cloned().or(name), |
| 172 | "mentioned": mentioned, |
| 173 | })) |
| 174 | }) |
| 175 | .collect(), |
| 176 | ) |
| 177 | } |
| 178 | |
| 179 | fn file_attachments(properties: &Value) -> Vec<Value> { |
| 180 | json_list(&properties["files"]) |
| 181 | .iter() |
| 182 | .filter_map(|file| { |
| 183 | let id = text(file, &["itemid", "id"])?; |
| 184 | let url = file |
| 185 | .pointer("/fileInfo/fileUrl") |
| 186 | .and_then(Value::as_str) |
| 187 | .or_else(|| text(file, &["objectUrl"]))?; |
| 188 | Some(json!({ |
| 189 | "id": id, |
| 190 | "contentType": "reference", |
| 191 | "contentUrl": url, |
| 192 | "name": text(file, &["fileName", "title"]), |
| 193 | })) |
| 194 | }) |
| 195 | .collect() |
| 196 | } |
| 197 | |
| 198 | fn card_attachments(properties: &Value) -> Vec<Value> { |
| 199 | json_list(&properties["cards"]) |
| 200 | .iter() |
| 201 | .filter_map(|card| { |
| 202 | let content = match &card["content"] { |
| 203 | Value::String(text) => text.clone(), |
| 204 | Value::Null => return None, |
| 205 | other => other.to_string(), |
| 206 | }; |
| 207 | Some(json!({ |
| 208 | "id": text(card, &["cardClientId"]), |
| 209 | "contentType": text(card, &["contentType"]).unwrap_or("application/vnd.microsoft.card.adaptive"), |
| 210 | "content": content, |
| 211 | "teamsAppId": text(card, &["appId"]), |
| 212 | })) |
| 213 | }) |
| 214 | .collect() |
| 215 | } |
| 216 | |
| 217 | fn swift_attachments(content: &str) -> Vec<Value> { |
| 218 | let Some(start) = content |
| 219 | .find(SWIFT_MARKER) |
| 220 | .map(|start| start + SWIFT_MARKER.len()) |
| 221 | else { |
| 222 | return Vec::new(); |
| 223 | }; |
| 224 | let Some(encoded) = content[start..].split('"').next() else { |
| 225 | return Vec::new(); |
| 226 | }; |
| 227 | let Some(swift) = STANDARD |
| 228 | .decode(encoded) |
| 229 | .ok() |
| 230 | .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok()) |
| 231 | else { |
| 232 | return Vec::new(); |
| 233 | }; |
| 234 | swift["attachments"] |
| 235 | .as_array() |
| 236 | .into_iter() |
| 237 | .flatten() |
| 238 | .enumerate() |
| 239 | .filter_map(|(index, attachment)| { |
| 240 | let content = match &attachment["content"] { |
| 241 | Value::String(text) => text.clone(), |
| 242 | Value::Null => return None, |
| 243 | other => other.to_string(), |
| 244 | }; |
| 245 | Some(json!({ |
| 246 | "id": format!("swift-{index}"), |
| 247 | "contentType": text(attachment, &["contentType"]), |
| 248 | "content": content, |
| 249 | })) |
| 250 | }) |
| 251 | .collect() |
| 252 | } |
| 253 | |
| 254 | struct ForwardContext { |
| 255 | id: String, |
| 256 | conversation_id: Option<String>, |
| 257 | sender_id: Option<String>, |
| 258 | sent_at: Option<String>, |
| 259 | } |
| 260 | |
| 261 | impl ForwardContext { |
| 262 | fn attachment(&self, inner_html: &str) -> Value { |
| 263 | json!({ |
| 264 | "id": self.id, |
| 265 | "contentType": FORWARDED_CONTENT_TYPE, |
| 266 | "content": json!({ |
| 267 | "originalMessageId": self.id, |
| 268 | "originalMessageContent": inner_html, |
| 269 | "originalConversationId": self.conversation_id, |
| 270 | "originalSentDateTime": self.sent_at, |
| 271 | "originalMessageSender": self.sender_id.as_ref().map(|id| json!({"user": {"id": id, "displayName": null}})), |
| 272 | }).to_string(), |
| 273 | }) |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | fn forward_contexts(properties: &Value) -> Vec<ForwardContext> { |
| 278 | (0..) |
| 279 | .map(|index| match index { |
| 280 | 0 => FORWARD_CONTEXT.to_owned(), |
| 281 | index => format!("{FORWARD_CONTEXT}{index}"), |
| 282 | }) |
| 283 | .map_while(|key| { |
| 284 | properties |
| 285 | .get(&key) |
| 286 | .filter(|context| context.is_object()) |
| 287 | .cloned() |
| 288 | }) |
| 289 | .filter_map(|context| { |
| 290 | Some(ForwardContext { |
| 291 | id: chatsvc::id_text(context.get("messageId")?)?, |
| 292 | conversation_id: text(&context, &["originalThreadId"]).map(str::to_owned), |
| 293 | sender_id: text(&context, &["originalSender"]).map(|mri| user_id(mri).to_owned()), |
| 294 | sent_at: text(&context, &["originalSentTime"]).map(str::to_owned), |
| 295 | }) |
| 296 | }) |
| 297 | .collect() |
| 298 | } |
| 299 | |
| 300 | /// Chat service properties carry lists either as JSON text or as arrays. |
| 301 | fn json_list(value: &Value) -> Vec<Value> { |
| 302 | match value { |
| 303 | Value::Array(items) => items.clone(), |
| 304 | Value::String(text) => serde_json::from_str::<Value>(text) |
| 305 | .ok() |
| 306 | .and_then(|parsed| parsed.as_array().cloned()) |
| 307 | .unwrap_or_default(), |
| 308 | _ => Vec::new(), |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | fn text<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> { |
| 313 | keys.iter() |
| 314 | .find_map(|key| value.get(*key)?.as_str()) |
| 315 | .filter(|text| !text.is_empty()) |
| 316 | } |
| 317 | |
| 318 | fn time(value: &Value, keys: &[&str]) -> Option<String> { |
| 319 | let text = text(value, keys)?; |
| 320 | DateTime::parse_from_rfc3339(text) |
| 321 | .ok() |
| 322 | .map(|time| time.with_timezone(&Utc).to_rfc3339()) |
| 323 | } |
| 324 | |
| 325 | fn millis(value: &Value) -> Option<DateTime<Utc>> { |
| 326 | let millis = value.as_i64().or_else(|| value.as_str()?.parse().ok())?; |
| 327 | (millis > 0) |
| 328 | .then(|| DateTime::<Utc>::from_timestamp_millis(millis)) |
| 329 | .flatten() |
| 330 | } |
| 331 | |
| 332 | #[cfg(test)] |
| 333 | mod tests { |
| 334 | use serde_json::json; |
| 335 | |
| 336 | use super::*; |
| 337 | use crate::mapping::message_record; |
| 338 | |
| 339 | const CHAT: &str = "19:chat@thread.v2"; |
| 340 | |
| 341 | fn native(message_type: &str, content: &str, properties: Value) -> Value { |
| 342 | json!({ |
| 343 | "id": "1794474789021", |
| 344 | "messagetype": message_type, |
| 345 | "content": content, |
| 346 | "from": "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/contacts/8:orgid:ann", |
| 347 | "imdisplayname": "Ann Example", |
| 348 | "originalarrivaltime": "2026-11-12T09:13:09.0210000Z", |
| 349 | "composetime": "2026-11-12T09:13:09.0210000Z", |
| 350 | "version": "1794474789021", |
| 351 | "properties": properties, |
| 352 | }) |
| 353 | } |
| 354 | |
| 355 | #[test] |
| 356 | fn a_rich_text_message_maps_like_graph() { |
| 357 | let message = native( |
| 358 | "RichText/Html", |
| 359 | r#"<p>hi <span itemtype="http://schema.skype.com/Mention" itemscope="" itemid="0">Bo</span></p>"#, |
| 360 | json!({ |
| 361 | "mentions": r#"[{"@type":"http://schema.skype.com/Mention","itemid":0,"mri":"8:orgid:bob","mentionType":"person","displayName":"Bo Sample"}]"#, |
| 362 | "emotions": [{"key": "like", "users": [{"mri": "8:orgid:bob", "time": 1794474799021i64, "value": "1"}]}], |
| 363 | "edittime": 1794474799021i64, |
| 364 | "importance": "high", |
| 365 | }), |
| 366 | ); |
| 367 | let graph = graph_message(CHAT, &message).unwrap(); |
| 368 | assert_eq!(graph.from.as_ref().unwrap().user_id(), Some("ann")); |
| 369 | assert_eq!( |
| 370 | graph.from.as_ref().unwrap().display_name(), |
| 371 | Some("Ann Example") |
| 372 | ); |
| 373 | assert_eq!(graph.mentions[0].mention_text.as_deref(), Some("Bo")); |
| 374 | assert_eq!(graph.reactions[0].reaction_type, "👍"); |
| 375 | let record = message_record(CHAT, &graph).unwrap(); |
| 376 | assert_eq!(record.message_id, "1794474789021"); |
| 377 | assert_eq!(record.body_html, r#"<p>hi <at id="0">Bo</at></p>"#); |
| 378 | assert!(record.edited_at.is_some()); |
| 379 | assert!(record.mentions_json.contains("\"user_id\":\"bob\"")); |
| 380 | assert_eq!(record.importance, store::MessageImportance::High); |
| 381 | } |
| 382 | |
| 383 | #[test] |
| 384 | fn files_and_cards_become_attachments() { |
| 385 | let message = native( |
| 386 | "RichText/Html", |
| 387 | r#"<p>see</p><span itemid="c1" itemscope="" itemtype="http://schema.skype.com/InputExtension"><span itemprop="cardId"></span></span>"#, |
| 388 | json!({ |
| 389 | "files": r#"[{"itemid":"f1","fileName":"plan.docx","fileInfo":{"fileUrl":"https://contoso.sharepoint.com/plan.docx"}}]"#, |
| 390 | "cards": [{"cardClientId": "c1", "appId": "app", "contentType": "application/vnd.microsoft.card.adaptive", "content": {"type": "AdaptiveCard", "body": []}}], |
| 391 | }), |
| 392 | ); |
| 393 | let graph = graph_message(CHAT, &message).unwrap(); |
| 394 | let kinds: Vec<_> = graph |
| 395 | .attachments |
| 396 | .iter() |
| 397 | .map(|attachment| attachment.content_type.clone().unwrap()) |
| 398 | .collect(); |
| 399 | assert_eq!( |
| 400 | kinds, |
| 401 | vec!["reference", "application/vnd.microsoft.card.adaptive"] |
| 402 | ); |
| 403 | assert_eq!(graph.attachments[0].name.as_deref(), Some("plan.docx")); |
| 404 | let html = graph.body.unwrap().content.unwrap(); |
| 405 | assert_eq!( |
| 406 | html, |
| 407 | r#"<p>see</p><attachment id="c1"></attachment><attachment id="f1"></attachment>"# |
| 408 | ); |
| 409 | } |
| 410 | |
| 411 | #[test] |
| 412 | fn a_forward_carries_the_original() { |
| 413 | let message = native( |
| 414 | "RichText/Html", |
| 415 | r#"<blockquote itemtype="http://schema.skype.com/Forward"><p>old</p></blockquote>"#, |
| 416 | json!({"originalMessageContext": {"messageId": 1793274845211i64, "originalSender": "8:orgid:bob", "originalSentTime": "2026-10-29T11:54:05.211Z", "originalThreadId": "19:other@thread.v2"}}), |
| 417 | ); |
| 418 | let graph = graph_message(CHAT, &message).unwrap(); |
| 419 | let forward = &graph.attachments[0]; |
| 420 | assert_eq!( |
| 421 | forward.content_type.as_deref(), |
| 422 | Some(FORWARDED_CONTENT_TYPE) |
| 423 | ); |
| 424 | let content: Value = serde_json::from_str(forward.content.as_deref().unwrap()).unwrap(); |
| 425 | assert_eq!(content["originalMessageId"], "1793274845211"); |
| 426 | assert_eq!(content["originalMessageContent"], "<p>old</p>"); |
| 427 | assert_eq!(content["originalMessageSender"]["user"]["id"], "bob"); |
| 428 | } |
| 429 | |
| 430 | #[test] |
| 431 | fn a_deleted_message_is_deleted() { |
| 432 | let graph = graph_message( |
| 433 | CHAT, |
| 434 | &native("RichText/Html", "", json!({"deletetime": 1794474799021i64})), |
| 435 | ) |
| 436 | .unwrap(); |
| 437 | assert!(graph.is_deleted()); |
| 438 | } |
| 439 | |
| 440 | #[test] |
| 441 | fn a_bot_card_is_decoded() { |
| 442 | let swift = STANDARD.encode(r#"{"type":"message/card","attachments":[{"contentType":"application/vnd.microsoft.card.adaptive","content":{"type":"AdaptiveCard"}}]}"#); |
| 443 | let mut message = native( |
| 444 | "RichText/Media_Card", |
| 445 | &format!(r#"<URIObject type="SWIFT.1"><Swift b64="{swift}"/></URIObject>"#), |
| 446 | json!({}), |
| 447 | ); |
| 448 | message["from"] = json!("https://x/contacts/28:bot-1"); |
| 449 | let graph = graph_message(CHAT, &message).unwrap(); |
| 450 | assert_eq!(graph.from.as_ref().unwrap().application_id(), Some("bot-1")); |
| 451 | assert_eq!(graph.attachments.len(), 1); |
| 452 | assert!( |
| 453 | graph.attachments[0] |
| 454 | .content |
| 455 | .as_deref() |
| 456 | .unwrap() |
| 457 | .contains("AdaptiveCard") |
| 458 | ); |
| 459 | } |
| 460 | |
| 461 | #[test] |
| 462 | fn controls_are_skipped_and_events_kept() { |
| 463 | assert!(graph_message(CHAT, &native("Control/Typing", "", json!({}))).is_none()); |
| 464 | let call = native( |
| 465 | "Event/Call", |
| 466 | "<ended/><partlist count=\"0\"></partlist><callId>c</callId>", |
| 467 | json!({}), |
| 468 | ); |
| 469 | let graph = graph_message(CHAT, &call).unwrap(); |
| 470 | assert_eq!(graph.message_type.as_deref(), Some("systemEventMessage")); |
| 471 | assert!( |
| 472 | message_record(CHAT, &graph) |
| 473 | .unwrap() |
| 474 | .call_event_json |
| 475 | .is_some() |
| 476 | ); |
| 477 | } |
| 478 | } |