BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / stored.rs

stored.rs

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