BlueGit

ict rusty-teams

Files

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

stored.rs

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