BlueGit

ict rusty-teams

Files

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

stored.rs

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