BlueGit

ict rusty-teams

Files

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

stored.rs

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