BlueGit

ict rusty-teams

Files

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

stored.rs

stored.rs 55.6 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(
823 &spans_with_mentions(record, &infos),
824 &infos,
825 None,
826 &mut inputs,
827 );
828 inputs
829}
830
831/// For editing a channel message: the user mentions plus a mention of the channel itself.
832pub fn channel_mention_inputs(record: &MessageRecord) -> Vec<MentionInput> {
833 let infos = mentions(record);
834 let mut inputs = Vec::new();
835 let channel = Some(record.conversation_id.as_str());
836 collect_user_mentions(
837 &spans_with_mentions(record, &infos),
838 &infos,
839 channel,
840 &mut inputs,
841 );
842 inputs
843}
844
845fn collect_user_mentions(
846 spans: &[Span],
847 infos: &[MentionInfo],
848 channel: Option<&str>,
849 inputs: &mut Vec<MentionInput>,
850) {
851 for span in spans {
852 match span {
853 Span::Bold(children)
854 | Span::Italic(children)
855 | Span::Strike(children)
856 | Span::Superscript(children)
857 | Span::Subscript(children)
858 | Span::Sized(_, children)
859 | Span::Underline(children)
860 | Span::Colored { children, .. }
861 | Span::Indent { children, .. }
862 | Span::Heading { children, .. }
863 | Span::Quote { children, .. }
864 | Span::BlockQuote(children)
865 | Span::Link { children, .. } => {
866 collect_user_mentions(children, infos, channel, inputs)
867 }
868 Span::List { items, .. } => items
869 .iter()
870 .for_each(|item| collect_user_mentions(item, infos, channel, inputs)),
871 Span::Table { rows, .. } => rows
872 .iter()
873 .flatten()
874 .for_each(|cell| collect_user_mentions(cell, infos, channel, inputs)),
875 Span::Mention { name, id } => {
876 let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok());
877 let info = infos
878 .iter()
879 .find(|info| parsed.is_some() && info.id == parsed);
880 if let Some(user_id) = info.and_then(|info| info.user_id.as_deref()) {
881 inputs.push(MentionInput::user(user_id, name));
882 } else if let Some(channel) = channel
883 && info.is_some_and(|info| {
884 info.group && info.target_id.as_deref() == Some(channel)
885 })
886 {
887 inputs.push(MentionInput::channel(channel, name));
888 }
889 }
890 _ => {}
891 }
892 }
893}
894
895fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {
896 let target_of = |id: &Option<String>| -> Option<String> {
897 let parsed: i64 = id.as_deref()?.parse().ok()?;
898 mentions
899 .iter()
900 .find(|info| info.id == Some(parsed))?
901 .target_id
902 .clone()
903 };
904 let mut merged: Vec<Span> = Vec::with_capacity(spans.len());
905 for mut span in std::mem::take(spans) {
906 match &mut span {
907 Span::Bold(children)
908 | Span::Italic(children)
909 | Span::Strike(children)
910 | Span::Superscript(children)
911 | Span::Subscript(children)
912 | Span::Sized(_, children)
913 | Span::Underline(children)
914 | Span::Colored { children, .. }
915 | Span::Indent { children, .. }
916 | Span::Heading { children, .. }
917 | Span::Quote { children, .. }
918 | Span::BlockQuote(children)
919 | Span::Link { children, .. } => merge_split_mentions(children, mentions),
920 Span::List { items, .. } => items
921 .iter_mut()
922 .for_each(|item| merge_split_mentions(item, mentions)),
923 Span::Table { rows, .. } => rows
924 .iter_mut()
925 .flatten()
926 .for_each(|cell| merge_split_mentions(cell, mentions)),
927 Span::Mention { name, id } => {
928 let continues = match merged.as_slice() {
929 [
930 ..,
931 Span::Mention {
932 id: previous_id, ..
933 },
934 Span::Text(gap),
935 ] => {
936 gap.trim().is_empty()
937 && target_of(id).is_some()
938 && target_of(previous_id) == target_of(id)
939 }
940 _ => false,
941 };
942 if continues {
943 merged.pop();
944 if let Some(Span::Mention {
945 name: previous_name,
946 ..
947 }) = merged.last_mut()
948 {
949 previous_name.push(' ');
950 previous_name.push_str(name);
951 }
952 continue;
953 }
954 }
955 _ => {}
956 }
957 merged.push(span);
958 }
959 *spans = merged;
960}
961
962#[cfg(test)]
963mod tests {
964 use chrono::Utc;
965
966 use super::*;
967
968 fn record(body_html: &str, attachments_json: &str) -> MessageRecord {
969 MessageRecord {
970 subject: None,
971 conversation_id: "c".to_owned(),
972 message_id: "m".to_owned(),
973 reply_to_id: None,
974 sender_id: Some("u".to_owned()),
975 sender_name: None,
976 sender_application_id: None,
977 links_json: "[]".to_owned(),
978 created_at: Utc::now(),
979 edited_at: None,
980 deleted: false,
981 body_html: body_html.to_owned(),
982 attachments_json: attachments_json.to_owned(),
983 reactions_json: "[]".to_owned(),
984 mentions_json: "[]".to_owned(),
985 call_event_json: None,
986 importance: Default::default(),
987 }
988 }
989
990 #[test]
991 fn reaction_without_created_at_still_parses() {
992 let mut stored = record("", "[]");
993 stored.reactions_json =
994 r#"[{"reaction_type":"like","user_id":"u","user_name":null}]"#.to_owned();
995 let parsed = reactions(&stored);
996 assert_eq!(parsed.len(), 1);
997 assert_eq!(parsed[0].created_at, None);
998 }
999
1000 #[test]
1001 fn an_ams_picture_has_a_full_size_view_kept_apart_from_the_inline_one() {
1002 let inline = ImageRef {
1003 id: "0-weu-d1-abc".into(),
1004 url: "https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo".into(),
1005 width: Some(640),
1006 height: Some(360),
1007 alt: Some("image".into()),
1008 };
1009 let full = inline.full_size().unwrap();
1010 assert_eq!(
1011 full.key(),
1012 "https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgpsh_fullsize_anim"
1013 );
1014 assert_ne!(full.key(), inline.key());
1015 assert_eq!((full.width, full.height), (None, None));
1016 assert_eq!(full.full_size(), None);
1017 let external = ImageRef {
1018 url: "https://example.com/a.png".into(),
1019 ..inline
1020 };
1021 assert_eq!(external.full_size(), None);
1022 }
1023
1024 #[test]
1025 fn images_cover_hosted_contents_and_ams_and_skip_emoji() {
1026 let html = concat!(
1027 r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,
1028 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">"#,
1029 r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,
1030 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">"#,
1031 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
1032 );
1033 let found = images(&record(html, "[]"));
1034 assert_eq!(found.len(), 2);
1035 assert_eq!((found[0].width, found[0].height), (Some(300), Some(120)));
1036 assert_eq!((found[1].width, found[1].height), (Some(64), None));
1037 assert!(found[0].id.starts_with("0-"));
1038 assert!(found[1].id.starts_with("1-"));
1039 }
1040
1041 #[test]
1042 fn two_giphy_gifs_get_different_image_ids_and_the_gif_kind() {
1043 let html = concat!(
1044 r#"<img src="https://media0.giphy.com/media/abc/giphy.gif" alt=" dancing cat ">"#,
1045 r#"<img src="https://media1.giphy.com/media/def/giphy.gif">"#,
1046 r#"<img src="https://statics.teams.cdn.office.net/evergreen-assets/stickerassets/a/b.gif">"#,
1047 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
1048 );
1049 let found = images(&record(html, "[]"));
1050 let ids: std::collections::HashSet<&str> =
1051 found.iter().map(|image| image.id.as_str()).collect();
1052 assert_eq!(ids.len(), 4);
1053 assert_eq!(found[0].id, images(&record(html, "[]"))[0].id);
1054 assert_eq!(found[0].alt.as_deref(), Some("dancing cat"));
1055 assert_eq!(found[1].alt, None);
1056 let kinds: Vec<ImageKind> = found.iter().map(ImageRef::kind).collect();
1057 assert_eq!(
1058 kinds,
1059 [
1060 ImageKind::Gif,
1061 ImageKind::Gif,
1062 ImageKind::Sticker,
1063 ImageKind::Inline
1064 ]
1065 );
1066 }
1067
1068 #[test]
1069 fn readable_text_keeps_lines_lists_code_and_mentions_and_drops_the_reply_quote() {
1070 let html = concat!(
1071 r#"<blockquote itemscope="" itemtype="http://schema.skype.com/Reply" itemid="Q0"><strong itemprop="mri">Bob</strong><p itemprop="preview">old words</p></blockquote>"#,
1072 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>"#,
1073 );
1074 let json = r#"[{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}]"#;
1075 let text = readable_text(&with_mentions(html, json));
1076 assert!(!text.contains("old words"), "{text}");
1077 assert!(!text.contains("Bob"), "{text}");
1078 assert!(text.starts_with("Hi @Ada\n"), "{text}");
1079 assert!(text.contains("- one\n- two\n"), "{text}");
1080 assert!(text.contains("let x = 1;\n"), "{text}");
1081 assert!(text.ends_with("last"), "{text}");
1082 }
1083
1084 #[test]
1085 fn a_quote_keeps_its_lines_and_shows_when_the_quoted_message_was_sent() {
1086 let html = quote_html(&QuoteInfo {
1087 message_id: "1760517360000".to_owned(),
1088 preview: "first link\nsecond link".to_owned(),
1089 sender_name: Some("Ada".to_owned()),
1090 });
1091 assert!(html.contains("first link<br>second link"), "{html}");
1092 assert!(html.contains("/2025 "), "{html}");
1093 let without_time = quote_html(&QuoteInfo {
1094 message_id: "Q9".to_owned(),
1095 preview: "text".to_owned(),
1096 sender_name: None,
1097 });
1098 assert!(
1099 !without_time.contains("itemprop=\"time\""),
1100 "{without_time}"
1101 );
1102 }
1103
1104 #[test]
1105 fn a_reply_blockquote_in_the_body_becomes_the_quote() {
1106 let html = format!(
1107 "{}<p>answer</p>",
1108 quote_html(&QuoteInfo {
1109 message_id: "Q9".to_owned(),
1110 preview: "a < b".to_owned(),
1111 sender_name: Some("Ada".to_owned()),
1112 })
1113 );
1114 let stored = record(&html, "[]");
1115 assert_eq!(
1116 message_quote(&stored),
1117 Some(QuoteInfo {
1118 message_id: "Q9".to_owned(),
1119 preview: "a < b".to_owned(),
1120 sender_name: Some("Ada".to_owned()),
1121 })
1122 );
1123 assert_eq!(readable_text(&stored), "answer");
1124 assert_eq!(message_quote(&record("<p>plain</p>", "[]")), None);
1125 }
1126
1127 #[test]
1128 fn a_reply_blockquote_nested_in_a_normal_blockquote_is_not_the_quote() {
1129 let html = format!(
1130 "<blockquote>{}</blockquote><p>answer</p>",
1131 quote_html(&QuoteInfo {
1132 message_id: "Q9".to_owned(),
1133 preview: "inner".to_owned(),
1134 sender_name: None,
1135 })
1136 );
1137 assert_eq!(message_quote(&record(&html, "[]")), None);
1138 }
1139
1140 #[test]
1141 fn readable_text_drops_the_stored_quote_and_card_text() {
1142 let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","quote":{"message_id":"Q1","preview":"quoted","sender_name":"Ada"}}]"#;
1143 let stored = record("<attachment id=\"Q1\"></attachment><p>answer</p>", json);
1144 assert_eq!(readable_text(&stored), "answer");
1145 }
1146
1147 #[test]
1148 fn reactions_group_by_base_emoji_and_merge_skin_tones() {
1149 let mut stored = record("", "[]");
1150 stored.reactions_json = r#"[
1151 {"reaction_type":"like","user_id":"a"},
1152 {"reaction_type":"\ud83d\udc4d\ud83c\udffd","user_id":"me"},
1153 {"reaction_type":"\ud83d\udc4d","user_id":"b"},
1154 {"reaction_type":"heart","user_id":"a"},
1155 {"reaction_type":"\u2764\ufe0f","user_id":"c"}
1156 ]"#
1157 .to_owned();
1158 let summaries = reaction_summaries(&stored, Some("me"));
1159 assert_eq!(
1160 summaries,
1161 vec![
1162 ReactionSummary {
1163 emoji: "\u{1F44D}".to_owned(),
1164 count: 3,
1165 mine: true
1166 },
1167 ReactionSummary {
1168 emoji: "\u{2764}".to_owned(),
1169 count: 2,
1170 mine: false
1171 },
1172 ]
1173 );
1174 assert!(
1175 reaction_summaries(&stored, None)
1176 .iter()
1177 .all(|summary| !summary.mine)
1178 );
1179 }
1180
1181 #[test]
1182 fn deleted_messages_have_no_images() {
1183 let mut deleted = record(r#"<img src="https://x/y">"#, "[]");
1184 deleted.deleted = true;
1185 assert!(images(&deleted).is_empty());
1186 }
1187
1188 #[test]
1189 fn edits_keep_images_and_match_files_to_their_attachment_tags() {
1190 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>";
1191 let attachments = r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"G1"}]"#;
1192 let preserved = edit_preserved(&record(html, attachments));
1193 assert!(
1194 preserved
1195 .images_html
1196 .starts_with("<p><img src=\"https://graph.microsoft.com/")
1197 );
1198 assert!(!preserved.images_html.contains("text"));
1199 assert_eq!(preserved.files.len(), 1);
1200 assert_eq!(preserved.files[0].attachment_id, "G1");
1201 assert_eq!(preserved.files[0].content_url, "https://x/a.pdf");
1202 assert_eq!(preserved.files[0].name, "a.pdf");
1203 assert!(preserved.kept.is_empty());
1204 }
1205
1206 const QUOTED_HTML: &str =
1207 "<attachment id=\"Q1\"></attachment><p>answer</p><attachment id=\"F1\"></attachment>";
1208
1209 #[test]
1210 fn a_quoted_reply_keeps_its_quote_and_pairs_the_file_by_id() {
1211 let attachments = r#"[
1212 {"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}},
1213 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"F1"}
1214 ]"#;
1215 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
1216 assert_eq!(preserved.files.len(), 1);
1217 assert_eq!(preserved.files[0].attachment_id, "F1");
1218 assert_eq!(preserved.kept.len(), 1);
1219 assert_eq!(preserved.kept[0].id, "Q1");
1220 assert_eq!(
1221 preserved.kept[0].content_type.as_deref(),
1222 Some("messageReference")
1223 );
1224 assert!(
1225 preserved.kept[0]
1226 .content
1227 .as_deref()
1228 .unwrap()
1229 .contains("messagePreview")
1230 );
1231 }
1232
1233 #[test]
1234 fn records_cached_before_content_was_stored_leave_the_quote_out() {
1235 let attachments = r#"[
1236 {"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}},
1237 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null}
1238 ]"#;
1239 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
1240 assert_eq!(preserved.files[0].attachment_id, "F1");
1241 assert!(preserved.kept.is_empty());
1242 }
1243
1244 #[test]
1245 fn sharepoint_videos_and_images_get_a_graph_thumbnail() {
1246 let card = |name: &str, url: &str| FileCard {
1247 name: name.to_owned(),
1248 kind: FileKind::from_name(name),
1249 content_type: Some("reference".to_owned()),
1250 size: None,
1251 open_url: url.to_owned(),
1252 };
1253 let sharepoint = "https://contoso.sharepoint.com/personal/a/Documents/clip.mp4";
1254 let preview = card("clip.mp4", sharepoint).preview().unwrap();
1255 assert!(
1256 preview
1257 .url
1258 .starts_with("https://graph.microsoft.com/v1.0/shares/u!")
1259 );
1260 assert!(
1261 preview
1262 .url
1263 .ends_with("/driveItem/thumbnails/0/large/content")
1264 );
1265 assert!(card("shot.PNG", sharepoint).preview().is_some());
1266 assert!(card("plan.docx", sharepoint).preview().is_some());
1267 assert!(card("report.pdf", sharepoint).preview().is_some());
1268 assert_eq!(card("bundle.zip", sharepoint).preview(), None);
1269 assert_eq!(
1270 card("clip.mov", "https://example.com/clip.mov").preview(),
1271 None
1272 );
1273 }
1274
1275 #[test]
1276 fn file_kind_follows_the_extension_then_the_content_type() {
1277 let kind = |name: Option<&str>, content_type: &str| {
1278 AttachmentInfo {
1279 content_type: Some(content_type.to_owned()),
1280 name: name.map(str::to_owned),
1281 url: None,
1282 text: None,
1283 size: None,
1284 quote: None,
1285 id: None,
1286 content: None,
1287 unavailable: false,
1288 teams_app_id: None,
1289 }
1290 .file_kind()
1291 };
1292 assert_eq!(kind(Some("Plan.DOCX"), "reference"), FileKind::Word);
1293 assert_eq!(kind(Some("a.xlsx"), "reference"), FileKind::Excel);
1294 assert_eq!(kind(Some("a.pptx"), "reference"), FileKind::PowerPoint);
1295 assert_eq!(kind(Some("a.pdf"), "reference"), FileKind::Pdf);
1296 assert_eq!(kind(Some("a.PNG"), "reference"), FileKind::Image);
1297 assert_eq!(kind(Some("a.zip"), "reference"), FileKind::Archive);
1298 assert_eq!(kind(Some("a.bin"), "reference"), FileKind::Other);
1299 assert_eq!(kind(None, "image/png"), FileKind::Image);
1300 assert_eq!(kind(Some("noextension"), "reference"), FileKind::Other);
1301 }
1302
1303 #[test]
1304 fn files_expose_name_kind_and_open_url() {
1305 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}]"#;
1306 let found = files(&record("", json));
1307 assert_eq!(found.len(), 1);
1308 assert_eq!(
1309 (found[0].name.as_str(), found[0].kind),
1310 ("Plan.docx", FileKind::Word)
1311 );
1312 assert_eq!(found[0].open_url, "https://x/Plan.docx");
1313 assert_eq!(found[0].size, None);
1314 }
1315
1316 #[test]
1317 fn a_loop_component_opens_its_component_url() {
1318 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\"}"}]"#;
1319 let found = files(&record("", json));
1320 assert_eq!(found.len(), 1);
1321 assert_eq!(
1322 (
1323 found[0].name.as_str(),
1324 found[0].kind,
1325 found[0].open_url.as_str()
1326 ),
1327 ("Loop component", FileKind::Loop, "https://x/loop.fluid")
1328 );
1329 }
1330
1331 #[test]
1332 fn copy_text_flattens_markup_and_keeps_mentions_and_lines() {
1333 let html = r#"<p>Hi <at id="0">Ada</at>, <b>look</b></p><p>second <a href="https://x">link</a></p>"#;
1334 let text = copy_text(&record(html, "[]"));
1335 assert!(text.starts_with("Hi @Ada, look"), "{text}");
1336 assert!(text.contains("second link"), "{text}");
1337 assert!(text.contains('\n'));
1338 }
1339
1340 #[test]
1341 fn an_attachment_listed_twice_shows_once() {
1342 let card = r#"{"content_type":"application/vnd.microsoft.card.adaptive","name":null,"url":null,"text":"Jira","id":"app-preview-card-1"}"#;
1343 let file = r#"{"content_type":"reference","name":"a.pdf","url":"u","text":null}"#;
1344 let parsed = attachments(&record("", &format!("[{card},{card},{file},{file}]")));
1345 assert_eq!(parsed.len(), 3);
1346 }
1347
1348 #[test]
1349 fn old_cached_attachments_still_parse() {
1350 let parsed = attachments(&record(
1351 "",
1352 r#"[{"content_type":"reference","name":"a.pdf","url":"u","text":null}]"#,
1353 ));
1354 assert_eq!(parsed.len(), 1);
1355 assert!(parsed[0].is_file());
1356 assert_eq!(parsed[0].size, None);
1357 }
1358
1359 #[test]
1360 fn quote_references_are_extracted_from_the_message_reference_attachment() {
1361 let attachment = graph::Attachment {
1362 id: Some("1".to_owned()),
1363 content_type: Some("messageReference".to_owned()),
1364 content_url: None,
1365 name: None,
1366 teams_app_id: None,
1367 content: Some(
1368 r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),
1369 ),
1370 };
1371 let info = crate::mapping::attachment_info(&attachment);
1372 assert_eq!(
1373 info.quote,
1374 Some(QuoteInfo {
1375 message_id: "1728".to_owned(),
1376 preview: "Hello".to_owned(),
1377 sender_name: Some("Adele".to_owned())
1378 })
1379 );
1380 let stored = record("", &serde_json::to_string(&[info]).unwrap());
1381 assert_eq!(quotes(&stored).len(), 1);
1382 }
1383
1384 #[test]
1385 fn a_message_reference_renders_as_a_reply_quote_where_its_tag_sits() {
1386 let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","quote":{"message_id":"Q1","preview":"a < b","sender_name":"Ada"}}]"#;
1387 let stored = record(
1388 "<p></p><attachment id=\"Q1\"></attachment>\ntest<p></p>",
1389 json,
1390 );
1391 let spans = message_spans(&stored);
1392 let Some(Span::Quote { children, .. }) = spans.first() else {
1393 panic!("expected a reply quote first, got {spans:?}");
1394 };
1395 let mut quoted = String::new();
1396 push_plain(&mut quoted, children);
1397 assert!(quoted.contains("Ada"));
1398 assert!(quoted.contains("a < b"));
1399 let mut own = String::new();
1400 push_plain(&mut own, &spans[1..]);
1401 assert_eq!(own.trim(), "test");
1402 }
1403
1404 #[test]
1405 fn a_message_reference_without_its_tag_still_shows_the_quote() {
1406 let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}}]"#;
1407 let spans = message_spans(&record("<p>answer</p>", json));
1408 assert!(matches!(spans.first(), Some(Span::Quote { .. })));
1409 }
1410
1411 fn with_mentions(body_html: &str, mentions_json: &str) -> MessageRecord {
1412 let mut stored = record(body_html, "[]");
1413 stored.mentions_json = mentions_json.to_owned();
1414 stored
1415 }
1416
1417 fn mention_names(spans: &[Span]) -> Vec<&str> {
1418 spans
1419 .iter()
1420 .filter_map(|span| match span {
1421 Span::Mention { name, .. } => Some(name.as_str()),
1422 _ => None,
1423 })
1424 .collect()
1425 }
1426
1427 #[test]
1428 fn user_mentions_link_to_their_profile_and_groups_do_not() {
1429 let json = r#"[
1430 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1431 {"user_id":null,"name":"Team","id":1,"target_id":"T1"}
1432 ]"#;
1433 let html = r#"<at id="0">Ada</at> <at id="1">Team</at>"#;
1434 let ids: Vec<Option<String>> = linked_message_spans(&with_mentions(html, json))
1435 .into_iter()
1436 .filter_map(|span| match span {
1437 Span::Mention { id, .. } => Some(id),
1438 _ => None,
1439 })
1440 .collect();
1441 assert_eq!(
1442 ids,
1443 vec![Some("teams-profile:U1".to_owned()), Some("1".to_owned())]
1444 );
1445 }
1446
1447 #[test]
1448 fn a_tag_mention_split_per_word_merges_into_one() {
1449 let json = r#"[
1450 {"user_id":null,"name":"Tip","id":0,"target_id":"T1"},
1451 {"user_id":null,"name":"of","id":1,"target_id":"T1"},
1452 {"user_id":null,"name":"the","id":2,"target_id":"T1"},
1453 {"user_id":null,"name":"day","id":3,"target_id":"T1"}
1454 ]"#;
1455 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>"#;
1456 let spans = message_spans(&with_mentions(html, json));
1457 assert_eq!(mention_names(&spans), vec!["Tip of the day"]);
1458 assert_eq!(
1459 copy_text(&with_mentions(html, json)),
1460 "Hey @Tip of the day!"
1461 );
1462 }
1463
1464 #[test]
1465 fn a_two_word_user_name_merges_but_different_users_stay_apart() {
1466 let json = r#"[
1467 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1468 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
1469 {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
1470 ]"#;
1471 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Bob</at>"#;
1472 let spans = message_spans(&with_mentions(html, json));
1473 assert_eq!(mention_names(&spans), vec!["Ada Lovelace", "Bob"]);
1474 }
1475
1476 #[test]
1477 fn different_users_next_to_each_other_stay_two_mentions() {
1478 let json = r#"[
1479 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1480 {"user_id":"U2","name":"Bob","id":1,"target_id":"U2"}
1481 ]"#;
1482 let html = r#"<at id="0">Ada</at> <at id="1">Bob</at>"#;
1483 let spans = message_spans(&with_mentions(html, json));
1484 assert_eq!(mention_names(&spans), vec!["Ada", "Bob"]);
1485 }
1486
1487 #[test]
1488 fn nested_split_mentions_merge() {
1489 let json = r#"[
1490 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1491 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"}
1492 ]"#;
1493 let html = r#"<b><at id="0">Ada</at> <at id="1">Lovelace</at></b>"#;
1494 let spans = message_spans(&with_mentions(html, json));
1495 let [Span::Bold(children)] = spans.as_slice() else {
1496 panic!("bold expected: {spans:?}")
1497 };
1498 assert_eq!(mention_names(children), vec!["Ada Lovelace"]);
1499 }
1500
1501 #[test]
1502 fn old_mention_json_without_ids_merges_users_by_position() {
1503 let json = r#"[{"user_id":"U1","name":"Ada"},{"user_id":"U1","name":"Lovelace"},{"user_id":null,"name":"Tip"},{"user_id":null,"name":"day"}]"#;
1504 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Tip</at> <at id="3">day</at>"#;
1505 let stored = with_mentions(html, json);
1506 let parsed = mentions(&stored);
1507 assert_eq!(
1508 (parsed[1].id, parsed[1].target_id.as_deref()),
1509 (Some(1), Some("U1"))
1510 );
1511 assert_eq!(
1512 mention_names(&message_spans(&stored)),
1513 vec!["Ada Lovelace", "Tip", "day"]
1514 );
1515 }
1516
1517 #[test]
1518 fn edit_mentions_follow_the_merged_names() {
1519 let json = r#"[
1520 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1521 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
1522 {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
1523 ]"#;
1524 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> and <at id="2">Bob</at>"#;
1525 assert_eq!(
1526 user_mention_inputs(&with_mentions(html, json)),
1527 vec![
1528 MentionInput::user("U1", "Ada Lovelace"),
1529 MentionInput::user("U2", "Bob"),
1530 ]
1531 );
1532 }
1533
1534 #[test]
1535 fn editing_a_channel_post_keeps_its_channel_mention() {
1536 let mut post = with_mentions(
1537 r#"<at id="0">General</at> and <at id="1">Bob</at> <at id="2">Squad</at>"#,
1538 r#"[
1539 {"user_id":null,"name":"General","id":0,"target_id":"19:c@thread.tacv2","group":true},
1540 {"user_id":"U2","name":"Bob","id":1,"target_id":"U2"},
1541 {"user_id":null,"name":"Squad","id":2,"target_id":"19:t@thread.tacv2","group":true}
1542 ]"#,
1543 );
1544 post.conversation_id = "19:c@thread.tacv2".to_owned();
1545 assert_eq!(
1546 channel_mention_inputs(&post),
1547 vec![
1548 MentionInput::channel("19:c@thread.tacv2", "General"),
1549 MentionInput::user("U2", "Bob"),
1550 ]
1551 );
1552 assert_eq!(
1553 user_mention_inputs(&post),
1554 vec![MentionInput::user("U2", "Bob")]
1555 );
1556 }
1557}