BlueGit

ict rusty-teams

Files

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

stored.rs

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