BlueGit

ict rusty-teams

Files

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

stored.rs

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