| 1 | use graph::Message; |
| 2 | use serde_json::Value; |
| 3 | use store::{ChatPreview, MessageRecord}; |
| 4 | |
| 5 | use crate::call_event::CallEvent; |
| 6 | use crate::external_image::is_giphy_url; |
| 7 | use crate::forwarded::FORWARDED_CONTENT_TYPE; |
| 8 | use crate::spans::{Span, html_to_spans}; |
| 9 | use crate::stored::{AttachmentInfo, attachments}; |
| 10 | |
| 11 | const MAX_PREVIEW_CHARS: usize = 200; |
| 12 | |
| 13 | pub const IMAGE_PREVIEW: &str = "Sent an image"; |
| 14 | pub const GIF_PREVIEW: &str = "\u{1F4F7} GIF"; |
| 15 | pub const VIDEO_PREVIEW: &str = "\u{1F3A5} Video"; |
| 16 | pub const FILE_PREVIEW: &str = "Sent a file"; |
| 17 | pub const CARD_PREVIEW: &str = "Sent a card"; |
| 18 | pub const FORWARD_PREVIEW: &str = "Forwarded a message"; |
| 19 | pub const AUDIO_PREVIEW: &str = "\u{1F399} Audio message"; |
| 20 | pub const LOOP_PREVIEW: &str = "Loop component"; |
| 21 | pub const RECORDING_STARTED_PREVIEW: &str = "Recording has started"; |
| 22 | pub const RECORDING_STOPPED_PREVIEW: &str = "Recording has stopped"; |
| 23 | pub const RECORDING_READY_PREVIEW: &str = "Recording is ready"; |
| 24 | pub const TRANSCRIPT_PREVIEW: &str = "Transcript is available"; |
| 25 | pub const USER_ADDED_PREVIEW: &str = "User added"; |
| 26 | pub const USER_JOINED_PREVIEW: &str = "User joined"; |
| 27 | |
| 28 | const AUDIO_CARD_TYPE: &str = "application/vnd.microsoft.card.audio"; |
| 29 | const LOOP_CARD_TYPE: &str = "application/vnd.microsoft.card.fluidEmbedCard"; |
| 30 | const FILE_CONTENT_TYPE: &str = "reference"; |
| 31 | const RECORDING_TYPE: &str = "#microsoft.graph.callRecordingEventMessageDetail"; |
| 32 | const TRANSCRIPT_TYPE: &str = "#microsoft.graph.callTranscriptEventMessageDetail"; |
| 33 | const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail"; |
| 34 | const MEMBERS_JOINED_TYPE: &str = "#microsoft.graph.membersJoinedEventMessageDetail"; |
| 35 | |
| 36 | #[derive(Default)] |
| 37 | struct BodyParts { |
| 38 | text: String, |
| 39 | images: usize, |
| 40 | gifs: usize, |
| 41 | } |
| 42 | |
| 43 | /// Plain text of a message body as the chat list shows it: emoji as glyphs, mentions by name, reply quotes and images dropped. |
| 44 | pub fn preview_text(html: &str) -> Option<String> { |
| 45 | let mut parts = BodyParts::default(); |
| 46 | collect(&html_to_spans(html), &mut parts); |
| 47 | collapse(&parts.text) |
| 48 | } |
| 49 | |
| 50 | /// The chat list line for a message, with the Teams labels for bodies without text. |
| 51 | pub fn message_preview(html: &str, attachments: &[AttachmentInfo]) -> Option<String> { |
| 52 | if html.contains("<video") { |
| 53 | return Some(VIDEO_PREVIEW.to_owned()); |
| 54 | } |
| 55 | let mut parts = BodyParts::default(); |
| 56 | collect(&html_to_spans(html), &mut parts); |
| 57 | if let Some(text) = collapse(&parts.text) { |
| 58 | return Some(text); |
| 59 | } |
| 60 | if parts.gifs > 0 { |
| 61 | return Some(GIF_PREVIEW.to_owned()); |
| 62 | } |
| 63 | if parts.images > 0 { |
| 64 | return Some(IMAGE_PREVIEW.to_owned()); |
| 65 | } |
| 66 | attachment_label(attachments).map(str::to_owned) |
| 67 | } |
| 68 | |
| 69 | fn attachment_label(attachments: &[AttachmentInfo]) -> Option<&'static str> { |
| 70 | let has_type = |wanted: &str| { |
| 71 | attachments |
| 72 | .iter() |
| 73 | .any(|attachment| attachment.content_type.as_deref() == Some(wanted)) |
| 74 | }; |
| 75 | if has_type(FORWARDED_CONTENT_TYPE) { |
| 76 | Some(FORWARD_PREVIEW) |
| 77 | } else if has_type(FILE_CONTENT_TYPE) { |
| 78 | Some(FILE_PREVIEW) |
| 79 | } else if has_type(AUDIO_CARD_TYPE) { |
| 80 | Some(AUDIO_PREVIEW) |
| 81 | } else if has_type(LOOP_CARD_TYPE) { |
| 82 | Some(LOOP_PREVIEW) |
| 83 | } else if attachments.iter().any(AttachmentInfo::is_card) { |
| 84 | Some(CARD_PREVIEW) |
| 85 | } else { |
| 86 | None |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | fn collect(spans: &[Span], parts: &mut BodyParts) { |
| 91 | for span in spans { |
| 92 | match span { |
| 93 | Span::Text(value) | Span::Code(value) => parts.text.push_str(value), |
| 94 | Span::CodeBlock { code, .. } => { |
| 95 | parts.text.push(' '); |
| 96 | parts.text.push_str(code); |
| 97 | parts.text.push(' '); |
| 98 | } |
| 99 | Span::Mention { name, .. } => parts.text.push_str(name), |
| 100 | Span::Quote { .. } => {} |
| 101 | Span::Image { hosted_content_url } if is_giphy_url(hosted_content_url) => { |
| 102 | parts.gifs += 1 |
| 103 | } |
| 104 | Span::Image { .. } => parts.images += 1, |
| 105 | Span::LineBreak | Span::Rule => parts.text.push(' '), |
| 106 | Span::Bold(children) |
| 107 | | Span::Italic(children) |
| 108 | | Span::Strike(children) |
| 109 | | Span::Superscript(children) |
| 110 | | Span::Subscript(children) |
| 111 | | Span::Sized(_, children) |
| 112 | | Span::Underline(children) |
| 113 | | Span::Colored { children, .. } |
| 114 | | Span::Link { children, .. } => collect(children, parts), |
| 115 | Span::Heading { children, .. } | Span::BlockQuote(children) => { |
| 116 | parts.text.push(' '); |
| 117 | collect(children, parts); |
| 118 | parts.text.push(' '); |
| 119 | } |
| 120 | Span::List { items, .. } => { |
| 121 | for item in items { |
| 122 | parts.text.push(' '); |
| 123 | collect(item, parts); |
| 124 | } |
| 125 | parts.text.push(' '); |
| 126 | } |
| 127 | Span::Table { rows, .. } => { |
| 128 | for cell in rows.iter().flatten() { |
| 129 | parts.text.push(' '); |
| 130 | collect(cell, parts); |
| 131 | } |
| 132 | parts.text.push(' '); |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | fn collapse(text: &str) -> Option<String> { |
| 139 | let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" "); |
| 140 | if collapsed.is_empty() { |
| 141 | return None; |
| 142 | } |
| 143 | Some(collapsed.chars().take(MAX_PREVIEW_CHARS).collect()) |
| 144 | } |
| 145 | |
| 146 | fn system_event_preview(detail: &Value) -> Option<&'static str> { |
| 147 | match detail.get("@odata.type")?.as_str()? { |
| 148 | RECORDING_TYPE => match detail.get("callRecordingStatus")?.as_str()? { |
| 149 | "initial" => Some(RECORDING_STARTED_PREVIEW), |
| 150 | "chunkFinished" => Some(RECORDING_STOPPED_PREVIEW), |
| 151 | "success" => Some(RECORDING_READY_PREVIEW), |
| 152 | _ => None, |
| 153 | }, |
| 154 | TRANSCRIPT_TYPE => Some(TRANSCRIPT_PREVIEW), |
| 155 | MEMBERS_JOINED_TYPE => Some(USER_JOINED_PREVIEW), |
| 156 | MEMBERS_ADDED_TYPE if added_only_self(detail) => Some(USER_JOINED_PREVIEW), |
| 157 | MEMBERS_ADDED_TYPE => Some(USER_ADDED_PREVIEW), |
| 158 | _ => None, |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | fn added_only_self(detail: &Value) -> bool { |
| 163 | let Some(initiator) = detail.pointer("/initiator/user/id").and_then(Value::as_str) else { |
| 164 | return false; |
| 165 | }; |
| 166 | let members = detail |
| 167 | .get("members") |
| 168 | .and_then(Value::as_array) |
| 169 | .map(Vec::as_slice) |
| 170 | .unwrap_or_default(); |
| 171 | !members.is_empty() |
| 172 | && members |
| 173 | .iter() |
| 174 | .all(|member| member.get("id").and_then(Value::as_str) == Some(initiator)) |
| 175 | } |
| 176 | |
| 177 | pub(crate) struct OwnedPreview { |
| 178 | pub text: Option<String>, |
| 179 | pub sender_id: Option<String>, |
| 180 | pub sender_name: Option<String>, |
| 181 | pub deleted: bool, |
| 182 | pub system: bool, |
| 183 | pub call: bool, |
| 184 | } |
| 185 | |
| 186 | impl OwnedPreview { |
| 187 | pub(crate) fn from_graph(message: &Message) -> Self { |
| 188 | let regular = message |
| 189 | .message_type |
| 190 | .as_deref() |
| 191 | .is_none_or(|kind| kind == "message"); |
| 192 | let deleted = message.is_deleted(); |
| 193 | let detail = message.event_detail.as_ref().filter(|_| !regular); |
| 194 | let call = detail.and_then(CallEvent::from_graph).is_some(); |
| 195 | let text = if deleted { |
| 196 | None |
| 197 | } else if regular { |
| 198 | message |
| 199 | .body |
| 200 | .as_ref() |
| 201 | .and_then(|body| body.content.as_deref()) |
| 202 | .and_then(|html| message_preview(html, &[])) |
| 203 | } else { |
| 204 | detail.and_then(system_event_preview).map(str::to_owned) |
| 205 | }; |
| 206 | let sender = message.from.as_ref().filter(|_| regular); |
| 207 | OwnedPreview { |
| 208 | text, |
| 209 | sender_id: sender |
| 210 | .and_then(|sender| sender.user_id()) |
| 211 | .map(str::to_owned), |
| 212 | sender_name: sender |
| 213 | .and_then(|sender| sender.display_name()) |
| 214 | .map(str::to_owned), |
| 215 | deleted, |
| 216 | system: !regular, |
| 217 | call, |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | pub(crate) fn from_record(record: &MessageRecord) -> Self { |
| 222 | OwnedPreview { |
| 223 | text: if record.deleted { |
| 224 | None |
| 225 | } else { |
| 226 | message_preview(&record.body_html, &attachments(record)) |
| 227 | }, |
| 228 | sender_id: record.sender_id.clone(), |
| 229 | sender_name: record.sender_name.clone(), |
| 230 | deleted: record.deleted, |
| 231 | system: false, |
| 232 | call: record.call_event_json.is_some(), |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | pub(crate) fn as_store(&self) -> ChatPreview<'_> { |
| 237 | ChatPreview { |
| 238 | text: self.text.as_deref(), |
| 239 | sender_id: self.sender_id.as_deref(), |
| 240 | sender_name: self.sender_name.as_deref(), |
| 241 | deleted: self.deleted, |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | #[cfg(test)] |
| 247 | mod tests { |
| 248 | use super::*; |
| 249 | |
| 250 | fn attachment(content_type: &str) -> AttachmentInfo { |
| 251 | serde_json::from_value(serde_json::json!({ |
| 252 | "content_type": content_type, |
| 253 | "name": null, |
| 254 | "url": null, |
| 255 | "text": null, |
| 256 | })) |
| 257 | .unwrap() |
| 258 | } |
| 259 | |
| 260 | fn graph_message(value: serde_json::Value) -> Message { |
| 261 | serde_json::from_value(value).unwrap() |
| 262 | } |
| 263 | |
| 264 | #[test] |
| 265 | fn strips_tags_and_collapses_whitespace() { |
| 266 | assert_eq!( |
| 267 | preview_text("<p>Hello <b>big</b>\n world</p><p>second</p>").as_deref(), |
| 268 | Some("Hello big world second") |
| 269 | ); |
| 270 | } |
| 271 | |
| 272 | #[test] |
| 273 | fn image_only_bodies_are_empty() { |
| 274 | assert_eq!(preview_text("<p><img src=\"x\"></p>"), None); |
| 275 | assert_eq!(preview_text(" "), None); |
| 276 | } |
| 277 | |
| 278 | #[test] |
| 279 | fn long_text_is_cut_to_the_limit() { |
| 280 | let long = "a ".repeat(400); |
| 281 | assert_eq!( |
| 282 | preview_text(&long).unwrap().chars().count(), |
| 283 | MAX_PREVIEW_CHARS |
| 284 | ); |
| 285 | } |
| 286 | |
| 287 | #[test] |
| 288 | fn plain_text_bodies_keep_entities_decoded() { |
| 289 | assert_eq!(preview_text("a & b").as_deref(), Some("a & b")); |
| 290 | } |
| 291 | |
| 292 | #[test] |
| 293 | fn emoji_and_mentions_read_like_teams() { |
| 294 | let html = r#"<p><at id="0">Robin Beck</at> kannst du? <emoji id="smile" alt="🙂" title="Smile"></emoji></p>"#; |
| 295 | assert_eq!( |
| 296 | preview_text(html).as_deref(), |
| 297 | Some("Robin Beck kannst du? 🙂") |
| 298 | ); |
| 299 | } |
| 300 | |
| 301 | #[test] |
| 302 | fn reply_quotes_are_left_out() { |
| 303 | let html = r#"<blockquote itemtype="http://schema.skype.com/Reply" itemid="1"><strong>Ada</strong><p>old</p></blockquote><p>new</p>"#; |
| 304 | assert_eq!(preview_text(html).as_deref(), Some("new")); |
| 305 | } |
| 306 | |
| 307 | #[test] |
| 308 | fn image_only_message_says_sent_an_image() { |
| 309 | let html = r#"<p><img src="https://graph.microsoft.com/v1.0/chats/19:x/messages/1/hostedContents/aWQ9/$value" alt="image" width="447" height="250" itemid="0-nde-d3-x"></p>"#; |
| 310 | assert_eq!(message_preview(html, &[]).as_deref(), Some(IMAGE_PREVIEW)); |
| 311 | } |
| 312 | |
| 313 | #[test] |
| 314 | fn text_with_an_image_keeps_only_the_text() { |
| 315 | let html = r#"<p>this is from QA:</p><p><img src="https://graph.microsoft.com/v1.0/x/$value"></p><p> </p>"#; |
| 316 | assert_eq!( |
| 317 | message_preview(html, &[]).as_deref(), |
| 318 | Some("this is from QA:") |
| 319 | ); |
| 320 | } |
| 321 | |
| 322 | #[test] |
| 323 | fn giphy_reads_as_gif() { |
| 324 | let html = r#"<p> </p><img alt="Happy Birthday Reaction GIF by The Office (GIF Image)" height="250" width="300" src="https://media2.giphy.com/media/g5R9dok94mrIvplmZd/giphy.gif?cid=x&ct=g"><p> </p>"#; |
| 325 | assert_eq!(message_preview(html, &[]).as_deref(), Some(GIF_PREVIEW)); |
| 326 | } |
| 327 | |
| 328 | #[test] |
| 329 | fn inline_video_reads_as_video() { |
| 330 | let html = r#"<p>look</p><video src="https://x/v.mp4"></video>"#; |
| 331 | assert_eq!(message_preview(html, &[]).as_deref(), Some(VIDEO_PREVIEW)); |
| 332 | } |
| 333 | |
| 334 | #[test] |
| 335 | fn attachment_only_bodies_get_a_label() { |
| 336 | let body = r#"<attachment id="1792149081221"></attachment>"#; |
| 337 | let cases = [ |
| 338 | (FORWARDED_CONTENT_TYPE, FORWARD_PREVIEW), |
| 339 | ("reference", FILE_PREVIEW), |
| 340 | ("application/vnd.microsoft.card.adaptive", CARD_PREVIEW), |
| 341 | ("application/vnd.microsoft.card.hero", CARD_PREVIEW), |
| 342 | (AUDIO_CARD_TYPE, AUDIO_PREVIEW), |
| 343 | (LOOP_CARD_TYPE, LOOP_PREVIEW), |
| 344 | ]; |
| 345 | for (content_type, expected) in cases { |
| 346 | assert_eq!( |
| 347 | message_preview(body, &[attachment(content_type)]).as_deref(), |
| 348 | Some(expected), |
| 349 | "{content_type}" |
| 350 | ); |
| 351 | } |
| 352 | assert_eq!(message_preview(body, &[]), None); |
| 353 | } |
| 354 | |
| 355 | #[test] |
| 356 | fn a_file_with_text_shows_the_text() { |
| 357 | let body = r#"Hi Philipp,<br>Kann's dir zeigen.<attachment id="0cf57a46"></attachment>"#; |
| 358 | assert_eq!( |
| 359 | message_preview(body, &[attachment("reference")]).as_deref(), |
| 360 | Some("Hi Philipp, Kann's dir zeigen.") |
| 361 | ); |
| 362 | } |
| 363 | |
| 364 | #[test] |
| 365 | fn a_reply_shows_the_reply_text() { |
| 366 | let body = "<attachment id=\"1792136042729\"></attachment>\nwas war mit dependabot?"; |
| 367 | assert_eq!( |
| 368 | message_preview(body, &[attachment("messageReference")]).as_deref(), |
| 369 | Some("was war mit dependabot?") |
| 370 | ); |
| 371 | } |
| 372 | |
| 373 | #[test] |
| 374 | fn graph_recording_and_transcript_events_have_teams_text() { |
| 375 | let event = |detail: serde_json::Value| { |
| 376 | OwnedPreview::from_graph(&graph_message(serde_json::json!({ |
| 377 | "id": "1", |
| 378 | "messageType": "systemEventMessage", |
| 379 | "body": {"contentType": "html", "content": "<systemEventMessage/>"}, |
| 380 | "from": {"user": {"id": "u1", "displayName": "Ada Lovelace"}}, |
| 381 | "eventDetail": detail, |
| 382 | }))) |
| 383 | }; |
| 384 | let ready = event(serde_json::json!({ |
| 385 | "@odata.type": RECORDING_TYPE, |
| 386 | "callRecordingStatus": "success", |
| 387 | })); |
| 388 | assert_eq!(ready.text.as_deref(), Some(RECORDING_READY_PREVIEW)); |
| 389 | assert!(ready.system && !ready.call); |
| 390 | assert_eq!(ready.sender_name, None); |
| 391 | let started = event(serde_json::json!({ |
| 392 | "@odata.type": RECORDING_TYPE, |
| 393 | "callRecordingStatus": "initial", |
| 394 | })); |
| 395 | assert_eq!(started.text.as_deref(), Some(RECORDING_STARTED_PREVIEW)); |
| 396 | let transcript = event(serde_json::json!({"@odata.type": TRANSCRIPT_TYPE})); |
| 397 | assert_eq!(transcript.text.as_deref(), Some(TRANSCRIPT_PREVIEW)); |
| 398 | } |
| 399 | |
| 400 | #[test] |
| 401 | fn graph_member_events_say_added_or_joined() { |
| 402 | let added = |members: serde_json::Value| { |
| 403 | OwnedPreview::from_graph(&graph_message(serde_json::json!({ |
| 404 | "id": "1", |
| 405 | "messageType": "systemEventMessage", |
| 406 | "eventDetail": { |
| 407 | "@odata.type": MEMBERS_ADDED_TYPE, |
| 408 | "members": members, |
| 409 | "initiator": {"user": {"id": "me"}}, |
| 410 | }, |
| 411 | }))) |
| 412 | .text |
| 413 | }; |
| 414 | assert_eq!( |
| 415 | added(serde_json::json!([{"id": "other"}])).as_deref(), |
| 416 | Some(USER_ADDED_PREVIEW) |
| 417 | ); |
| 418 | assert_eq!( |
| 419 | added(serde_json::json!([{"id": "me"}])).as_deref(), |
| 420 | Some(USER_JOINED_PREVIEW) |
| 421 | ); |
| 422 | } |
| 423 | |
| 424 | #[test] |
| 425 | fn graph_call_events_are_marked_to_keep_the_previous_line() { |
| 426 | let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({ |
| 427 | "id": "1", |
| 428 | "messageType": "systemEventMessage", |
| 429 | "eventDetail": { |
| 430 | "@odata.type": "#microsoft.graph.callEndedEventMessageDetail", |
| 431 | "callId": "c1", |
| 432 | "callDuration": "PT30S", |
| 433 | "callEventType": "call", |
| 434 | }, |
| 435 | }))); |
| 436 | assert!(preview.call); |
| 437 | assert_eq!(preview.text, None); |
| 438 | } |
| 439 | |
| 440 | #[test] |
| 441 | fn graph_deleted_flag_marks_the_preview_deleted() { |
| 442 | let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({ |
| 443 | "id": "1", |
| 444 | "messageType": "message", |
| 445 | "isDeleted": true, |
| 446 | "body": {"contentType": "html", "content": "secret"}, |
| 447 | }))); |
| 448 | assert!(preview.deleted); |
| 449 | assert_eq!(preview.text, None); |
| 450 | } |
| 451 | |
| 452 | #[test] |
| 453 | fn graph_image_preview_says_sent_an_image() { |
| 454 | let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({ |
| 455 | "id": "1", |
| 456 | "messageType": "message", |
| 457 | "body": {"contentType": "html", "content": "<p><img src=\"https://graph.microsoft.com/x/$value\"></p>"}, |
| 458 | "from": {"user": {"id": "u1", "displayName": "Lukas Berg"}}, |
| 459 | }))); |
| 460 | assert_eq!(preview.text.as_deref(), Some(IMAGE_PREVIEW)); |
| 461 | assert_eq!(preview.sender_name.as_deref(), Some("Lukas Berg")); |
| 462 | } |
| 463 | } |