BlueGit

ict rusty-teams

Files

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

stored.rs

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