BlueGit

ict rusty-teams

Files

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

stored.rs

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