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 teams_app_id: attachment.teams_app_id,
407 });
408 }
409 }
410 preserved
411}
412
413#[derive(Debug, Clone, PartialEq, Eq)]
414pub struct FileCard {
415 pub name: String,
416 pub kind: FileKind,
417 pub content_type: Option<String>,
418 pub size: Option<u64>,
419 pub open_url: String,
420}
421
422impl FileCard {
423 pub fn preview(&self) -> Option<ImageRef> {
424 if !matches!(self.kind, FileKind::Image | FileKind::Video) {
425 return None;
426 }
427 Some(ImageRef {
428 id: format!("file-preview-{}", self.open_url),
429 url: crate::call_event::sharepoint_thumbnail_url(&self.open_url)?,
430 width: None,
431 height: None,
432 alt: Some(self.name.clone()),
433 })
434 }
435}
436
437/// File attachments (`reference` type) with a name and a URL. `size` is rarely known; Graph does not send it for these.
438pub fn files(record: &MessageRecord) -> Vec<FileCard> {
439 let all = attachments(record);
440 all.iter()
441 .filter(|attachment| attachment.is_file())
442 .map(|attachment| FileCard {
443 kind: attachment.file_kind(),
444 name: attachment.name.clone().unwrap_or_default(),
445 content_type: attachment.content_type.clone(),
446 size: attachment.size,
447 open_url: attachment.url.clone().unwrap_or_default(),
448 })
449 .chain(all.iter().filter_map(|attachment| {
450 Some(FileCard {
451 open_url: attachment.loop_component_url()?,
452 kind: FileKind::Loop,
453 name: attachment.name.clone().unwrap_or_else(|| LOOP_CARD_NAME.to_owned()),
454 content_type: attachment.content_type.clone(),
455 size: None,
456 })
457 }))
458 .collect()
459}
460
461/// Text for the clipboard: body and card text, mentions as `@name`, no markup.
462pub fn copy_text(record: &MessageRecord) -> String {
463 let mut text = String::new();
464 push_plain(&mut text, &message_spans(record));
465 for extra_text in forwarded_texts(record).into_iter().chain(card_texts(record)) {
466 text.push('\n');
467 text.push_str(&extra_text);
468 }
469 text.trim().to_owned()
470}
471
472pub fn readable_text(record: &MessageRecord) -> String {
473 if let Some(event) = crate::call_event::call_event(record) {
474 return event.plain_text();
475 }
476 let spans: Vec<Span> = message_spans(record)
477 .into_iter()
478 .filter(|span| !matches!(span, Span::Quote { .. }))
479 .collect();
480 let mut text = String::new();
481 push_plain(&mut text, &spans);
482 text.trim().to_owned()
483}
484
485#[derive(Debug, Clone, PartialEq, Eq)]
486pub struct ReactionSummary {
487 pub emoji: String,
488 pub count: usize,
489 pub mine: bool,
490}
491
492pub fn reaction_summaries(
493 record: &MessageRecord,
494 my_user_id: Option<&str>,
495) -> Vec<ReactionSummary> {
496 let mut summaries: Vec<ReactionSummary> = Vec::new();
497 for reaction in reactions(record) {
498 let emoji = base_reaction_emoji(&reaction.reaction_type);
499 let position = match summaries.iter().position(|summary| summary.emoji == emoji) {
500 Some(position) => position,
501 None => {
502 summaries.push(ReactionSummary {
503 emoji,
504 count: 0,
505 mine: false,
506 });
507 summaries.len() - 1
508 }
509 };
510 let summary = &mut summaries[position];
511 summary.count += 1;
512 summary.mine |= my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id;
513 }
514 summaries
515}
516
517fn base_reaction_emoji(reaction_type: &str) -> String {
518 let legacy = match reaction_type {
519 "like" => "\u{1F44D}",
520 "heart" => "\u{2764}",
521 "laugh" => "\u{1F606}",
522 "surprised" => "\u{1F62E}",
523 "sad" => "\u{1F641}",
524 "angry" => "\u{1F620}",
525 other => other,
526 };
527 legacy
528 .chars()
529 .filter(|character| {
530 *character != '\u{FE0F}' && !('\u{1F3FB}'..='\u{1F3FF}').contains(character)
531 })
532 .collect()
533}
534
535pub(crate) fn push_plain(text: &mut String, spans: &[Span]) {
536 for span in spans {
537 match span {
538 Span::Text(value) | Span::Code(value) => text.push_str(value),
539 Span::CodeBlock { code, .. } => {
540 text.push_str(code);
541 text.push('\n');
542 }
543 Span::Bold(children)
544 | Span::Italic(children)
545 | Span::Strike(children)
546 | Span::Superscript(children)
547 | Span::Subscript(children)
548 | Span::Sized(_, children)
549 | Span::Underline(children)
550 | Span::Colored { children, .. }
551 | Span::Indent { children, .. }
552 | Span::Quote { children, .. }
553 | Span::BlockQuote(children)
554 | Span::Link { children, .. } => push_plain(text, children),
555 Span::Heading { children, .. } => {
556 push_plain(text, children);
557 text.push('\n');
558 }
559 Span::Mention { name, .. } => {
560 text.push('@');
561 text.push_str(name);
562 }
563 Span::LineBreak | Span::Rule => text.push('\n'),
564 Span::List {
565 ordered,
566 start,
567 items,
568 } => {
569 for (offset, item) in items.iter().enumerate() {
570 if *ordered {
571 text.push_str(&format!("{}. ", *start as usize + offset));
572 } else {
573 text.push_str("- ");
574 }
575 push_plain(text, item);
576 text.push('\n');
577 }
578 }
579 Span::Table { rows, .. } => {
580 for row in rows {
581 for (index, cell) in row.iter().enumerate() {
582 if index > 0 {
583 text.push('\t');
584 }
585 push_plain(text, cell);
586 }
587 text.push('\n');
588 }
589 }
590 Span::Image { .. } => {}
591 Span::CustomEmoji { name, .. } => {
592 text.push(':');
593 text.push_str(name);
594 text.push(':');
595 }
596 }
597 }
598}
599
600/// Own, not deleted. Whether the conversation supports the write is the engine's call.
601pub fn can_edit(record: &MessageRecord, my_user_id: &str) -> bool {
602 !record.deleted && record.sender_id.as_deref() == Some(my_user_id)
603}
604
605pub fn can_delete(record: &MessageRecord, my_user_id: &str) -> bool {
606 can_edit(record, my_user_id)
607}
608
609/// Position in the message plus an FNV-1a hash of the URL, so two GIFs from the same host never share an id.
610fn image_id(position: usize, url: &str) -> String {
611 let hash = url.bytes().fold(0x811c_9dc5_u32, |hash, byte| {
612 (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193)
613 });
614 format!("{position}-{hash:08x}")
615}
616
617fn dimension(attribute: Option<&str>, style: &str, property: &str) -> Option<u32> {
618 let from_style = || {
619 style.split(';').find_map(|declaration| {
620 let (name, value) = declaration.split_once(':')?;
621 (name.trim() == property).then(|| leading_number(value))?
622 })
623 };
624 attribute
625 .and_then(leading_number)
626 .or_else(from_style)
627 .filter(|pixels| *pixels > 0)
628}
629
630fn leading_number(text: &str) -> Option<u32> {
631 let digits: String = text
632 .trim()
633 .chars()
634 .take_while(char::is_ascii_digit)
635 .collect();
636 digits.parse().ok()
637}
638
639pub fn message_spans(record: &MessageRecord) -> Vec<Span> {
640 spans_with_mentions(record, &mentions(record))
641}
642
643pub const PROFILE_LINK_PREFIX: &str = "teams-profile:";
644
645/// Like `message_spans`, with the id of each user mention replaced by a profile link.
646pub fn linked_message_spans(record: &MessageRecord) -> Vec<Span> {
647 linked_message_spans_with(record, &|_| None, &no_forward_header)
648}
649
650/// 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.
651pub fn linked_message_spans_with(
652 record: &MessageRecord,
653 quoted_text: &dyn Fn(&str) -> Option<String>,
654 forward_header: &dyn Fn(&ForwardInfo) -> ForwardHeader,
655) -> Vec<Span> {
656 let infos = mentions(record);
657 let html = inline_forwards(record, with_inline_quotes(record, quoted_text), forward_header);
658 let mut spans = html_to_spans(&html);
659 merge_split_mentions(&mut spans, &infos);
660 link_user_mentions(&mut spans, &infos);
661 spans
662}
663
664/// The spans of `record` with its body replaced by the translated html.
665pub fn translated_spans(
666 record: &MessageRecord,
667 translated_html: &str,
668 forward_header: &dyn Fn(&ForwardInfo) -> ForwardHeader,
669) -> Vec<Span> {
670 let mut translated = record.clone();
671 translated.body_html = translated_html.to_owned();
672 linked_message_spans_with(&translated, &|_| None, forward_header)
673}
674
675fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) {
676 for span in spans {
677 match span {
678 Span::Bold(children)
679 | Span::Italic(children)
680 | Span::Strike(children)
681 | Span::Superscript(children)
682 | Span::Subscript(children)
683 | Span::Sized(_, children)
684 | Span::Underline(children)
685 | Span::Colored { children, .. }
686 | Span::Indent { children, .. }
687 | Span::Heading { children, .. }
688 | Span::Quote { children, .. }
689 | Span::BlockQuote(children)
690 | Span::Link { children, .. } => link_user_mentions(children, infos),
691 Span::List { items, .. } => items
692 .iter_mut()
693 .for_each(|item| link_user_mentions(item, infos)),
694 Span::Table { rows, .. } => rows
695 .iter_mut()
696 .flatten()
697 .for_each(|cell| link_user_mentions(cell, infos)),
698 Span::Mention { id, .. } => {
699 let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok());
700 let user_id = infos
701 .iter()
702 .find(|info| parsed.is_some() && info.id == parsed)
703 .and_then(|info| info.user_id.as_deref());
704 if let Some(user_id) = user_id {
705 *id = Some(format!("{PROFILE_LINK_PREFIX}{user_id}"));
706 }
707 }
708 _ => {}
709 }
710 }
711}
712
713fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> {
714 let mut spans = html_to_spans(&with_inline_quotes(record, &|_| None));
715 merge_split_mentions(&mut spans, infos);
716 spans
717}
718
719fn with_inline_quotes(record: &MessageRecord, quoted_text: &dyn Fn(&str) -> Option<String>) -> String {
720 let mut html = record.body_html.clone();
721 for attachment in attachments(record) {
722 let Some(mut quote) = attachment.quote else {
723 continue;
724 };
725 if let Some(text) = quoted_text(&quote.message_id).filter(|text| !text.trim().is_empty()) {
726 quote.preview = text;
727 }
728 let id = attachment.id.unwrap_or_else(|| quote.message_id.clone());
729 let tag = format!("<attachment id=\"{id}\"></attachment>");
730 let block = quote_html(&quote);
731 if html.contains(&tag) {
732 html = html.replacen(&tag, &block, 1);
733 } else {
734 html.insert_str(0, &block);
735 }
736 }
737 html
738}
739
740pub fn quote_html(quote: &QuoteInfo) -> String {
741 let sender = quote
742 .sender_name
743 .as_deref()
744 .map(|name| format!("<strong itemprop=\"mri\">{}</strong>", escape_html(name)))
745 .unwrap_or_default();
746 let time = quote_time(&quote.message_id)
747 .map(|time| format!(" <span itemprop=\"time\">{time}</span>"))
748 .unwrap_or_default();
749 let preview = escape_html(quote.preview.trim()).replace('\n', "<br>");
750 format!(
751 "<blockquote itemscope=\"\" itemtype=\"http://{REPLY_ITEMTYPE}\" itemid=\"{}\">{sender}{time}<p itemprop=\"preview\">{preview}</p></blockquote>",
752 escape_html(&quote.message_id),
753 )
754}
755
756fn quote_time(message_id: &str) -> Option<String> {
757 let millis = message_id.parse::<i64>().ok()?;
758 let time = chrono::DateTime::from_timestamp_millis(millis)?;
759 Some(time.with_timezone(&chrono::Local).format("%d/%m/%Y %H:%M").to_string())
760}
761
762pub fn user_mention_inputs(record: &MessageRecord) -> Vec<MentionInput> {
763 let infos = mentions(record);
764 let mut inputs = Vec::new();
765 collect_user_mentions(&spans_with_mentions(record, &infos), &infos, &mut inputs);
766 inputs
767}
768
769fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec<MentionInput>) {
770 for span in spans {
771 match span {
772 Span::Bold(children)
773 | Span::Italic(children)
774 | Span::Strike(children)
775 | Span::Superscript(children)
776 | Span::Subscript(children)
777 | Span::Sized(_, children)
778 | Span::Underline(children)
779 | Span::Colored { children, .. }
780 | Span::Indent { children, .. }
781 | Span::Heading { children, .. }
782 | Span::Quote { children, .. }
783 | Span::BlockQuote(children)
784 | Span::Link { children, .. } => collect_user_mentions(children, infos, inputs),
785 Span::List { items, .. } => items
786 .iter()
787 .for_each(|item| collect_user_mentions(item, infos, inputs)),
788 Span::Table { rows, .. } => rows
789 .iter()
790 .flatten()
791 .for_each(|cell| collect_user_mentions(cell, infos, inputs)),
792 Span::Mention { name, id } => {
793 let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok());
794 let user_id = infos
795 .iter()
796 .find(|info| parsed.is_some() && info.id == parsed)
797 .and_then(|info| info.user_id.as_deref());
798 if let Some(user_id) = user_id {
799 inputs.push(MentionInput::user(user_id, name));
800 }
801 }
802 _ => {}
803 }
804 }
805}
806
807fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {
808 let target_of = |id: &Option<String>| -> Option<String> {
809 let parsed: i64 = id.as_deref()?.parse().ok()?;
810 mentions
811 .iter()
812 .find(|info| info.id == Some(parsed))?
813 .target_id
814 .clone()
815 };
816 let mut merged: Vec<Span> = Vec::with_capacity(spans.len());
817 for mut span in std::mem::take(spans) {
818 match &mut span {
819 Span::Bold(children)
820 | Span::Italic(children)
821 | Span::Strike(children)
822 | Span::Superscript(children)
823 | Span::Subscript(children)
824 | Span::Sized(_, children)
825 | Span::Underline(children)
826 | Span::Colored { children, .. }
827 | Span::Indent { children, .. }
828 | Span::Heading { children, .. }
829 | Span::Quote { children, .. }
830 | Span::BlockQuote(children)
831 | Span::Link { children, .. } => merge_split_mentions(children, mentions),
832 Span::List { items, .. } => items
833 .iter_mut()
834 .for_each(|item| merge_split_mentions(item, mentions)),
835 Span::Table { rows, .. } => rows
836 .iter_mut()
837 .flatten()
838 .for_each(|cell| merge_split_mentions(cell, mentions)),
839 Span::Mention { name, id } => {
840 let continues = match merged.as_slice() {
841 [
842 ..,
843 Span::Mention {
844 id: previous_id, ..
845 },
846 Span::Text(gap),
847 ] => {
848 gap.trim().is_empty()
849 && target_of(id).is_some()
850 && target_of(previous_id) == target_of(id)
851 }
852 _ => false,
853 };
854 if continues {
855 merged.pop();
856 if let Some(Span::Mention {
857 name: previous_name,
858 ..
859 }) = merged.last_mut()
860 {
861 previous_name.push(' ');
862 previous_name.push_str(name);
863 }
864 continue;
865 }
866 }
867 _ => {}
868 }
869 merged.push(span);
870 }
871 *spans = merged;
872}
873
874#[cfg(test)]
875mod tests {
876 use chrono::Utc;
877
878 use super::*;
879
880 fn record(body_html: &str, attachments_json: &str) -> MessageRecord {
881 MessageRecord {
882 subject: None,
883 conversation_id: "c".to_owned(),
884 message_id: "m".to_owned(),
885 reply_to_id: None,
886 sender_id: Some("u".to_owned()),
887 sender_name: None,
888 sender_application_id: None,
889 links_json: "[]".to_owned(),
890 created_at: Utc::now(),
891 edited_at: None,
892 deleted: false,
893 body_html: body_html.to_owned(),
894 attachments_json: attachments_json.to_owned(),
895 reactions_json: "[]".to_owned(),
896 mentions_json: "[]".to_owned(),
897 call_event_json: None,
898 importance: Default::default(),
899 }
900 }
901
902 #[test]
903 fn reaction_without_created_at_still_parses() {
904 let mut stored = record("", "[]");
905 stored.reactions_json =
906 r#"[{"reaction_type":"like","user_id":"u","user_name":null}]"#.to_owned();
907 let parsed = reactions(&stored);
908 assert_eq!(parsed.len(), 1);
909 assert_eq!(parsed[0].created_at, None);
910 }
911
912 #[test]
913 fn images_cover_hosted_contents_and_ams_and_skip_emoji() {
914 let html = concat!(
915 r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,
916 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">"#,
917 r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,
918 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
919 );
920 let found = images(&record(html, "[]"));
921 assert_eq!(found.len(), 2);
922 assert_eq!((found[0].width, found[0].height), (Some(300), Some(120)));
923 assert_eq!((found[1].width, found[1].height), (Some(64), None));
924 assert!(found[0].id.starts_with("0-"));
925 assert!(found[1].id.starts_with("1-"));
926 }
927
928 #[test]
929 fn two_giphy_gifs_get_different_image_ids_and_the_gif_kind() {
930 let html = concat!(
931 r#"<img src="https://media0.giphy.com/media/abc/giphy.gif" alt=" dancing cat ">"#,
932 r#"<img src="https://media1.giphy.com/media/def/giphy.gif">"#,
933 r#"<img src="https://statics.teams.cdn.office.net/evergreen-assets/stickerassets/a/b.gif">"#,
934 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
935 );
936 let found = images(&record(html, "[]"));
937 let ids: std::collections::HashSet<&str> =
938 found.iter().map(|image| image.id.as_str()).collect();
939 assert_eq!(ids.len(), 4);
940 assert_eq!(found[0].id, images(&record(html, "[]"))[0].id);
941 assert_eq!(found[0].alt.as_deref(), Some("dancing cat"));
942 assert_eq!(found[1].alt, None);
943 let kinds: Vec<ImageKind> = found.iter().map(ImageRef::kind).collect();
944 assert_eq!(
945 kinds,
946 [
947 ImageKind::Gif,
948 ImageKind::Gif,
949 ImageKind::Sticker,
950 ImageKind::Inline
951 ]
952 );
953 }
954
955 #[test]
956 fn readable_text_keeps_lines_lists_code_and_mentions_and_drops_the_reply_quote() {
957 let html = concat!(
958 r#"<blockquote itemscope="" itemtype="http://schema.skype.com/Reply" itemid="Q0"><strong itemprop="mri">Bob</strong><p itemprop="preview">old words</p></blockquote>"#,
959 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>"#,
960 );
961 let json = r#"[{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}]"#;
962 let text = readable_text(&with_mentions(html, json));
963 assert!(!text.contains("old words"), "{text}");
964 assert!(!text.contains("Bob"), "{text}");
965 assert!(text.starts_with("Hi @Ada\n"), "{text}");
966 assert!(text.contains("- one\n- two\n"), "{text}");
967 assert!(text.contains("let x = 1;\n"), "{text}");
968 assert!(text.ends_with("last"), "{text}");
969 }
970
971 #[test]
972 fn a_quote_keeps_its_lines_and_shows_when_the_quoted_message_was_sent() {
973 let html = quote_html(&QuoteInfo {
974 message_id: "1760517360000".to_owned(),
975 preview: "first link\nsecond link".to_owned(),
976 sender_name: Some("Ada".to_owned()),
977 });
978 assert!(html.contains("first link<br>second link"), "{html}");
979 assert!(html.contains("/2025 "), "{html}");
980 let without_time = quote_html(&QuoteInfo {
981 message_id: "Q9".to_owned(),
982 preview: "text".to_owned(),
983 sender_name: None,
984 });
985 assert!(!without_time.contains("itemprop=\"time\""), "{without_time}");
986 }
987
988 #[test]
989 fn a_reply_blockquote_in_the_body_becomes_the_quote() {
990 let html = format!(
991 "{}<p>answer</p>",
992 quote_html(&QuoteInfo {
993 message_id: "Q9".to_owned(),
994 preview: "a < b".to_owned(),
995 sender_name: Some("Ada".to_owned()),
996 })
997 );
998 let stored = record(&html, "[]");
999 assert_eq!(
1000 message_quote(&stored),
1001 Some(QuoteInfo {
1002 message_id: "Q9".to_owned(),
1003 preview: "a < b".to_owned(),
1004 sender_name: Some("Ada".to_owned()),
1005 })
1006 );
1007 assert_eq!(readable_text(&stored), "answer");
1008 assert_eq!(message_quote(&record("<p>plain</p>", "[]")), None);
1009 }
1010
1011 #[test]
1012 fn a_reply_blockquote_nested_in_a_normal_blockquote_is_not_the_quote() {
1013 let html = format!(
1014 "<blockquote>{}</blockquote><p>answer</p>",
1015 quote_html(&QuoteInfo {
1016 message_id: "Q9".to_owned(),
1017 preview: "inner".to_owned(),
1018 sender_name: None,
1019 })
1020 );
1021 assert_eq!(message_quote(&record(&html, "[]")), None);
1022 }
1023
1024 #[test]
1025 fn readable_text_drops_the_stored_quote_and_card_text() {
1026 let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","quote":{"message_id":"Q1","preview":"quoted","sender_name":"Ada"}}]"#;
1027 let stored = record("<attachment id=\"Q1\"></attachment><p>answer</p>", json);
1028 assert_eq!(readable_text(&stored), "answer");
1029 }
1030
1031 #[test]
1032 fn reactions_group_by_base_emoji_and_merge_skin_tones() {
1033 let mut stored = record("", "[]");
1034 stored.reactions_json = r#"[
1035 {"reaction_type":"like","user_id":"a"},
1036 {"reaction_type":"\ud83d\udc4d\ud83c\udffd","user_id":"me"},
1037 {"reaction_type":"\ud83d\udc4d","user_id":"b"},
1038 {"reaction_type":"heart","user_id":"a"},
1039 {"reaction_type":"\u2764\ufe0f","user_id":"c"}
1040 ]"#
1041 .to_owned();
1042 let summaries = reaction_summaries(&stored, Some("me"));
1043 assert_eq!(
1044 summaries,
1045 vec![
1046 ReactionSummary {
1047 emoji: "\u{1F44D}".to_owned(),
1048 count: 3,
1049 mine: true
1050 },
1051 ReactionSummary {
1052 emoji: "\u{2764}".to_owned(),
1053 count: 2,
1054 mine: false
1055 },
1056 ]
1057 );
1058 assert!(
1059 reaction_summaries(&stored, None)
1060 .iter()
1061 .all(|summary| !summary.mine)
1062 );
1063 }
1064
1065 #[test]
1066 fn deleted_messages_have_no_images() {
1067 let mut deleted = record(r#"<img src="https://x/y">"#, "[]");
1068 deleted.deleted = true;
1069 assert!(images(&deleted).is_empty());
1070 }
1071
1072 #[test]
1073 fn edits_keep_images_and_match_files_to_their_attachment_tags() {
1074 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>";
1075 let attachments = r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"G1"}]"#;
1076 let preserved = edit_preserved(&record(html, attachments));
1077 assert!(
1078 preserved
1079 .images_html
1080 .starts_with("<p><img src=\"https://graph.microsoft.com/")
1081 );
1082 assert!(!preserved.images_html.contains("text"));
1083 assert_eq!(preserved.files.len(), 1);
1084 assert_eq!(preserved.files[0].attachment_id, "G1");
1085 assert_eq!(preserved.files[0].content_url, "https://x/a.pdf");
1086 assert_eq!(preserved.files[0].name, "a.pdf");
1087 assert!(preserved.kept.is_empty());
1088 }
1089
1090 const QUOTED_HTML: &str =
1091 "<attachment id=\"Q1\"></attachment><p>answer</p><attachment id=\"F1\"></attachment>";
1092
1093 #[test]
1094 fn a_quoted_reply_keeps_its_quote_and_pairs_the_file_by_id() {
1095 let attachments = r#"[
1096 {"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}},
1097 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"F1"}
1098 ]"#;
1099 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
1100 assert_eq!(preserved.files.len(), 1);
1101 assert_eq!(preserved.files[0].attachment_id, "F1");
1102 assert_eq!(preserved.kept.len(), 1);
1103 assert_eq!(preserved.kept[0].id, "Q1");
1104 assert_eq!(
1105 preserved.kept[0].content_type.as_deref(),
1106 Some("messageReference")
1107 );
1108 assert!(
1109 preserved.kept[0]
1110 .content
1111 .as_deref()
1112 .unwrap()
1113 .contains("messagePreview")
1114 );
1115 }
1116
1117 #[test]
1118 fn records_cached_before_content_was_stored_leave_the_quote_out() {
1119 let attachments = r#"[
1120 {"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}},
1121 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null}
1122 ]"#;
1123 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
1124 assert_eq!(preserved.files[0].attachment_id, "F1");
1125 assert!(preserved.kept.is_empty());
1126 }
1127
1128 #[test]
1129 fn sharepoint_videos_and_images_get_a_graph_thumbnail() {
1130 let card = |name: &str, url: &str| FileCard {
1131 name: name.to_owned(),
1132 kind: FileKind::from_name(name),
1133 content_type: Some("reference".to_owned()),
1134 size: None,
1135 open_url: url.to_owned(),
1136 };
1137 let sharepoint = "https://contoso.sharepoint.com/personal/a/Documents/clip.mp4";
1138 let preview = card("clip.mp4", sharepoint).preview().unwrap();
1139 assert!(preview.url.starts_with("https://graph.microsoft.com/v1.0/shares/u!"));
1140 assert!(preview.url.ends_with("/driveItem/thumbnails/0/large/content"));
1141 assert!(card("shot.PNG", sharepoint).preview().is_some());
1142 assert_eq!(card("plan.docx", sharepoint).preview(), None);
1143 assert_eq!(card("clip.mov", "https://example.com/clip.mov").preview(), None);
1144 }
1145
1146 #[test]
1147 fn file_kind_follows_the_extension_then_the_content_type() {
1148 let kind = |name: Option<&str>, content_type: &str| {
1149 AttachmentInfo {
1150 content_type: Some(content_type.to_owned()),
1151 name: name.map(str::to_owned),
1152 url: None,
1153 text: None,
1154 size: None,
1155 quote: None,
1156 id: None,
1157 content: None,
1158 unavailable: false,
1159 teams_app_id: None,
1160 }
1161 .file_kind()
1162 };
1163 assert_eq!(kind(Some("Plan.DOCX"), "reference"), FileKind::Word);
1164 assert_eq!(kind(Some("a.xlsx"), "reference"), FileKind::Excel);
1165 assert_eq!(kind(Some("a.pptx"), "reference"), FileKind::PowerPoint);
1166 assert_eq!(kind(Some("a.pdf"), "reference"), FileKind::Pdf);
1167 assert_eq!(kind(Some("a.PNG"), "reference"), FileKind::Image);
1168 assert_eq!(kind(Some("a.zip"), "reference"), FileKind::Archive);
1169 assert_eq!(kind(Some("a.bin"), "reference"), FileKind::Other);
1170 assert_eq!(kind(None, "image/png"), FileKind::Image);
1171 assert_eq!(kind(Some("noextension"), "reference"), FileKind::Other);
1172 }
1173
1174 #[test]
1175 fn files_expose_name_kind_and_open_url() {
1176 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}]"#;
1177 let found = files(&record("", json));
1178 assert_eq!(found.len(), 1);
1179 assert_eq!(
1180 (found[0].name.as_str(), found[0].kind),
1181 ("Plan.docx", FileKind::Word)
1182 );
1183 assert_eq!(found[0].open_url, "https://x/Plan.docx");
1184 assert_eq!(found[0].size, None);
1185 }
1186
1187 #[test]
1188 fn a_loop_component_opens_its_component_url() {
1189 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\"}"}]"#;
1190 let found = files(&record("", json));
1191 assert_eq!(found.len(), 1);
1192 assert_eq!(
1193 (found[0].name.as_str(), found[0].kind, found[0].open_url.as_str()),
1194 ("Loop component", FileKind::Loop, "https://x/loop.fluid")
1195 );
1196 }
1197
1198 #[test]
1199 fn copy_text_flattens_markup_and_keeps_mentions_and_lines() {
1200 let html = r#"<p>Hi <at id="0">Ada</at>, <b>look</b></p><p>second <a href="https://x">link</a></p>"#;
1201 let text = copy_text(&record(html, "[]"));
1202 assert!(text.starts_with("Hi @Ada, look"), "{text}");
1203 assert!(text.contains("second link"), "{text}");
1204 assert!(text.contains('\n'));
1205 }
1206
1207 #[test]
1208 fn an_attachment_listed_twice_shows_once() {
1209 let card = r#"{"content_type":"application/vnd.microsoft.card.adaptive","name":null,"url":null,"text":"Jira","id":"app-preview-card-1"}"#;
1210 let file = r#"{"content_type":"reference","name":"a.pdf","url":"u","text":null}"#;
1211 let parsed = attachments(&record("", &format!("[{card},{card},{file},{file}]")));
1212 assert_eq!(parsed.len(), 3);
1213 }
1214
1215 #[test]
1216 fn old_cached_attachments_still_parse() {
1217 let parsed = attachments(&record(
1218 "",
1219 r#"[{"content_type":"reference","name":"a.pdf","url":"u","text":null}]"#,
1220 ));
1221 assert_eq!(parsed.len(), 1);
1222 assert!(parsed[0].is_file());
1223 assert_eq!(parsed[0].size, None);
1224 }
1225
1226 #[test]
1227 fn quote_references_are_extracted_from_the_message_reference_attachment() {
1228 let attachment = graph::Attachment {
1229 id: Some("1".to_owned()),
1230 content_type: Some("messageReference".to_owned()),
1231 content_url: None,
1232 name: None,
1233 teams_app_id: None,
1234 content: Some(
1235 r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),
1236 ),
1237 };
1238 let info = crate::mapping::attachment_info(&attachment);
1239 assert_eq!(
1240 info.quote,
1241 Some(QuoteInfo {
1242 message_id: "1728".to_owned(),
1243 preview: "Hello".to_owned(),
1244 sender_name: Some("Adele".to_owned())
1245 })
1246 );
1247 let stored = record("", &serde_json::to_string(&[info]).unwrap());
1248 assert_eq!(quotes(&stored).len(), 1);
1249 }
1250
1251 #[test]
1252 fn a_message_reference_renders_as_a_reply_quote_where_its_tag_sits() {
1253 let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","quote":{"message_id":"Q1","preview":"a < b","sender_name":"Ada"}}]"#;
1254 let stored = record(
1255 "<p></p><attachment id=\"Q1\"></attachment>\ntest<p></p>",
1256 json,
1257 );
1258 let spans = message_spans(&stored);
1259 let Some(Span::Quote { children, .. }) = spans.first() else {
1260 panic!("expected a reply quote first, got {spans:?}");
1261 };
1262 let mut quoted = String::new();
1263 push_plain(&mut quoted, children);
1264 assert!(quoted.contains("Ada"));
1265 assert!(quoted.contains("a < b"));
1266 let mut own = String::new();
1267 push_plain(&mut own, &spans[1..]);
1268 assert_eq!(own.trim(), "test");
1269 }
1270
1271 #[test]
1272 fn a_message_reference_without_its_tag_still_shows_the_quote() {
1273 let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}}]"#;
1274 let spans = message_spans(&record("<p>answer</p>", json));
1275 assert!(matches!(spans.first(), Some(Span::Quote { .. })));
1276 }
1277
1278 fn with_mentions(body_html: &str, mentions_json: &str) -> MessageRecord {
1279 let mut stored = record(body_html, "[]");
1280 stored.mentions_json = mentions_json.to_owned();
1281 stored
1282 }
1283
1284 fn mention_names(spans: &[Span]) -> Vec<&str> {
1285 spans
1286 .iter()
1287 .filter_map(|span| match span {
1288 Span::Mention { name, .. } => Some(name.as_str()),
1289 _ => None,
1290 })
1291 .collect()
1292 }
1293
1294 #[test]
1295 fn user_mentions_link_to_their_profile_and_groups_do_not() {
1296 let json = r#"[
1297 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1298 {"user_id":null,"name":"Team","id":1,"target_id":"T1"}
1299 ]"#;
1300 let html = r#"<at id="0">Ada</at> <at id="1">Team</at>"#;
1301 let ids: Vec<Option<String>> = linked_message_spans(&with_mentions(html, json))
1302 .into_iter()
1303 .filter_map(|span| match span {
1304 Span::Mention { id, .. } => Some(id),
1305 _ => None,
1306 })
1307 .collect();
1308 assert_eq!(
1309 ids,
1310 vec![Some("teams-profile:U1".to_owned()), Some("1".to_owned())]
1311 );
1312 }
1313
1314 #[test]
1315 fn a_tag_mention_split_per_word_merges_into_one() {
1316 let json = r#"[
1317 {"user_id":null,"name":"Tip","id":0,"target_id":"T1"},
1318 {"user_id":null,"name":"of","id":1,"target_id":"T1"},
1319 {"user_id":null,"name":"the","id":2,"target_id":"T1"},
1320 {"user_id":null,"name":"day","id":3,"target_id":"T1"}
1321 ]"#;
1322 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>"#;
1323 let spans = message_spans(&with_mentions(html, json));
1324 assert_eq!(mention_names(&spans), vec!["Tip of the day"]);
1325 assert_eq!(
1326 copy_text(&with_mentions(html, json)),
1327 "Hey @Tip of the day!"
1328 );
1329 }
1330
1331 #[test]
1332 fn a_two_word_user_name_merges_but_different_users_stay_apart() {
1333 let json = r#"[
1334 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1335 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
1336 {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
1337 ]"#;
1338 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Bob</at>"#;
1339 let spans = message_spans(&with_mentions(html, json));
1340 assert_eq!(mention_names(&spans), vec!["Ada Lovelace", "Bob"]);
1341 }
1342
1343 #[test]
1344 fn different_users_next_to_each_other_stay_two_mentions() {
1345 let json = r#"[
1346 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1347 {"user_id":"U2","name":"Bob","id":1,"target_id":"U2"}
1348 ]"#;
1349 let html = r#"<at id="0">Ada</at> <at id="1">Bob</at>"#;
1350 let spans = message_spans(&with_mentions(html, json));
1351 assert_eq!(mention_names(&spans), vec!["Ada", "Bob"]);
1352 }
1353
1354 #[test]
1355 fn nested_split_mentions_merge() {
1356 let json = r#"[
1357 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1358 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"}
1359 ]"#;
1360 let html = r#"<b><at id="0">Ada</at> <at id="1">Lovelace</at></b>"#;
1361 let spans = message_spans(&with_mentions(html, json));
1362 let [Span::Bold(children)] = spans.as_slice() else {
1363 panic!("bold expected: {spans:?}")
1364 };
1365 assert_eq!(mention_names(children), vec!["Ada Lovelace"]);
1366 }
1367
1368 #[test]
1369 fn old_mention_json_without_ids_merges_users_by_position() {
1370 let json = r#"[{"user_id":"U1","name":"Ada"},{"user_id":"U1","name":"Lovelace"},{"user_id":null,"name":"Tip"},{"user_id":null,"name":"day"}]"#;
1371 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Tip</at> <at id="3">day</at>"#;
1372 let stored = with_mentions(html, json);
1373 let parsed = mentions(&stored);
1374 assert_eq!(
1375 (parsed[1].id, parsed[1].target_id.as_deref()),
1376 (Some(1), Some("U1"))
1377 );
1378 assert_eq!(
1379 mention_names(&message_spans(&stored)),
1380 vec!["Ada Lovelace", "Tip", "day"]
1381 );
1382 }
1383
1384 #[test]
1385 fn edit_mentions_follow_the_merged_names() {
1386 let json = r#"[
1387 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1388 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
1389 {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
1390 ]"#;
1391 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> and <at id="2">Bob</at>"#;
1392 assert_eq!(
1393 user_mention_inputs(&with_mentions(html, json)),
1394 vec![
1395 MentionInput::user("U1", "Ada Lovelace"),
1396 MentionInput::user("U2", "Bob"),
1397 ]
1398 );
1399 }
1400}