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