| 1 | use chrono::{DateTime, Utc}; |
| 2 | use scraper::{ElementRef, Html}; |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use store::MessageRecord; |
| 5 | |
| 6 | use crate::adaptive_card::{AdaptiveCard, card_content_text}; |
| 7 | use crate::external_image::{external_image_url, is_giphy_url}; |
| 8 | use crate::forwarded::{ForwardHeader, ForwardInfo, forwarded_texts, inline_forwards, no_forward_header}; |
| 9 | use crate::markdown::escape_html; |
| 10 | use crate::mentions::MentionInput; |
| 11 | use crate::spans::{Span, html_to_spans}; |
| 12 | |
| 13 | const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji"; |
| 14 | const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply"; |
| 15 | const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A"; |
| 16 | const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card"; |
| 17 | pub(crate) const LOOP_CARD_TYPE: &str = "application/vnd.microsoft.card.fluidEmbedCard"; |
| 18 | const LOOP_CARD_NAME: &str = "Loop component"; |
| 19 | |
| 20 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 21 | pub struct AttachmentInfo { |
| 22 | pub content_type: Option<String>, |
| 23 | pub name: Option<String>, |
| 24 | pub url: Option<String>, |
| 25 | pub text: Option<String>, |
| 26 | #[serde(default)] |
| 27 | pub size: Option<u64>, |
| 28 | #[serde(default)] |
| 29 | pub quote: Option<QuoteInfo>, |
| 30 | #[serde(default)] |
| 31 | pub id: Option<String>, |
| 32 | /// Raw content, kept only for quotes and cards so an edit can send them back unchanged. |
| 33 | #[serde(default)] |
| 34 | pub content: Option<String>, |
| 35 | /// A forward whose original Graph did not return; it is not fetched again. |
| 36 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] |
| 37 | pub unavailable: bool, |
| 38 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 39 | pub teams_app_id: Option<String>, |
| 40 | } |
| 41 | |
| 42 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 43 | pub enum FileKind { |
| 44 | Word, |
| 45 | Excel, |
| 46 | PowerPoint, |
| 47 | Pdf, |
| 48 | Image, |
| 49 | Archive, |
| 50 | Loop, |
| 51 | Other, |
| 52 | } |
| 53 | |
| 54 | impl FileKind { |
| 55 | pub fn from_name(name: &str) -> FileKind { |
| 56 | let Some((_, extension)) = name.rsplit_once('.') else { |
| 57 | return FileKind::Other; |
| 58 | }; |
| 59 | match extension.to_ascii_lowercase().as_str() { |
| 60 | "doc" | "docx" | "docm" | "dot" | "dotx" | "rtf" | "odt" => FileKind::Word, |
| 61 | "xls" | "xlsx" | "xlsm" | "xlsb" | "csv" | "ods" => FileKind::Excel, |
| 62 | "ppt" | "pptx" | "pptm" | "pps" | "ppsx" | "odp" => FileKind::PowerPoint, |
| 63 | "pdf" => FileKind::Pdf, |
| 64 | "png" | "jpg" | "jpeg" | "gif" | "bmp" | "webp" | "svg" | "heic" | "tif" | "tiff" => { |
| 65 | FileKind::Image |
| 66 | } |
| 67 | "zip" | "rar" | "7z" | "tar" | "gz" | "tgz" => FileKind::Archive, |
| 68 | _ => FileKind::Other, |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 74 | pub struct QuoteInfo { |
| 75 | pub message_id: String, |
| 76 | pub preview: String, |
| 77 | pub sender_name: Option<String>, |
| 78 | } |
| 79 | |
| 80 | /// Image inside a message body. `key()` is the image cache key. |
| 81 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 82 | pub struct ImageRef { |
| 83 | pub id: String, |
| 84 | pub url: String, |
| 85 | pub width: Option<u32>, |
| 86 | pub height: Option<u32>, |
| 87 | pub alt: Option<String>, |
| 88 | } |
| 89 | |
| 90 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 91 | pub enum ImageKind { |
| 92 | Inline, |
| 93 | Gif, |
| 94 | Sticker, |
| 95 | } |
| 96 | |
| 97 | impl ImageRef { |
| 98 | pub fn key(&self) -> &str { |
| 99 | &self.url |
| 100 | } |
| 101 | |
| 102 | pub fn kind(&self) -> ImageKind { |
| 103 | match external_image_url(&self.url) { |
| 104 | None => ImageKind::Inline, |
| 105 | Some(direct) if is_giphy_url(&direct) => ImageKind::Gif, |
| 106 | Some(_) => ImageKind::Sticker, |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | impl AttachmentInfo { |
| 112 | pub fn is_card(&self) -> bool { |
| 113 | self.content_type |
| 114 | .as_deref() |
| 115 | .is_some_and(|content_type| content_type.contains("card")) |
| 116 | } |
| 117 | |
| 118 | pub fn is_link_unfurl_card(&self) -> bool { |
| 119 | self.is_card() |
| 120 | && (self |
| 121 | .teams_app_id |
| 122 | .as_deref() |
| 123 | .is_some_and(|app_id| app_id.eq_ignore_ascii_case(LINK_UNFURL_APP_ID)) |
| 124 | || self |
| 125 | .id |
| 126 | .as_deref() |
| 127 | .is_some_and(|id| id.starts_with(LINK_UNFURL_CARD_PREFIX))) |
| 128 | } |
| 129 | |
| 130 | pub fn adaptive_card(&self) -> Option<AdaptiveCard> { |
| 131 | self.content |
| 132 | .as_deref() |
| 133 | .filter(|_| self.is_card()) |
| 134 | .and_then(AdaptiveCard::parse) |
| 135 | } |
| 136 | |
| 137 | pub fn card_text(&self) -> Option<String> { |
| 138 | let content = self.content.as_deref().filter(|_| self.is_card())?; |
| 139 | card_content_text(content).or_else(|| self.text.clone()) |
| 140 | } |
| 141 | |
| 142 | pub fn file_kind(&self) -> FileKind { |
| 143 | match self.name.as_deref().map(FileKind::from_name) { |
| 144 | Some(FileKind::Other) | None if self.has_image_content_type() => FileKind::Image, |
| 145 | Some(kind) => kind, |
| 146 | None => FileKind::Other, |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | fn has_image_content_type(&self) -> bool { |
| 151 | self.content_type |
| 152 | .as_deref() |
| 153 | .is_some_and(|content_type| content_type.starts_with("image/")) |
| 154 | } |
| 155 | |
| 156 | pub fn is_file(&self) -> bool { |
| 157 | self.content_type.as_deref() == Some("reference") && self.url.is_some() |
| 158 | } |
| 159 | |
| 160 | fn loop_component_url(&self) -> Option<String> { |
| 161 | if self.content_type.as_deref() != Some(LOOP_CARD_TYPE) { |
| 162 | return None; |
| 163 | } |
| 164 | let from_content = self |
| 165 | .content |
| 166 | .as_deref() |
| 167 | .and_then(|content| serde_json::from_str::<serde_json::Value>(content).ok()) |
| 168 | .and_then(|content| content.get("componentUrl")?.as_str().map(str::to_owned)); |
| 169 | from_content.or_else(|| self.url.clone()).filter(|url| !url.is_empty()) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 174 | pub struct ReactionInfo { |
| 175 | pub reaction_type: String, |
| 176 | pub user_id: Option<String>, |
| 177 | pub user_name: Option<String>, |
| 178 | #[serde(default)] |
| 179 | pub created_at: Option<DateTime<Utc>>, |
| 180 | } |
| 181 | |
| 182 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 183 | pub struct MentionInfo { |
| 184 | pub user_id: Option<String>, |
| 185 | pub name: String, |
| 186 | #[serde(default)] |
| 187 | pub id: Option<i64>, |
| 188 | #[serde(default)] |
| 189 | pub target_id: Option<String>, |
| 190 | #[serde(default)] |
| 191 | pub group: bool, |
| 192 | } |
| 193 | |
| 194 | pub fn attachments(record: &MessageRecord) -> Vec<AttachmentInfo> { |
| 195 | serde_json::from_str(&record.attachments_json).unwrap_or_default() |
| 196 | } |
| 197 | |
| 198 | pub fn adaptive_cards(record: &MessageRecord) -> Vec<AdaptiveCard> { |
| 199 | attachments(record) |
| 200 | .iter() |
| 201 | .filter_map(AttachmentInfo::adaptive_card) |
| 202 | .collect() |
| 203 | } |
| 204 | |
| 205 | pub fn card_texts(record: &MessageRecord) -> Vec<String> { |
| 206 | attachments(record) |
| 207 | .iter() |
| 208 | .filter_map(AttachmentInfo::card_text) |
| 209 | .collect() |
| 210 | } |
| 211 | |
| 212 | pub fn reactions(record: &MessageRecord) -> Vec<ReactionInfo> { |
| 213 | serde_json::from_str(&record.reactions_json).unwrap_or_default() |
| 214 | } |
| 215 | |
| 216 | pub fn mentions(record: &MessageRecord) -> Vec<MentionInfo> { |
| 217 | let mut infos: Vec<MentionInfo> = |
| 218 | serde_json::from_str(&record.mentions_json).unwrap_or_default(); |
| 219 | for (index, info) in infos.iter_mut().enumerate() { |
| 220 | info.id = info.id.or(i64::try_from(index).ok()); |
| 221 | info.target_id = info.target_id.take().or_else(|| info.user_id.clone()); |
| 222 | } |
| 223 | infos |
| 224 | } |
| 225 | |
| 226 | /// An @Everyone of a group chat: Graph names the chat itself as the mentioned conversation. Only meaningful in chats, a channel mention looks the same in its channel. |
| 227 | pub fn mentions_whole_chat(record: &MessageRecord) -> bool { |
| 228 | mentions(record).iter().any(|mention| { |
| 229 | mention.group && mention.target_id.as_deref() == Some(record.conversation_id.as_str()) |
| 230 | }) |
| 231 | } |
| 232 | |
| 233 | pub fn quotes(record: &MessageRecord) -> Vec<QuoteInfo> { |
| 234 | attachments(record) |
| 235 | .into_iter() |
| 236 | .filter_map(|attachment| attachment.quote) |
| 237 | .collect() |
| 238 | } |
| 239 | |
| 240 | pub fn message_quote(record: &MessageRecord) -> Option<QuoteInfo> { |
| 241 | quotes(record) |
| 242 | .into_iter() |
| 243 | .next() |
| 244 | .or_else(|| inline_reply_quote(record)) |
| 245 | } |
| 246 | |
| 247 | fn inline_reply_quote(record: &MessageRecord) -> Option<QuoteInfo> { |
| 248 | let fragment = Html::parse_fragment(&record.body_html); |
| 249 | let blockquote = fragment |
| 250 | .root_element() |
| 251 | .descendants() |
| 252 | .filter_map(ElementRef::wrap) |
| 253 | .find(|element| { |
| 254 | element.value().name() == "blockquote" |
| 255 | && element |
| 256 | .value() |
| 257 | .attr("itemtype") |
| 258 | .is_some_and(|itemtype| itemtype.contains(REPLY_ITEMTYPE)) |
| 259 | && !element |
| 260 | .ancestors() |
| 261 | .filter_map(ElementRef::wrap) |
| 262 | .any(|ancestor| ancestor.value().name() == "blockquote") |
| 263 | })?; |
| 264 | let text_of = |property: &str| { |
| 265 | blockquote |
| 266 | .descendants() |
| 267 | .filter_map(ElementRef::wrap) |
| 268 | .find(|element| element.value().attr("itemprop") == Some(property)) |
| 269 | .map(|element| element.text().collect::<String>().trim().to_owned()) |
| 270 | .filter(|text| !text.is_empty()) |
| 271 | }; |
| 272 | Some(QuoteInfo { |
| 273 | message_id: blockquote.value().attr("itemid")?.to_owned(), |
| 274 | preview: text_of("preview").unwrap_or_default(), |
| 275 | sender_name: text_of("mri"), |
| 276 | }) |
| 277 | } |
| 278 | |
| 279 | pub fn images(record: &MessageRecord) -> Vec<ImageRef> { |
| 280 | if record.deleted { |
| 281 | return Vec::new(); |
| 282 | } |
| 283 | let fragment = Html::parse_fragment(&inline_forwards(record, record.body_html.clone(), &no_forward_header)); |
| 284 | let mut found: Vec<ImageRef> = Vec::new(); |
| 285 | for element in fragment |
| 286 | .root_element() |
| 287 | .descendants() |
| 288 | .filter_map(ElementRef::wrap) |
| 289 | { |
| 290 | let value = element.value(); |
| 291 | let is_emoji = value |
| 292 | .attr("itemtype") |
| 293 | .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE)); |
| 294 | let Some(url) = value |
| 295 | .attr("src") |
| 296 | .filter(|url| value.name() == "img" && !is_emoji && !url.is_empty()) |
| 297 | else { |
| 298 | continue; |
| 299 | }; |
| 300 | if found.iter().any(|image| image.url == url) { |
| 301 | continue; |
| 302 | } |
| 303 | let style = value.attr("style").unwrap_or_default(); |
| 304 | found.push(ImageRef { |
| 305 | id: image_id(found.len(), url), |
| 306 | url: url.to_owned(), |
| 307 | width: dimension(value.attr("width"), style, "width"), |
| 308 | height: dimension(value.attr("height"), style, "height"), |
| 309 | alt: value |
| 310 | .attr("alt") |
| 311 | .map(str::trim) |
| 312 | .filter(|alt| !alt.is_empty()) |
| 313 | .map(str::to_owned), |
| 314 | }); |
| 315 | } |
| 316 | found |
| 317 | } |
| 318 | |
| 319 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 320 | pub struct EditPreserved { |
| 321 | pub images_html: String, |
| 322 | pub files: Vec<graph::FileReference>, |
| 323 | pub kept: Vec<graph::KeptAttachment>, |
| 324 | } |
| 325 | |
| 326 | /// What an edit must carry over: the `<img>` elements, the file attachments and the quote or card attachments, each matched to its `<attachment id>` tag. |
| 327 | pub fn edit_preserved(record: &MessageRecord) -> EditPreserved { |
| 328 | let fragment = Html::parse_fragment(&record.body_html); |
| 329 | let mut preserved = EditPreserved::default(); |
| 330 | let mut tag_ids: Vec<&str> = Vec::new(); |
| 331 | for element in fragment |
| 332 | .root_element() |
| 333 | .descendants() |
| 334 | .filter_map(ElementRef::wrap) |
| 335 | { |
| 336 | let value = element.value(); |
| 337 | let is_emoji = value |
| 338 | .attr("itemtype") |
| 339 | .is_some_and(|itemtype| itemtype.contains(EMOJI_ITEMTYPE)); |
| 340 | match value.name() { |
| 341 | "img" if !is_emoji && value.attr("src").is_some_and(|src| !src.is_empty()) => { |
| 342 | preserved |
| 343 | .images_html |
| 344 | .push_str(&format!("<p>{}</p>", element.html())); |
| 345 | } |
| 346 | "attachment" => tag_ids.extend(value.attr("id")), |
| 347 | _ => {} |
| 348 | } |
| 349 | } |
| 350 | let stored = attachments(record); |
| 351 | let attachment_id = |attachment: &AttachmentInfo| { |
| 352 | attachment.id.clone().or_else(|| { |
| 353 | attachment |
| 354 | .quote |
| 355 | .as_ref() |
| 356 | .map(|quote| quote.message_id.clone()) |
| 357 | }) |
| 358 | }; |
| 359 | let mut unclaimed: Vec<&str> = tag_ids |
| 360 | .iter() |
| 361 | .copied() |
| 362 | .filter(|id| { |
| 363 | !stored.iter().any(|attachment| { |
| 364 | !attachment.is_file() && attachment_id(attachment).as_deref() == Some(*id) |
| 365 | }) |
| 366 | }) |
| 367 | .collect(); |
| 368 | for attachment in stored { |
| 369 | if attachment.is_file() { |
| 370 | let id = match attachment_id(&attachment) { |
| 371 | Some(id) if tag_ids.contains(&id.as_str()) => id, |
| 372 | Some(_) => continue, |
| 373 | None if unclaimed.is_empty() => continue, |
| 374 | None => unclaimed.remove(0).to_owned(), |
| 375 | }; |
| 376 | if let Some(content_url) = attachment.url { |
| 377 | preserved.files.push(graph::FileReference { |
| 378 | attachment_id: id, |
| 379 | content_url, |
| 380 | name: attachment.name.unwrap_or_default(), |
| 381 | }); |
| 382 | } |
| 383 | } else if let Some(id) = attachment_id(&attachment) |
| 384 | && tag_ids.contains(&id.as_str()) |
| 385 | && attachment.content.is_some() |
| 386 | { |
| 387 | preserved.kept.push(graph::KeptAttachment { |
| 388 | id, |
| 389 | content_type: attachment.content_type, |
| 390 | content: attachment.content, |
| 391 | content_url: attachment.url, |
| 392 | name: attachment.name, |
| 393 | }); |
| 394 | } |
| 395 | } |
| 396 | preserved |
| 397 | } |
| 398 | |
| 399 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 400 | pub struct FileCard { |
| 401 | pub name: String, |
| 402 | pub kind: FileKind, |
| 403 | pub content_type: Option<String>, |
| 404 | pub size: Option<u64>, |
| 405 | pub open_url: String, |
| 406 | } |
| 407 | |
| 408 | /// File attachments (`reference` type) with a name and a URL. `size` is rarely known; Graph does not send it for these. |
| 409 | pub fn files(record: &MessageRecord) -> Vec<FileCard> { |
| 410 | let all = attachments(record); |
| 411 | all.iter() |
| 412 | .filter(|attachment| attachment.is_file()) |
| 413 | .map(|attachment| FileCard { |
| 414 | kind: attachment.file_kind(), |
| 415 | name: attachment.name.clone().unwrap_or_default(), |
| 416 | content_type: attachment.content_type.clone(), |
| 417 | size: attachment.size, |
| 418 | open_url: attachment.url.clone().unwrap_or_default(), |
| 419 | }) |
| 420 | .chain(all.iter().filter_map(|attachment| { |
| 421 | Some(FileCard { |
| 422 | open_url: attachment.loop_component_url()?, |
| 423 | kind: FileKind::Loop, |
| 424 | name: attachment.name.clone().unwrap_or_else(|| LOOP_CARD_NAME.to_owned()), |
| 425 | content_type: attachment.content_type.clone(), |
| 426 | size: None, |
| 427 | }) |
| 428 | })) |
| 429 | .collect() |
| 430 | } |
| 431 | |
| 432 | /// Text for the clipboard: body and card text, mentions as `@name`, no markup. |
| 433 | pub fn copy_text(record: &MessageRecord) -> String { |
| 434 | let mut text = String::new(); |
| 435 | push_plain(&mut text, &message_spans(record)); |
| 436 | for extra_text in forwarded_texts(record).into_iter().chain(card_texts(record)) { |
| 437 | text.push('\n'); |
| 438 | text.push_str(&extra_text); |
| 439 | } |
| 440 | text.trim().to_owned() |
| 441 | } |
| 442 | |
| 443 | pub fn readable_text(record: &MessageRecord) -> String { |
| 444 | if let Some(event) = crate::call_event::call_event(record) { |
| 445 | return event.plain_text(); |
| 446 | } |
| 447 | let spans: Vec<Span> = message_spans(record) |
| 448 | .into_iter() |
| 449 | .filter(|span| !matches!(span, Span::Quote { .. })) |
| 450 | .collect(); |
| 451 | let mut text = String::new(); |
| 452 | push_plain(&mut text, &spans); |
| 453 | text.trim().to_owned() |
| 454 | } |
| 455 | |
| 456 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 457 | pub struct ReactionSummary { |
| 458 | pub emoji: String, |
| 459 | pub count: usize, |
| 460 | pub mine: bool, |
| 461 | } |
| 462 | |
| 463 | pub fn reaction_summaries( |
| 464 | record: &MessageRecord, |
| 465 | my_user_id: Option<&str>, |
| 466 | ) -> Vec<ReactionSummary> { |
| 467 | let mut summaries: Vec<ReactionSummary> = Vec::new(); |
| 468 | for reaction in reactions(record) { |
| 469 | let emoji = base_reaction_emoji(&reaction.reaction_type); |
| 470 | let position = match summaries.iter().position(|summary| summary.emoji == emoji) { |
| 471 | Some(position) => position, |
| 472 | None => { |
| 473 | summaries.push(ReactionSummary { |
| 474 | emoji, |
| 475 | count: 0, |
| 476 | mine: false, |
| 477 | }); |
| 478 | summaries.len() - 1 |
| 479 | } |
| 480 | }; |
| 481 | let summary = &mut summaries[position]; |
| 482 | summary.count += 1; |
| 483 | summary.mine |= my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id; |
| 484 | } |
| 485 | summaries |
| 486 | } |
| 487 | |
| 488 | fn base_reaction_emoji(reaction_type: &str) -> String { |
| 489 | let legacy = match reaction_type { |
| 490 | "like" => "\u{1F44D}", |
| 491 | "heart" => "\u{2764}", |
| 492 | "laugh" => "\u{1F606}", |
| 493 | "surprised" => "\u{1F62E}", |
| 494 | "sad" => "\u{1F641}", |
| 495 | "angry" => "\u{1F620}", |
| 496 | other => other, |
| 497 | }; |
| 498 | legacy |
| 499 | .chars() |
| 500 | .filter(|character| { |
| 501 | *character != '\u{FE0F}' && !('\u{1F3FB}'..='\u{1F3FF}').contains(character) |
| 502 | }) |
| 503 | .collect() |
| 504 | } |
| 505 | |
| 506 | pub(crate) fn push_plain(text: &mut String, spans: &[Span]) { |
| 507 | for span in spans { |
| 508 | match span { |
| 509 | Span::Text(value) | Span::Code(value) => text.push_str(value), |
| 510 | Span::CodeBlock { code, .. } => { |
| 511 | text.push_str(code); |
| 512 | text.push('\n'); |
| 513 | } |
| 514 | Span::Bold(children) |
| 515 | | Span::Italic(children) |
| 516 | | Span::Strike(children) |
| 517 | | Span::Superscript(children) |
| 518 | | Span::Subscript(children) |
| 519 | | Span::Sized(_, children) |
| 520 | | Span::Underline(children) |
| 521 | | Span::Colored { children, .. } |
| 522 | | Span::Indent { children, .. } |
| 523 | | Span::Quote { children, .. } |
| 524 | | Span::BlockQuote(children) |
| 525 | | Span::Link { children, .. } => push_plain(text, children), |
| 526 | Span::Heading { children, .. } => { |
| 527 | push_plain(text, children); |
| 528 | text.push('\n'); |
| 529 | } |
| 530 | Span::Mention { name, .. } => { |
| 531 | text.push('@'); |
| 532 | text.push_str(name); |
| 533 | } |
| 534 | Span::LineBreak | Span::Rule => text.push('\n'), |
| 535 | Span::List { |
| 536 | ordered, |
| 537 | start, |
| 538 | items, |
| 539 | } => { |
| 540 | for (offset, item) in items.iter().enumerate() { |
| 541 | if *ordered { |
| 542 | text.push_str(&format!("{}. ", *start as usize + offset)); |
| 543 | } else { |
| 544 | text.push_str("- "); |
| 545 | } |
| 546 | push_plain(text, item); |
| 547 | text.push('\n'); |
| 548 | } |
| 549 | } |
| 550 | Span::Table { rows, .. } => { |
| 551 | for row in rows { |
| 552 | for (index, cell) in row.iter().enumerate() { |
| 553 | if index > 0 { |
| 554 | text.push('\t'); |
| 555 | } |
| 556 | push_plain(text, cell); |
| 557 | } |
| 558 | text.push('\n'); |
| 559 | } |
| 560 | } |
| 561 | Span::Image { .. } => {} |
| 562 | Span::CustomEmoji { name, .. } => { |
| 563 | text.push(':'); |
| 564 | text.push_str(name); |
| 565 | text.push(':'); |
| 566 | } |
| 567 | } |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | /// Own, not deleted. Whether the conversation supports the write is the engine's call. |
| 572 | pub fn can_edit(record: &MessageRecord, my_user_id: &str) -> bool { |
| 573 | !record.deleted && record.sender_id.as_deref() == Some(my_user_id) |
| 574 | } |
| 575 | |
| 576 | pub fn can_delete(record: &MessageRecord, my_user_id: &str) -> bool { |
| 577 | can_edit(record, my_user_id) |
| 578 | } |
| 579 | |
| 580 | /// Position in the message plus an FNV-1a hash of the URL, so two GIFs from the same host never share an id. |
| 581 | fn image_id(position: usize, url: &str) -> String { |
| 582 | let hash = url.bytes().fold(0x811c_9dc5_u32, |hash, byte| { |
| 583 | (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193) |
| 584 | }); |
| 585 | format!("{position}-{hash:08x}") |
| 586 | } |
| 587 | |
| 588 | fn dimension(attribute: Option<&str>, style: &str, property: &str) -> Option<u32> { |
| 589 | let from_style = || { |
| 590 | style.split(';').find_map(|declaration| { |
| 591 | let (name, value) = declaration.split_once(':')?; |
| 592 | (name.trim() == property).then(|| leading_number(value))? |
| 593 | }) |
| 594 | }; |
| 595 | attribute |
| 596 | .and_then(leading_number) |
| 597 | .or_else(from_style) |
| 598 | .filter(|pixels| *pixels > 0) |
| 599 | } |
| 600 | |
| 601 | fn leading_number(text: &str) -> Option<u32> { |
| 602 | let digits: String = text |
| 603 | .trim() |
| 604 | .chars() |
| 605 | .take_while(char::is_ascii_digit) |
| 606 | .collect(); |
| 607 | digits.parse().ok() |
| 608 | } |
| 609 | |
| 610 | pub fn message_spans(record: &MessageRecord) -> Vec<Span> { |
| 611 | spans_with_mentions(record, &mentions(record)) |
| 612 | } |
| 613 | |
| 614 | pub const PROFILE_LINK_PREFIX: &str = "teams-profile:"; |
| 615 | |
| 616 | /// Like `message_spans`, with the id of each user mention replaced by a profile link. |
| 617 | pub fn linked_message_spans(record: &MessageRecord) -> Vec<Span> { |
| 618 | linked_message_spans_with(record, &|_| None, &no_forward_header) |
| 619 | } |
| 620 | |
| 621 | /// Like `linked_message_spans`, but a quote shows `quoted_text(message_id)` when known instead of the one-line server preview, and a forward shows `forward_header(forward)` above the original. |
| 622 | pub fn linked_message_spans_with( |
| 623 | record: &MessageRecord, |
| 624 | quoted_text: &dyn Fn(&str) -> Option<String>, |
| 625 | forward_header: &dyn Fn(&ForwardInfo) -> ForwardHeader, |
| 626 | ) -> Vec<Span> { |
| 627 | let infos = mentions(record); |
| 628 | let html = inline_forwards(record, with_inline_quotes(record, quoted_text), forward_header); |
| 629 | let mut spans = html_to_spans(&html); |
| 630 | merge_split_mentions(&mut spans, &infos); |
| 631 | link_user_mentions(&mut spans, &infos); |
| 632 | spans |
| 633 | } |
| 634 | |
| 635 | /// The spans of `record` with its body replaced by the translated html. |
| 636 | pub fn translated_spans( |
| 637 | record: &MessageRecord, |
| 638 | translated_html: &str, |
| 639 | forward_header: &dyn Fn(&ForwardInfo) -> ForwardHeader, |
| 640 | ) -> Vec<Span> { |
| 641 | let mut translated = record.clone(); |
| 642 | translated.body_html = translated_html.to_owned(); |
| 643 | linked_message_spans_with(&translated, &|_| None, forward_header) |
| 644 | } |
| 645 | |
| 646 | fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) { |
| 647 | for span in spans { |
| 648 | match span { |
| 649 | Span::Bold(children) |
| 650 | | Span::Italic(children) |
| 651 | | Span::Strike(children) |
| 652 | | Span::Superscript(children) |
| 653 | | Span::Subscript(children) |
| 654 | | Span::Sized(_, children) |
| 655 | | Span::Underline(children) |
| 656 | | Span::Colored { children, .. } |
| 657 | | Span::Indent { children, .. } |
| 658 | | Span::Heading { children, .. } |
| 659 | | Span::Quote { children, .. } |
| 660 | | Span::BlockQuote(children) |
| 661 | | Span::Link { children, .. } => link_user_mentions(children, infos), |
| 662 | Span::List { items, .. } => items |
| 663 | .iter_mut() |
| 664 | .for_each(|item| link_user_mentions(item, infos)), |
| 665 | Span::Table { rows, .. } => rows |
| 666 | .iter_mut() |
| 667 | .flatten() |
| 668 | .for_each(|cell| link_user_mentions(cell, infos)), |
| 669 | Span::Mention { id, .. } => { |
| 670 | let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok()); |
| 671 | let user_id = infos |
| 672 | .iter() |
| 673 | .find(|info| parsed.is_some() && info.id == parsed) |
| 674 | .and_then(|info| info.user_id.as_deref()); |
| 675 | if let Some(user_id) = user_id { |
| 676 | *id = Some(format!("{PROFILE_LINK_PREFIX}{user_id}")); |
| 677 | } |
| 678 | } |
| 679 | _ => {} |
| 680 | } |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> { |
| 685 | let mut spans = html_to_spans(&with_inline_quotes(record, &|_| None)); |
| 686 | merge_split_mentions(&mut spans, infos); |
| 687 | spans |
| 688 | } |
| 689 | |
| 690 | fn with_inline_quotes(record: &MessageRecord, quoted_text: &dyn Fn(&str) -> Option<String>) -> String { |
| 691 | let mut html = record.body_html.clone(); |
| 692 | for attachment in attachments(record) { |
| 693 | let Some(mut quote) = attachment.quote else { |
| 694 | continue; |
| 695 | }; |
| 696 | if let Some(text) = quoted_text("e.message_id).filter(|text| !text.trim().is_empty()) { |
| 697 | quote.preview = text; |
| 698 | } |
| 699 | let id = attachment.id.unwrap_or_else(|| quote.message_id.clone()); |
| 700 | let tag = format!("<attachment id=\"{id}\"></attachment>"); |
| 701 | let block = quote_html("e); |
| 702 | if html.contains(&tag) { |
| 703 | html = html.replacen(&tag, &block, 1); |
| 704 | } else { |
| 705 | html.insert_str(0, &block); |
| 706 | } |
| 707 | } |
| 708 | html |
| 709 | } |
| 710 | |
| 711 | pub fn quote_html(quote: &QuoteInfo) -> String { |
| 712 | let sender = quote |
| 713 | .sender_name |
| 714 | .as_deref() |
| 715 | .map(|name| format!("<strong itemprop=\"mri\">{}</strong>", escape_html(name))) |
| 716 | .unwrap_or_default(); |
| 717 | let time = quote_time("e.message_id) |
| 718 | .map(|time| format!(" <span itemprop=\"time\">{time}</span>")) |
| 719 | .unwrap_or_default(); |
| 720 | let preview = escape_html(quote.preview.trim()).replace('\n', "<br>"); |
| 721 | format!( |
| 722 | "<blockquote itemscope=\"\" itemtype=\"http://{REPLY_ITEMTYPE}\" itemid=\"{}\">{sender}{time}<p itemprop=\"preview\">{preview}</p></blockquote>", |
| 723 | escape_html("e.message_id), |
| 724 | ) |
| 725 | } |
| 726 | |
| 727 | fn quote_time(message_id: &str) -> Option<String> { |
| 728 | let millis = message_id.parse::<i64>().ok()?; |
| 729 | let time = chrono::DateTime::from_timestamp_millis(millis)?; |
| 730 | Some(time.with_timezone(&chrono::Local).format("%d/%m/%Y %H:%M").to_string()) |
| 731 | } |
| 732 | |
| 733 | pub fn user_mention_inputs(record: &MessageRecord) -> Vec<MentionInput> { |
| 734 | let infos = mentions(record); |
| 735 | let mut inputs = Vec::new(); |
| 736 | collect_user_mentions(&spans_with_mentions(record, &infos), &infos, &mut inputs); |
| 737 | inputs |
| 738 | } |
| 739 | |
| 740 | fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec<MentionInput>) { |
| 741 | for span in spans { |
| 742 | match span { |
| 743 | Span::Bold(children) |
| 744 | | Span::Italic(children) |
| 745 | | Span::Strike(children) |
| 746 | | Span::Superscript(children) |
| 747 | | Span::Subscript(children) |
| 748 | | Span::Sized(_, children) |
| 749 | | Span::Underline(children) |
| 750 | | Span::Colored { children, .. } |
| 751 | | Span::Indent { children, .. } |
| 752 | | Span::Heading { children, .. } |
| 753 | | Span::Quote { children, .. } |
| 754 | | Span::BlockQuote(children) |
| 755 | | Span::Link { children, .. } => collect_user_mentions(children, infos, inputs), |
| 756 | Span::List { items, .. } => items |
| 757 | .iter() |
| 758 | .for_each(|item| collect_user_mentions(item, infos, inputs)), |
| 759 | Span::Table { rows, .. } => rows |
| 760 | .iter() |
| 761 | .flatten() |
| 762 | .for_each(|cell| collect_user_mentions(cell, infos, inputs)), |
| 763 | Span::Mention { name, id } => { |
| 764 | let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok()); |
| 765 | let user_id = infos |
| 766 | .iter() |
| 767 | .find(|info| parsed.is_some() && info.id == parsed) |
| 768 | .and_then(|info| info.user_id.as_deref()); |
| 769 | if let Some(user_id) = user_id { |
| 770 | inputs.push(MentionInput::user(user_id, name)); |
| 771 | } |
| 772 | } |
| 773 | _ => {} |
| 774 | } |
| 775 | } |
| 776 | } |
| 777 | |
| 778 | fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) { |
| 779 | let target_of = |id: &Option<String>| -> Option<String> { |
| 780 | let parsed: i64 = id.as_deref()?.parse().ok()?; |
| 781 | mentions |
| 782 | .iter() |
| 783 | .find(|info| info.id == Some(parsed))? |
| 784 | .target_id |
| 785 | .clone() |
| 786 | }; |
| 787 | let mut merged: Vec<Span> = Vec::with_capacity(spans.len()); |
| 788 | for mut span in std::mem::take(spans) { |
| 789 | match &mut span { |
| 790 | Span::Bold(children) |
| 791 | | Span::Italic(children) |
| 792 | | Span::Strike(children) |
| 793 | | Span::Superscript(children) |
| 794 | | Span::Subscript(children) |
| 795 | | Span::Sized(_, children) |
| 796 | | Span::Underline(children) |
| 797 | | Span::Colored { children, .. } |
| 798 | | Span::Indent { children, .. } |
| 799 | | Span::Heading { children, .. } |
| 800 | | Span::Quote { children, .. } |
| 801 | | Span::BlockQuote(children) |
| 802 | | Span::Link { children, .. } => merge_split_mentions(children, mentions), |
| 803 | Span::List { items, .. } => items |
| 804 | .iter_mut() |
| 805 | .for_each(|item| merge_split_mentions(item, mentions)), |
| 806 | Span::Table { rows, .. } => rows |
| 807 | .iter_mut() |
| 808 | .flatten() |
| 809 | .for_each(|cell| merge_split_mentions(cell, mentions)), |
| 810 | Span::Mention { name, id } => { |
| 811 | let continues = match merged.as_slice() { |
| 812 | [ |
| 813 | .., |
| 814 | Span::Mention { |
| 815 | id: previous_id, .. |
| 816 | }, |
| 817 | Span::Text(gap), |
| 818 | ] => { |
| 819 | gap.trim().is_empty() |
| 820 | && target_of(id).is_some() |
| 821 | && target_of(previous_id) == target_of(id) |
| 822 | } |
| 823 | _ => false, |
| 824 | }; |
| 825 | if continues { |
| 826 | merged.pop(); |
| 827 | if let Some(Span::Mention { |
| 828 | name: previous_name, |
| 829 | .. |
| 830 | }) = merged.last_mut() |
| 831 | { |
| 832 | previous_name.push(' '); |
| 833 | previous_name.push_str(name); |
| 834 | } |
| 835 | continue; |
| 836 | } |
| 837 | } |
| 838 | _ => {} |
| 839 | } |
| 840 | merged.push(span); |
| 841 | } |
| 842 | *spans = merged; |
| 843 | } |
| 844 | |
| 845 | #[cfg(test)] |
| 846 | mod tests { |
| 847 | use chrono::Utc; |
| 848 | |
| 849 | use super::*; |
| 850 | |
| 851 | fn record(body_html: &str, attachments_json: &str) -> MessageRecord { |
| 852 | MessageRecord { |
| 853 | subject: None, |
| 854 | conversation_id: "c".to_owned(), |
| 855 | message_id: "m".to_owned(), |
| 856 | reply_to_id: None, |
| 857 | sender_id: Some("u".to_owned()), |
| 858 | sender_name: None, |
| 859 | sender_application_id: None, |
| 860 | links_json: "[]".to_owned(), |
| 861 | created_at: Utc::now(), |
| 862 | edited_at: None, |
| 863 | deleted: false, |
| 864 | body_html: body_html.to_owned(), |
| 865 | attachments_json: attachments_json.to_owned(), |
| 866 | reactions_json: "[]".to_owned(), |
| 867 | mentions_json: "[]".to_owned(), |
| 868 | call_event_json: None, |
| 869 | importance: Default::default(), |
| 870 | } |
| 871 | } |
| 872 | |
| 873 | #[test] |
| 874 | fn reaction_without_created_at_still_parses() { |
| 875 | let mut stored = record("", "[]"); |
| 876 | stored.reactions_json = |
| 877 | r#"[{"reaction_type":"like","user_id":"u","user_name":null}]"#.to_owned(); |
| 878 | let parsed = reactions(&stored); |
| 879 | assert_eq!(parsed.len(), 1); |
| 880 | assert_eq!(parsed[0].created_at, None); |
| 881 | } |
| 882 | |
| 883 | #[test] |
| 884 | fn images_cover_hosted_contents_and_ams_and_skip_emoji() { |
| 885 | let html = concat!( |
| 886 | r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#, |
| 887 | r#"<img itemtype="http://schema.skype.com/AMSImage" src="https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo" width="64" height="auto">"#, |
| 888 | r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#, |
| 889 | r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#, |
| 890 | ); |
| 891 | let found = images(&record(html, "[]")); |
| 892 | assert_eq!(found.len(), 2); |
| 893 | assert_eq!((found[0].width, found[0].height), (Some(300), Some(120))); |
| 894 | assert_eq!((found[1].width, found[1].height), (Some(64), None)); |
| 895 | assert!(found[0].id.starts_with("0-")); |
| 896 | assert!(found[1].id.starts_with("1-")); |
| 897 | } |
| 898 | |
| 899 | #[test] |
| 900 | fn two_giphy_gifs_get_different_image_ids_and_the_gif_kind() { |
| 901 | let html = concat!( |
| 902 | r#"<img src="https://media0.giphy.com/media/abc/giphy.gif" alt=" dancing cat ">"#, |
| 903 | r#"<img src="https://media1.giphy.com/media/def/giphy.gif">"#, |
| 904 | r#"<img src="https://statics.teams.cdn.office.net/evergreen-assets/stickerassets/a/b.gif">"#, |
| 905 | r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#, |
| 906 | ); |
| 907 | let found = images(&record(html, "[]")); |
| 908 | let ids: std::collections::HashSet<&str> = |
| 909 | found.iter().map(|image| image.id.as_str()).collect(); |
| 910 | assert_eq!(ids.len(), 4); |
| 911 | assert_eq!(found[0].id, images(&record(html, "[]"))[0].id); |
| 912 | assert_eq!(found[0].alt.as_deref(), Some("dancing cat")); |
| 913 | assert_eq!(found[1].alt, None); |
| 914 | let kinds: Vec<ImageKind> = found.iter().map(ImageRef::kind).collect(); |
| 915 | assert_eq!( |
| 916 | kinds, |
| 917 | [ |
| 918 | ImageKind::Gif, |
| 919 | ImageKind::Gif, |
| 920 | ImageKind::Sticker, |
| 921 | ImageKind::Inline |
| 922 | ] |
| 923 | ); |
| 924 | } |
| 925 | |
| 926 | #[test] |
| 927 | fn readable_text_keeps_lines_lists_code_and_mentions_and_drops_the_reply_quote() { |
| 928 | let html = concat!( |
| 929 | r#"<blockquote itemscope="" itemtype="http://schema.skype.com/Reply" itemid="Q0"><strong itemprop="mri">Bob</strong><p itemprop="preview">old words</p></blockquote>"#, |
| 930 | r#"<p>Hi <at id="0">Ada</at></p><ul><li>one</li><li>two</li></ul><pre>let x = 1;</pre><p>last</p>"#, |
| 931 | ); |
| 932 | let json = r#"[{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}]"#; |
| 933 | let text = readable_text(&with_mentions(html, json)); |
| 934 | assert!(!text.contains("old words"), "{text}"); |
| 935 | assert!(!text.contains("Bob"), "{text}"); |
| 936 | assert!(text.starts_with("Hi @Ada\n"), "{text}"); |
| 937 | assert!(text.contains("- one\n- two\n"), "{text}"); |
| 938 | assert!(text.contains("let x = 1;\n"), "{text}"); |
| 939 | assert!(text.ends_with("last"), "{text}"); |
| 940 | } |
| 941 | |
| 942 | #[test] |
| 943 | fn a_quote_keeps_its_lines_and_shows_when_the_quoted_message_was_sent() { |
| 944 | let html = quote_html(&QuoteInfo { |
| 945 | message_id: "1760517360000".to_owned(), |
| 946 | preview: "first link\nsecond link".to_owned(), |
| 947 | sender_name: Some("Ada".to_owned()), |
| 948 | }); |
| 949 | assert!(html.contains("first link<br>second link"), "{html}"); |
| 950 | assert!(html.contains("/2025 "), "{html}"); |
| 951 | let without_time = quote_html(&QuoteInfo { |
| 952 | message_id: "Q9".to_owned(), |
| 953 | preview: "text".to_owned(), |
| 954 | sender_name: None, |
| 955 | }); |
| 956 | assert!(!without_time.contains("itemprop=\"time\""), "{without_time}"); |
| 957 | } |
| 958 | |
| 959 | #[test] |
| 960 | fn a_reply_blockquote_in_the_body_becomes_the_quote() { |
| 961 | let html = format!( |
| 962 | "{}<p>answer</p>", |
| 963 | quote_html(&QuoteInfo { |
| 964 | message_id: "Q9".to_owned(), |
| 965 | preview: "a < b".to_owned(), |
| 966 | sender_name: Some("Ada".to_owned()), |
| 967 | }) |
| 968 | ); |
| 969 | let stored = record(&html, "[]"); |
| 970 | assert_eq!( |
| 971 | message_quote(&stored), |
| 972 | Some(QuoteInfo { |
| 973 | message_id: "Q9".to_owned(), |
| 974 | preview: "a < b".to_owned(), |
| 975 | sender_name: Some("Ada".to_owned()), |
| 976 | }) |
| 977 | ); |
| 978 | assert_eq!(readable_text(&stored), "answer"); |
| 979 | assert_eq!(message_quote(&record("<p>plain</p>", "[]")), None); |
| 980 | } |
| 981 | |
| 982 | #[test] |
| 983 | fn a_reply_blockquote_nested_in_a_normal_blockquote_is_not_the_quote() { |
| 984 | let html = format!( |
| 985 | "<blockquote>{}</blockquote><p>answer</p>", |
| 986 | quote_html(&QuoteInfo { |
| 987 | message_id: "Q9".to_owned(), |
| 988 | preview: "inner".to_owned(), |
| 989 | sender_name: None, |
| 990 | }) |
| 991 | ); |
| 992 | assert_eq!(message_quote(&record(&html, "[]")), None); |
| 993 | } |
| 994 | |
| 995 | #[test] |
| 996 | fn readable_text_drops_the_stored_quote_and_card_text() { |
| 997 | let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","quote":{"message_id":"Q1","preview":"quoted","sender_name":"Ada"}}]"#; |
| 998 | let stored = record("<attachment id=\"Q1\"></attachment><p>answer</p>", json); |
| 999 | assert_eq!(readable_text(&stored), "answer"); |
| 1000 | } |
| 1001 | |
| 1002 | #[test] |
| 1003 | fn reactions_group_by_base_emoji_and_merge_skin_tones() { |
| 1004 | let mut stored = record("", "[]"); |
| 1005 | stored.reactions_json = r#"[ |
| 1006 | {"reaction_type":"like","user_id":"a"}, |
| 1007 | {"reaction_type":"\ud83d\udc4d\ud83c\udffd","user_id":"me"}, |
| 1008 | {"reaction_type":"\ud83d\udc4d","user_id":"b"}, |
| 1009 | {"reaction_type":"heart","user_id":"a"}, |
| 1010 | {"reaction_type":"\u2764\ufe0f","user_id":"c"} |
| 1011 | ]"# |
| 1012 | .to_owned(); |
| 1013 | let summaries = reaction_summaries(&stored, Some("me")); |
| 1014 | assert_eq!( |
| 1015 | summaries, |
| 1016 | vec![ |
| 1017 | ReactionSummary { |
| 1018 | emoji: "\u{1F44D}".to_owned(), |
| 1019 | count: 3, |
| 1020 | mine: true |
| 1021 | }, |
| 1022 | ReactionSummary { |
| 1023 | emoji: "\u{2764}".to_owned(), |
| 1024 | count: 2, |
| 1025 | mine: false |
| 1026 | }, |
| 1027 | ] |
| 1028 | ); |
| 1029 | assert!( |
| 1030 | reaction_summaries(&stored, None) |
| 1031 | .iter() |
| 1032 | .all(|summary| !summary.mine) |
| 1033 | ); |
| 1034 | } |
| 1035 | |
| 1036 | #[test] |
| 1037 | fn deleted_messages_have_no_images() { |
| 1038 | let mut deleted = record(r#"<img src="https://x/y">"#, "[]"); |
| 1039 | deleted.deleted = true; |
| 1040 | assert!(images(&deleted).is_empty()); |
| 1041 | } |
| 1042 | |
| 1043 | #[test] |
| 1044 | fn edits_keep_images_and_match_files_to_their_attachment_tags() { |
| 1045 | let html = "<p>text</p><p><img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\"></p><attachment id=\"G1\"></attachment>"; |
| 1046 | let attachments = r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"G1"}]"#; |
| 1047 | let preserved = edit_preserved(&record(html, attachments)); |
| 1048 | assert!( |
| 1049 | preserved |
| 1050 | .images_html |
| 1051 | .starts_with("<p><img src=\"https://graph.microsoft.com/") |
| 1052 | ); |
| 1053 | assert!(!preserved.images_html.contains("text")); |
| 1054 | assert_eq!(preserved.files.len(), 1); |
| 1055 | assert_eq!(preserved.files[0].attachment_id, "G1"); |
| 1056 | assert_eq!(preserved.files[0].content_url, "https://x/a.pdf"); |
| 1057 | assert_eq!(preserved.files[0].name, "a.pdf"); |
| 1058 | assert!(preserved.kept.is_empty()); |
| 1059 | } |
| 1060 | |
| 1061 | const QUOTED_HTML: &str = |
| 1062 | "<attachment id=\"Q1\"></attachment><p>answer</p><attachment id=\"F1\"></attachment>"; |
| 1063 | |
| 1064 | #[test] |
| 1065 | fn a_quoted_reply_keeps_its_quote_and_pairs_the_file_by_id() { |
| 1066 | let attachments = r#"[ |
| 1067 | {"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","content":"{\"messageId\":\"Q1\",\"messagePreview\":\"hi\"}","quote":{"message_id":"Q1","preview":"hi","sender_name":null}}, |
| 1068 | {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"F1"} |
| 1069 | ]"#; |
| 1070 | let preserved = edit_preserved(&record(QUOTED_HTML, attachments)); |
| 1071 | assert_eq!(preserved.files.len(), 1); |
| 1072 | assert_eq!(preserved.files[0].attachment_id, "F1"); |
| 1073 | assert_eq!(preserved.kept.len(), 1); |
| 1074 | assert_eq!(preserved.kept[0].id, "Q1"); |
| 1075 | assert_eq!( |
| 1076 | preserved.kept[0].content_type.as_deref(), |
| 1077 | Some("messageReference") |
| 1078 | ); |
| 1079 | assert!( |
| 1080 | preserved.kept[0] |
| 1081 | .content |
| 1082 | .as_deref() |
| 1083 | .unwrap() |
| 1084 | .contains("messagePreview") |
| 1085 | ); |
| 1086 | } |
| 1087 | |
| 1088 | #[test] |
| 1089 | fn records_cached_before_content_was_stored_leave_the_quote_out() { |
| 1090 | let attachments = r#"[ |
| 1091 | {"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}}, |
| 1092 | {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null} |
| 1093 | ]"#; |
| 1094 | let preserved = edit_preserved(&record(QUOTED_HTML, attachments)); |
| 1095 | assert_eq!(preserved.files[0].attachment_id, "F1"); |
| 1096 | assert!(preserved.kept.is_empty()); |
| 1097 | } |
| 1098 | |
| 1099 | #[test] |
| 1100 | fn file_kind_follows_the_extension_then_the_content_type() { |
| 1101 | let kind = |name: Option<&str>, content_type: &str| { |
| 1102 | AttachmentInfo { |
| 1103 | content_type: Some(content_type.to_owned()), |
| 1104 | name: name.map(str::to_owned), |
| 1105 | url: None, |
| 1106 | text: None, |
| 1107 | size: None, |
| 1108 | quote: None, |
| 1109 | id: None, |
| 1110 | content: None, |
| 1111 | unavailable: false, |
| 1112 | teams_app_id: None, |
| 1113 | } |
| 1114 | .file_kind() |
| 1115 | }; |
| 1116 | assert_eq!(kind(Some("Plan.DOCX"), "reference"), FileKind::Word); |
| 1117 | assert_eq!(kind(Some("a.xlsx"), "reference"), FileKind::Excel); |
| 1118 | assert_eq!(kind(Some("a.pptx"), "reference"), FileKind::PowerPoint); |
| 1119 | assert_eq!(kind(Some("a.pdf"), "reference"), FileKind::Pdf); |
| 1120 | assert_eq!(kind(Some("a.PNG"), "reference"), FileKind::Image); |
| 1121 | assert_eq!(kind(Some("a.zip"), "reference"), FileKind::Archive); |
| 1122 | assert_eq!(kind(Some("a.bin"), "reference"), FileKind::Other); |
| 1123 | assert_eq!(kind(None, "image/png"), FileKind::Image); |
| 1124 | assert_eq!(kind(Some("noextension"), "reference"), FileKind::Other); |
| 1125 | } |
| 1126 | |
| 1127 | #[test] |
| 1128 | fn files_expose_name_kind_and_open_url() { |
| 1129 | let json = r#"[{"content_type":"reference","name":"Plan.docx","url":"https://x/Plan.docx","text":null},{"content_type":"messageReference","name":null,"url":null,"text":null}]"#; |
| 1130 | let found = files(&record("", json)); |
| 1131 | assert_eq!(found.len(), 1); |
| 1132 | assert_eq!( |
| 1133 | (found[0].name.as_str(), found[0].kind), |
| 1134 | ("Plan.docx", FileKind::Word) |
| 1135 | ); |
| 1136 | assert_eq!(found[0].open_url, "https://x/Plan.docx"); |
| 1137 | assert_eq!(found[0].size, None); |
| 1138 | } |
| 1139 | |
| 1140 | #[test] |
| 1141 | fn a_loop_component_opens_its_component_url() { |
| 1142 | let json = r#"[{"content_type":"application/vnd.microsoft.card.fluidEmbedCard","name":null,"url":null,"text":null,"id":"placeholder","content":"{\"componentUrl\":\"https://x/loop.fluid\",\"sourceType\":\"Compose\"}"}]"#; |
| 1143 | let found = files(&record("", json)); |
| 1144 | assert_eq!(found.len(), 1); |
| 1145 | assert_eq!( |
| 1146 | (found[0].name.as_str(), found[0].kind, found[0].open_url.as_str()), |
| 1147 | ("Loop component", FileKind::Loop, "https://x/loop.fluid") |
| 1148 | ); |
| 1149 | } |
| 1150 | |
| 1151 | #[test] |
| 1152 | fn copy_text_flattens_markup_and_keeps_mentions_and_lines() { |
| 1153 | let html = r#"<p>Hi <at id="0">Ada</at>, <b>look</b></p><p>second <a href="https://x">link</a></p>"#; |
| 1154 | let text = copy_text(&record(html, "[]")); |
| 1155 | assert!(text.starts_with("Hi @Ada, look"), "{text}"); |
| 1156 | assert!(text.contains("second link"), "{text}"); |
| 1157 | assert!(text.contains('\n')); |
| 1158 | } |
| 1159 | |
| 1160 | #[test] |
| 1161 | fn old_cached_attachments_still_parse() { |
| 1162 | let parsed = attachments(&record( |
| 1163 | "", |
| 1164 | r#"[{"content_type":"reference","name":"a.pdf","url":"u","text":null}]"#, |
| 1165 | )); |
| 1166 | assert_eq!(parsed.len(), 1); |
| 1167 | assert!(parsed[0].is_file()); |
| 1168 | assert_eq!(parsed[0].size, None); |
| 1169 | } |
| 1170 | |
| 1171 | #[test] |
| 1172 | fn quote_references_are_extracted_from_the_message_reference_attachment() { |
| 1173 | let attachment = graph::Attachment { |
| 1174 | id: Some("1".to_owned()), |
| 1175 | content_type: Some("messageReference".to_owned()), |
| 1176 | content_url: None, |
| 1177 | name: None, |
| 1178 | teams_app_id: None, |
| 1179 | content: Some( |
| 1180 | r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(), |
| 1181 | ), |
| 1182 | }; |
| 1183 | let info = crate::mapping::attachment_info(&attachment); |
| 1184 | assert_eq!( |
| 1185 | info.quote, |
| 1186 | Some(QuoteInfo { |
| 1187 | message_id: "1728".to_owned(), |
| 1188 | preview: "Hello".to_owned(), |
| 1189 | sender_name: Some("Adele".to_owned()) |
| 1190 | }) |
| 1191 | ); |
| 1192 | let stored = record("", &serde_json::to_string(&[info]).unwrap()); |
| 1193 | assert_eq!(quotes(&stored).len(), 1); |
| 1194 | } |
| 1195 | |
| 1196 | #[test] |
| 1197 | fn a_message_reference_renders_as_a_reply_quote_where_its_tag_sits() { |
| 1198 | let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","quote":{"message_id":"Q1","preview":"a < b","sender_name":"Ada"}}]"#; |
| 1199 | let stored = record( |
| 1200 | "<p></p><attachment id=\"Q1\"></attachment>\ntest<p></p>", |
| 1201 | json, |
| 1202 | ); |
| 1203 | let spans = message_spans(&stored); |
| 1204 | let Some(Span::Quote { children, .. }) = spans.first() else { |
| 1205 | panic!("expected a reply quote first, got {spans:?}"); |
| 1206 | }; |
| 1207 | let mut quoted = String::new(); |
| 1208 | push_plain(&mut quoted, children); |
| 1209 | assert!(quoted.contains("Ada")); |
| 1210 | assert!(quoted.contains("a < b")); |
| 1211 | let mut own = String::new(); |
| 1212 | push_plain(&mut own, &spans[1..]); |
| 1213 | assert_eq!(own.trim(), "test"); |
| 1214 | } |
| 1215 | |
| 1216 | #[test] |
| 1217 | fn a_message_reference_without_its_tag_still_shows_the_quote() { |
| 1218 | let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}}]"#; |
| 1219 | let spans = message_spans(&record("<p>answer</p>", json)); |
| 1220 | assert!(matches!(spans.first(), Some(Span::Quote { .. }))); |
| 1221 | } |
| 1222 | |
| 1223 | fn with_mentions(body_html: &str, mentions_json: &str) -> MessageRecord { |
| 1224 | let mut stored = record(body_html, "[]"); |
| 1225 | stored.mentions_json = mentions_json.to_owned(); |
| 1226 | stored |
| 1227 | } |
| 1228 | |
| 1229 | fn mention_names(spans: &[Span]) -> Vec<&str> { |
| 1230 | spans |
| 1231 | .iter() |
| 1232 | .filter_map(|span| match span { |
| 1233 | Span::Mention { name, .. } => Some(name.as_str()), |
| 1234 | _ => None, |
| 1235 | }) |
| 1236 | .collect() |
| 1237 | } |
| 1238 | |
| 1239 | #[test] |
| 1240 | fn user_mentions_link_to_their_profile_and_groups_do_not() { |
| 1241 | let json = r#"[ |
| 1242 | {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}, |
| 1243 | {"user_id":null,"name":"Team","id":1,"target_id":"T1"} |
| 1244 | ]"#; |
| 1245 | let html = r#"<at id="0">Ada</at> <at id="1">Team</at>"#; |
| 1246 | let ids: Vec<Option<String>> = linked_message_spans(&with_mentions(html, json)) |
| 1247 | .into_iter() |
| 1248 | .filter_map(|span| match span { |
| 1249 | Span::Mention { id, .. } => Some(id), |
| 1250 | _ => None, |
| 1251 | }) |
| 1252 | .collect(); |
| 1253 | assert_eq!( |
| 1254 | ids, |
| 1255 | vec![Some("teams-profile:U1".to_owned()), Some("1".to_owned())] |
| 1256 | ); |
| 1257 | } |
| 1258 | |
| 1259 | #[test] |
| 1260 | fn a_tag_mention_split_per_word_merges_into_one() { |
| 1261 | let json = r#"[ |
| 1262 | {"user_id":null,"name":"Tip","id":0,"target_id":"T1"}, |
| 1263 | {"user_id":null,"name":"of","id":1,"target_id":"T1"}, |
| 1264 | {"user_id":null,"name":"the","id":2,"target_id":"T1"}, |
| 1265 | {"user_id":null,"name":"day","id":3,"target_id":"T1"} |
| 1266 | ]"#; |
| 1267 | let html = r#"<p>Hey <at id="0">Tip</at> <at id="1">of</at> <at id="2">the</at> <at id="3">day</at>!</p>"#; |
| 1268 | let spans = message_spans(&with_mentions(html, json)); |
| 1269 | assert_eq!(mention_names(&spans), vec!["Tip of the day"]); |
| 1270 | assert_eq!( |
| 1271 | copy_text(&with_mentions(html, json)), |
| 1272 | "Hey @Tip of the day!" |
| 1273 | ); |
| 1274 | } |
| 1275 | |
| 1276 | #[test] |
| 1277 | fn a_two_word_user_name_merges_but_different_users_stay_apart() { |
| 1278 | let json = r#"[ |
| 1279 | {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}, |
| 1280 | {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"}, |
| 1281 | {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"} |
| 1282 | ]"#; |
| 1283 | let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Bob</at>"#; |
| 1284 | let spans = message_spans(&with_mentions(html, json)); |
| 1285 | assert_eq!(mention_names(&spans), vec!["Ada Lovelace", "Bob"]); |
| 1286 | } |
| 1287 | |
| 1288 | #[test] |
| 1289 | fn different_users_next_to_each_other_stay_two_mentions() { |
| 1290 | let json = r#"[ |
| 1291 | {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}, |
| 1292 | {"user_id":"U2","name":"Bob","id":1,"target_id":"U2"} |
| 1293 | ]"#; |
| 1294 | let html = r#"<at id="0">Ada</at> <at id="1">Bob</at>"#; |
| 1295 | let spans = message_spans(&with_mentions(html, json)); |
| 1296 | assert_eq!(mention_names(&spans), vec!["Ada", "Bob"]); |
| 1297 | } |
| 1298 | |
| 1299 | #[test] |
| 1300 | fn nested_split_mentions_merge() { |
| 1301 | let json = r#"[ |
| 1302 | {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}, |
| 1303 | {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"} |
| 1304 | ]"#; |
| 1305 | let html = r#"<b><at id="0">Ada</at> <at id="1">Lovelace</at></b>"#; |
| 1306 | let spans = message_spans(&with_mentions(html, json)); |
| 1307 | let [Span::Bold(children)] = spans.as_slice() else { |
| 1308 | panic!("bold expected: {spans:?}") |
| 1309 | }; |
| 1310 | assert_eq!(mention_names(children), vec!["Ada Lovelace"]); |
| 1311 | } |
| 1312 | |
| 1313 | #[test] |
| 1314 | fn old_mention_json_without_ids_merges_users_by_position() { |
| 1315 | let json = r#"[{"user_id":"U1","name":"Ada"},{"user_id":"U1","name":"Lovelace"},{"user_id":null,"name":"Tip"},{"user_id":null,"name":"day"}]"#; |
| 1316 | let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Tip</at> <at id="3">day</at>"#; |
| 1317 | let stored = with_mentions(html, json); |
| 1318 | let parsed = mentions(&stored); |
| 1319 | assert_eq!( |
| 1320 | (parsed[1].id, parsed[1].target_id.as_deref()), |
| 1321 | (Some(1), Some("U1")) |
| 1322 | ); |
| 1323 | assert_eq!( |
| 1324 | mention_names(&message_spans(&stored)), |
| 1325 | vec!["Ada Lovelace", "Tip", "day"] |
| 1326 | ); |
| 1327 | } |
| 1328 | |
| 1329 | #[test] |
| 1330 | fn edit_mentions_follow_the_merged_names() { |
| 1331 | let json = r#"[ |
| 1332 | {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}, |
| 1333 | {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"}, |
| 1334 | {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"} |
| 1335 | ]"#; |
| 1336 | let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> and <at id="2">Bob</at>"#; |
| 1337 | assert_eq!( |
| 1338 | user_mention_inputs(&with_mentions(html, json)), |
| 1339 | vec![ |
| 1340 | MentionInput::user("U1", "Ada Lovelace"), |
| 1341 | MentionInput::user("U2", "Bob"), |
| 1342 | ] |
| 1343 | ); |
| 1344 | } |
| 1345 | } |