BlueGit

ict rusty-teams

Files

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

stored.rs

stored.rs 46.7 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::Quote { children, .. }
492 | Span::BlockQuote(children)
493 | Span::Link { children, .. } => push_plain(text, children),
494 Span::Heading { children, .. } => {
495 push_plain(text, children);
496 text.push('\n');
497 }
498 Span::Mention { name, .. } => {
499 text.push('@');
500 text.push_str(name);
501 }
502 Span::LineBreak | Span::Rule => text.push('\n'),
503 Span::List {
504 ordered,
505 start,
506 items,
507 } => {
508 for (offset, item) in items.iter().enumerate() {
509 if *ordered {
510 text.push_str(&format!("{}. ", *start as usize + offset));
511 } else {
512 text.push_str("- ");
513 }
514 push_plain(text, item);
515 text.push('\n');
516 }
517 }
518 Span::Table { rows, .. } => {
519 for row in rows {
520 for (index, cell) in row.iter().enumerate() {
521 if index > 0 {
522 text.push('\t');
523 }
524 push_plain(text, cell);
525 }
526 text.push('\n');
527 }
528 }
529 Span::Image { .. } => {}
530 }
531 }
532}
533
534/// Own, not deleted. Whether the conversation supports the write is the engine's call.
535pub fn can_edit(record: &MessageRecord, my_user_id: &str) -> bool {
536 !record.deleted && record.sender_id.as_deref() == Some(my_user_id)
537}
538
539pub fn can_delete(record: &MessageRecord, my_user_id: &str) -> bool {
540 can_edit(record, my_user_id)
541}
542
543/// Position in the message plus an FNV-1a hash of the URL, so two GIFs from the same host never share an id.
544fn image_id(position: usize, url: &str) -> String {
545 let hash = url.bytes().fold(0x811c_9dc5_u32, |hash, byte| {
546 (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193)
547 });
548 format!("{position}-{hash:08x}")
549}
550
551fn dimension(attribute: Option<&str>, style: &str, property: &str) -> Option<u32> {
552 let from_style = || {
553 style.split(';').find_map(|declaration| {
554 let (name, value) = declaration.split_once(':')?;
555 (name.trim() == property).then(|| leading_number(value))?
556 })
557 };
558 attribute
559 .and_then(leading_number)
560 .or_else(from_style)
561 .filter(|pixels| *pixels > 0)
562}
563
564fn leading_number(text: &str) -> Option<u32> {
565 let digits: String = text
566 .trim()
567 .chars()
568 .take_while(char::is_ascii_digit)
569 .collect();
570 digits.parse().ok()
571}
572
573pub fn message_spans(record: &MessageRecord) -> Vec<Span> {
574 spans_with_mentions(record, &mentions(record))
575}
576
577pub const PROFILE_LINK_PREFIX: &str = "teams-profile:";
578
579/// Like `message_spans`, with the id of each user mention replaced by a profile link.
580pub fn linked_message_spans(record: &MessageRecord) -> Vec<Span> {
581 linked_message_spans_with(record, &|_| None, &no_forward_header)
582}
583
584/// 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.
585pub fn linked_message_spans_with(
586 record: &MessageRecord,
587 quoted_text: &dyn Fn(&str) -> Option<String>,
588 forward_header: &dyn Fn(&ForwardInfo) -> ForwardHeader,
589) -> Vec<Span> {
590 let infos = mentions(record);
591 let html = inline_forwards(record, with_inline_quotes(record, quoted_text), forward_header);
592 let mut spans = html_to_spans(&html);
593 merge_split_mentions(&mut spans, &infos);
594 link_user_mentions(&mut spans, &infos);
595 spans
596}
597
598/// The spans of `record` with its body replaced by the translated html.
599pub fn translated_spans(
600 record: &MessageRecord,
601 translated_html: &str,
602 forward_header: &dyn Fn(&ForwardInfo) -> ForwardHeader,
603) -> Vec<Span> {
604 let mut translated = record.clone();
605 translated.body_html = translated_html.to_owned();
606 linked_message_spans_with(&translated, &|_| None, forward_header)
607}
608
609fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) {
610 for span in spans {
611 match span {
612 Span::Bold(children)
613 | Span::Italic(children)
614 | Span::Strike(children)
615 | Span::Superscript(children)
616 | Span::Subscript(children)
617 | Span::Sized(_, children)
618 | Span::Underline(children)
619 | Span::Colored { children, .. }
620 | Span::Heading { children, .. }
621 | Span::Quote { children, .. }
622 | Span::BlockQuote(children)
623 | Span::Link { children, .. } => link_user_mentions(children, infos),
624 Span::List { items, .. } => items
625 .iter_mut()
626 .for_each(|item| link_user_mentions(item, infos)),
627 Span::Table { rows, .. } => rows
628 .iter_mut()
629 .flatten()
630 .for_each(|cell| link_user_mentions(cell, infos)),
631 Span::Mention { id, .. } => {
632 let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok());
633 let user_id = infos
634 .iter()
635 .find(|info| parsed.is_some() && info.id == parsed)
636 .and_then(|info| info.user_id.as_deref());
637 if let Some(user_id) = user_id {
638 *id = Some(format!("{PROFILE_LINK_PREFIX}{user_id}"));
639 }
640 }
641 _ => {}
642 }
643 }
644}
645
646fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> {
647 let mut spans = html_to_spans(&with_inline_quotes(record, &|_| None));
648 merge_split_mentions(&mut spans, infos);
649 spans
650}
651
652fn with_inline_quotes(record: &MessageRecord, quoted_text: &dyn Fn(&str) -> Option<String>) -> String {
653 let mut html = record.body_html.clone();
654 for attachment in attachments(record) {
655 let Some(mut quote) = attachment.quote else {
656 continue;
657 };
658 if let Some(text) = quoted_text(&quote.message_id).filter(|text| !text.trim().is_empty()) {
659 quote.preview = text;
660 }
661 let id = attachment.id.unwrap_or_else(|| quote.message_id.clone());
662 let tag = format!("<attachment id=\"{id}\"></attachment>");
663 let block = quote_html(&quote);
664 if html.contains(&tag) {
665 html = html.replacen(&tag, &block, 1);
666 } else {
667 html.insert_str(0, &block);
668 }
669 }
670 html
671}
672
673pub fn quote_html(quote: &QuoteInfo) -> String {
674 let sender = quote
675 .sender_name
676 .as_deref()
677 .map(|name| format!("<strong itemprop=\"mri\">{}</strong>", escape_html(name)))
678 .unwrap_or_default();
679 let time = quote_time(&quote.message_id)
680 .map(|time| format!(" <span itemprop=\"time\">{time}</span>"))
681 .unwrap_or_default();
682 let preview = escape_html(quote.preview.trim()).replace('\n', "<br>");
683 format!(
684 "<blockquote itemscope=\"\" itemtype=\"http://{REPLY_ITEMTYPE}\" itemid=\"{}\">{sender}{time}<p itemprop=\"preview\">{preview}</p></blockquote>",
685 escape_html(&quote.message_id),
686 )
687}
688
689fn quote_time(message_id: &str) -> Option<String> {
690 let millis = message_id.parse::<i64>().ok()?;
691 let time = chrono::DateTime::from_timestamp_millis(millis)?;
692 Some(time.with_timezone(&chrono::Local).format("%d/%m/%Y %H:%M").to_string())
693}
694
695pub fn user_mention_inputs(record: &MessageRecord) -> Vec<MentionInput> {
696 let infos = mentions(record);
697 let mut inputs = Vec::new();
698 collect_user_mentions(&spans_with_mentions(record, &infos), &infos, &mut inputs);
699 inputs
700}
701
702fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec<MentionInput>) {
703 for span in spans {
704 match span {
705 Span::Bold(children)
706 | Span::Italic(children)
707 | Span::Strike(children)
708 | Span::Superscript(children)
709 | Span::Subscript(children)
710 | Span::Sized(_, children)
711 | Span::Underline(children)
712 | Span::Colored { children, .. }
713 | Span::Heading { children, .. }
714 | Span::Quote { children, .. }
715 | Span::BlockQuote(children)
716 | Span::Link { children, .. } => collect_user_mentions(children, infos, inputs),
717 Span::List { items, .. } => items
718 .iter()
719 .for_each(|item| collect_user_mentions(item, infos, inputs)),
720 Span::Table { rows, .. } => rows
721 .iter()
722 .flatten()
723 .for_each(|cell| collect_user_mentions(cell, infos, inputs)),
724 Span::Mention { name, id } => {
725 let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok());
726 let user_id = infos
727 .iter()
728 .find(|info| parsed.is_some() && info.id == parsed)
729 .and_then(|info| info.user_id.as_deref());
730 if let Some(user_id) = user_id {
731 inputs.push(MentionInput::user(user_id, name));
732 }
733 }
734 _ => {}
735 }
736 }
737}
738
739fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {
740 let target_of = |id: &Option<String>| -> Option<String> {
741 let parsed: i64 = id.as_deref()?.parse().ok()?;
742 mentions
743 .iter()
744 .find(|info| info.id == Some(parsed))?
745 .target_id
746 .clone()
747 };
748 let mut merged: Vec<Span> = Vec::with_capacity(spans.len());
749 for mut span in std::mem::take(spans) {
750 match &mut span {
751 Span::Bold(children)
752 | Span::Italic(children)
753 | Span::Strike(children)
754 | Span::Superscript(children)
755 | Span::Subscript(children)
756 | Span::Sized(_, children)
757 | Span::Underline(children)
758 | Span::Colored { children, .. }
759 | Span::Heading { children, .. }
760 | Span::Quote { children, .. }
761 | Span::BlockQuote(children)
762 | Span::Link { children, .. } => merge_split_mentions(children, mentions),
763 Span::List { items, .. } => items
764 .iter_mut()
765 .for_each(|item| merge_split_mentions(item, mentions)),
766 Span::Table { rows, .. } => rows
767 .iter_mut()
768 .flatten()
769 .for_each(|cell| merge_split_mentions(cell, mentions)),
770 Span::Mention { name, id } => {
771 let continues = match merged.as_slice() {
772 [
773 ..,
774 Span::Mention {
775 id: previous_id, ..
776 },
777 Span::Text(gap),
778 ] => {
779 gap.trim().is_empty()
780 && target_of(id).is_some()
781 && target_of(previous_id) == target_of(id)
782 }
783 _ => false,
784 };
785 if continues {
786 merged.pop();
787 if let Some(Span::Mention {
788 name: previous_name,
789 ..
790 }) = merged.last_mut()
791 {
792 previous_name.push(' ');
793 previous_name.push_str(name);
794 }
795 continue;
796 }
797 }
798 _ => {}
799 }
800 merged.push(span);
801 }
802 *spans = merged;
803}
804
805#[cfg(test)]
806mod tests {
807 use chrono::Utc;
808
809 use super::*;
810
811 fn record(body_html: &str, attachments_json: &str) -> MessageRecord {
812 MessageRecord {
813 subject: None,
814 conversation_id: "c".to_owned(),
815 message_id: "m".to_owned(),
816 reply_to_id: None,
817 sender_id: Some("u".to_owned()),
818 sender_name: None,
819 sender_application_id: None,
820 links_json: "[]".to_owned(),
821 created_at: Utc::now(),
822 edited_at: None,
823 deleted: false,
824 body_html: body_html.to_owned(),
825 attachments_json: attachments_json.to_owned(),
826 reactions_json: "[]".to_owned(),
827 mentions_json: "[]".to_owned(),
828 call_event_json: None,
829 importance: Default::default(),
830 }
831 }
832
833 #[test]
834 fn reaction_without_created_at_still_parses() {
835 let mut stored = record("", "[]");
836 stored.reactions_json =
837 r#"[{"reaction_type":"like","user_id":"u","user_name":null}]"#.to_owned();
838 let parsed = reactions(&stored);
839 assert_eq!(parsed.len(), 1);
840 assert_eq!(parsed[0].created_at, None);
841 }
842
843 #[test]
844 fn images_cover_hosted_contents_and_ams_and_skip_emoji() {
845 let html = concat!(
846 r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,
847 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">"#,
848 r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,
849 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
850 );
851 let found = images(&record(html, "[]"));
852 assert_eq!(found.len(), 2);
853 assert_eq!((found[0].width, found[0].height), (Some(300), Some(120)));
854 assert_eq!((found[1].width, found[1].height), (Some(64), None));
855 assert!(found[0].id.starts_with("0-"));
856 assert!(found[1].id.starts_with("1-"));
857 }
858
859 #[test]
860 fn two_giphy_gifs_get_different_image_ids_and_the_gif_kind() {
861 let html = concat!(
862 r#"<img src="https://media0.giphy.com/media/abc/giphy.gif" alt=" dancing cat ">"#,
863 r#"<img src="https://media1.giphy.com/media/def/giphy.gif">"#,
864 r#"<img src="https://statics.teams.cdn.office.net/evergreen-assets/stickerassets/a/b.gif">"#,
865 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
866 );
867 let found = images(&record(html, "[]"));
868 let ids: std::collections::HashSet<&str> =
869 found.iter().map(|image| image.id.as_str()).collect();
870 assert_eq!(ids.len(), 4);
871 assert_eq!(found[0].id, images(&record(html, "[]"))[0].id);
872 assert_eq!(found[0].alt.as_deref(), Some("dancing cat"));
873 assert_eq!(found[1].alt, None);
874 let kinds: Vec<ImageKind> = found.iter().map(ImageRef::kind).collect();
875 assert_eq!(
876 kinds,
877 [
878 ImageKind::Gif,
879 ImageKind::Gif,
880 ImageKind::Sticker,
881 ImageKind::Inline
882 ]
883 );
884 }
885
886 #[test]
887 fn readable_text_keeps_lines_lists_code_and_mentions_and_drops_the_reply_quote() {
888 let html = concat!(
889 r#"<blockquote itemscope="" itemtype="http://schema.skype.com/Reply" itemid="Q0"><strong itemprop="mri">Bob</strong><p itemprop="preview">old words</p></blockquote>"#,
890 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>"#,
891 );
892 let json = r#"[{"user_id":"U1","name":"Ada","id":0,"target_id":"U1"}]"#;
893 let text = readable_text(&with_mentions(html, json));
894 assert!(!text.contains("old words"), "{text}");
895 assert!(!text.contains("Bob"), "{text}");
896 assert!(text.starts_with("Hi @Ada\n"), "{text}");
897 assert!(text.contains("- one\n- two\n"), "{text}");
898 assert!(text.contains("let x = 1;\n"), "{text}");
899 assert!(text.ends_with("last"), "{text}");
900 }
901
902 #[test]
903 fn a_quote_keeps_its_lines_and_shows_when_the_quoted_message_was_sent() {
904 let html = quote_html(&QuoteInfo {
905 message_id: "1760517360000".to_owned(),
906 preview: "first link\nsecond link".to_owned(),
907 sender_name: Some("Ada".to_owned()),
908 });
909 assert!(html.contains("first link<br>second link"), "{html}");
910 assert!(html.contains("/2025 "), "{html}");
911 let without_time = quote_html(&QuoteInfo {
912 message_id: "Q9".to_owned(),
913 preview: "text".to_owned(),
914 sender_name: None,
915 });
916 assert!(!without_time.contains("itemprop=\"time\""), "{without_time}");
917 }
918
919 #[test]
920 fn a_reply_blockquote_in_the_body_becomes_the_quote() {
921 let html = format!(
922 "{}<p>answer</p>",
923 quote_html(&QuoteInfo {
924 message_id: "Q9".to_owned(),
925 preview: "a < b".to_owned(),
926 sender_name: Some("Ada".to_owned()),
927 })
928 );
929 let stored = record(&html, "[]");
930 assert_eq!(
931 message_quote(&stored),
932 Some(QuoteInfo {
933 message_id: "Q9".to_owned(),
934 preview: "a < b".to_owned(),
935 sender_name: Some("Ada".to_owned()),
936 })
937 );
938 assert_eq!(readable_text(&stored), "answer");
939 assert_eq!(message_quote(&record("<p>plain</p>", "[]")), None);
940 }
941
942 #[test]
943 fn a_reply_blockquote_nested_in_a_normal_blockquote_is_not_the_quote() {
944 let html = format!(
945 "<blockquote>{}</blockquote><p>answer</p>",
946 quote_html(&QuoteInfo {
947 message_id: "Q9".to_owned(),
948 preview: "inner".to_owned(),
949 sender_name: None,
950 })
951 );
952 assert_eq!(message_quote(&record(&html, "[]")), None);
953 }
954
955 #[test]
956 fn readable_text_drops_the_stored_quote_and_card_text() {
957 let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","quote":{"message_id":"Q1","preview":"quoted","sender_name":"Ada"}}]"#;
958 let stored = record("<attachment id=\"Q1\"></attachment><p>answer</p>", json);
959 assert_eq!(readable_text(&stored), "answer");
960 }
961
962 #[test]
963 fn reactions_group_by_base_emoji_and_merge_skin_tones() {
964 let mut stored = record("", "[]");
965 stored.reactions_json = r#"[
966 {"reaction_type":"like","user_id":"a"},
967 {"reaction_type":"\ud83d\udc4d\ud83c\udffd","user_id":"me"},
968 {"reaction_type":"\ud83d\udc4d","user_id":"b"},
969 {"reaction_type":"heart","user_id":"a"},
970 {"reaction_type":"\u2764\ufe0f","user_id":"c"}
971 ]"#
972 .to_owned();
973 let summaries = reaction_summaries(&stored, Some("me"));
974 assert_eq!(
975 summaries,
976 vec![
977 ReactionSummary {
978 emoji: "\u{1F44D}".to_owned(),
979 count: 3,
980 mine: true
981 },
982 ReactionSummary {
983 emoji: "\u{2764}".to_owned(),
984 count: 2,
985 mine: false
986 },
987 ]
988 );
989 assert!(
990 reaction_summaries(&stored, None)
991 .iter()
992 .all(|summary| !summary.mine)
993 );
994 }
995
996 #[test]
997 fn deleted_messages_have_no_images() {
998 let mut deleted = record(r#"<img src="https://x/y">"#, "[]");
999 deleted.deleted = true;
1000 assert!(images(&deleted).is_empty());
1001 }
1002
1003 #[test]
1004 fn edits_keep_images_and_match_files_to_their_attachment_tags() {
1005 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>";
1006 let attachments = r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"G1"}]"#;
1007 let preserved = edit_preserved(&record(html, attachments));
1008 assert!(
1009 preserved
1010 .images_html
1011 .starts_with("<p><img src=\"https://graph.microsoft.com/")
1012 );
1013 assert!(!preserved.images_html.contains("text"));
1014 assert_eq!(preserved.files.len(), 1);
1015 assert_eq!(preserved.files[0].attachment_id, "G1");
1016 assert_eq!(preserved.files[0].content_url, "https://x/a.pdf");
1017 assert_eq!(preserved.files[0].name, "a.pdf");
1018 assert!(preserved.kept.is_empty());
1019 }
1020
1021 const QUOTED_HTML: &str =
1022 "<attachment id=\"Q1\"></attachment><p>answer</p><attachment id=\"F1\"></attachment>";
1023
1024 #[test]
1025 fn a_quoted_reply_keeps_its_quote_and_pairs_the_file_by_id() {
1026 let attachments = r#"[
1027 {"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}},
1028 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"F1"}
1029 ]"#;
1030 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
1031 assert_eq!(preserved.files.len(), 1);
1032 assert_eq!(preserved.files[0].attachment_id, "F1");
1033 assert_eq!(preserved.kept.len(), 1);
1034 assert_eq!(preserved.kept[0].id, "Q1");
1035 assert_eq!(
1036 preserved.kept[0].content_type.as_deref(),
1037 Some("messageReference")
1038 );
1039 assert!(
1040 preserved.kept[0]
1041 .content
1042 .as_deref()
1043 .unwrap()
1044 .contains("messagePreview")
1045 );
1046 }
1047
1048 #[test]
1049 fn records_cached_before_content_was_stored_leave_the_quote_out() {
1050 let attachments = r#"[
1051 {"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}},
1052 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null}
1053 ]"#;
1054 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
1055 assert_eq!(preserved.files[0].attachment_id, "F1");
1056 assert!(preserved.kept.is_empty());
1057 }
1058
1059 #[test]
1060 fn file_kind_follows_the_extension_then_the_content_type() {
1061 let kind = |name: Option<&str>, content_type: &str| {
1062 AttachmentInfo {
1063 content_type: Some(content_type.to_owned()),
1064 name: name.map(str::to_owned),
1065 url: None,
1066 text: None,
1067 size: None,
1068 quote: None,
1069 id: None,
1070 content: None,
1071 unavailable: false,
1072 teams_app_id: None,
1073 }
1074 .file_kind()
1075 };
1076 assert_eq!(kind(Some("Plan.DOCX"), "reference"), FileKind::Word);
1077 assert_eq!(kind(Some("a.xlsx"), "reference"), FileKind::Excel);
1078 assert_eq!(kind(Some("a.pptx"), "reference"), FileKind::PowerPoint);
1079 assert_eq!(kind(Some("a.pdf"), "reference"), FileKind::Pdf);
1080 assert_eq!(kind(Some("a.PNG"), "reference"), FileKind::Image);
1081 assert_eq!(kind(Some("a.zip"), "reference"), FileKind::Archive);
1082 assert_eq!(kind(Some("a.bin"), "reference"), FileKind::Other);
1083 assert_eq!(kind(None, "image/png"), FileKind::Image);
1084 assert_eq!(kind(Some("noextension"), "reference"), FileKind::Other);
1085 }
1086
1087 #[test]
1088 fn files_expose_name_kind_and_open_url() {
1089 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}]"#;
1090 let found = files(&record("", json));
1091 assert_eq!(found.len(), 1);
1092 assert_eq!(
1093 (found[0].name.as_str(), found[0].kind),
1094 ("Plan.docx", FileKind::Word)
1095 );
1096 assert_eq!(found[0].open_url, "https://x/Plan.docx");
1097 assert_eq!(found[0].size, None);
1098 }
1099
1100 #[test]
1101 fn copy_text_flattens_markup_and_keeps_mentions_and_lines() {
1102 let html = r#"<p>Hi <at id="0">Ada</at>, <b>look</b></p><p>second <a href="https://x">link</a></p>"#;
1103 let text = copy_text(&record(html, "[]"));
1104 assert!(text.starts_with("Hi @Ada, look"), "{text}");
1105 assert!(text.contains("second link"), "{text}");
1106 assert!(text.contains('\n'));
1107 }
1108
1109 #[test]
1110 fn old_cached_attachments_still_parse() {
1111 let parsed = attachments(&record(
1112 "",
1113 r#"[{"content_type":"reference","name":"a.pdf","url":"u","text":null}]"#,
1114 ));
1115 assert_eq!(parsed.len(), 1);
1116 assert!(parsed[0].is_file());
1117 assert_eq!(parsed[0].size, None);
1118 }
1119
1120 #[test]
1121 fn quote_references_are_extracted_from_the_message_reference_attachment() {
1122 let attachment = graph::Attachment {
1123 id: Some("1".to_owned()),
1124 content_type: Some("messageReference".to_owned()),
1125 content_url: None,
1126 name: None,
1127 teams_app_id: None,
1128 content: Some(
1129 r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),
1130 ),
1131 };
1132 let info = crate::mapping::attachment_info(&attachment);
1133 assert_eq!(
1134 info.quote,
1135 Some(QuoteInfo {
1136 message_id: "1728".to_owned(),
1137 preview: "Hello".to_owned(),
1138 sender_name: Some("Adele".to_owned())
1139 })
1140 );
1141 let stored = record("", &serde_json::to_string(&[info]).unwrap());
1142 assert_eq!(quotes(&stored).len(), 1);
1143 }
1144
1145 #[test]
1146 fn a_message_reference_renders_as_a_reply_quote_where_its_tag_sits() {
1147 let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","quote":{"message_id":"Q1","preview":"a < b","sender_name":"Ada"}}]"#;
1148 let stored = record(
1149 "<p></p><attachment id=\"Q1\"></attachment>\ntest<p></p>",
1150 json,
1151 );
1152 let spans = message_spans(&stored);
1153 let Some(Span::Quote { children, .. }) = spans.first() else {
1154 panic!("expected a reply quote first, got {spans:?}");
1155 };
1156 let mut quoted = String::new();
1157 push_plain(&mut quoted, children);
1158 assert!(quoted.contains("Ada"));
1159 assert!(quoted.contains("a < b"));
1160 let mut own = String::new();
1161 push_plain(&mut own, &spans[1..]);
1162 assert_eq!(own.trim(), "test");
1163 }
1164
1165 #[test]
1166 fn a_message_reference_without_its_tag_still_shows_the_quote() {
1167 let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}}]"#;
1168 let spans = message_spans(&record("<p>answer</p>", json));
1169 assert!(matches!(spans.first(), Some(Span::Quote { .. })));
1170 }
1171
1172 fn with_mentions(body_html: &str, mentions_json: &str) -> MessageRecord {
1173 let mut stored = record(body_html, "[]");
1174 stored.mentions_json = mentions_json.to_owned();
1175 stored
1176 }
1177
1178 fn mention_names(spans: &[Span]) -> Vec<&str> {
1179 spans
1180 .iter()
1181 .filter_map(|span| match span {
1182 Span::Mention { name, .. } => Some(name.as_str()),
1183 _ => None,
1184 })
1185 .collect()
1186 }
1187
1188 #[test]
1189 fn user_mentions_link_to_their_profile_and_groups_do_not() {
1190 let json = r#"[
1191 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1192 {"user_id":null,"name":"Team","id":1,"target_id":"T1"}
1193 ]"#;
1194 let html = r#"<at id="0">Ada</at> <at id="1">Team</at>"#;
1195 let ids: Vec<Option<String>> = linked_message_spans(&with_mentions(html, json))
1196 .into_iter()
1197 .filter_map(|span| match span {
1198 Span::Mention { id, .. } => Some(id),
1199 _ => None,
1200 })
1201 .collect();
1202 assert_eq!(
1203 ids,
1204 vec![Some("teams-profile:U1".to_owned()), Some("1".to_owned())]
1205 );
1206 }
1207
1208 #[test]
1209 fn a_tag_mention_split_per_word_merges_into_one() {
1210 let json = r#"[
1211 {"user_id":null,"name":"Tip","id":0,"target_id":"T1"},
1212 {"user_id":null,"name":"of","id":1,"target_id":"T1"},
1213 {"user_id":null,"name":"the","id":2,"target_id":"T1"},
1214 {"user_id":null,"name":"day","id":3,"target_id":"T1"}
1215 ]"#;
1216 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>"#;
1217 let spans = message_spans(&with_mentions(html, json));
1218 assert_eq!(mention_names(&spans), vec!["Tip of the day"]);
1219 assert_eq!(
1220 copy_text(&with_mentions(html, json)),
1221 "Hey @Tip of the day!"
1222 );
1223 }
1224
1225 #[test]
1226 fn a_two_word_user_name_merges_but_different_users_stay_apart() {
1227 let json = r#"[
1228 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1229 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
1230 {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
1231 ]"#;
1232 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Bob</at>"#;
1233 let spans = message_spans(&with_mentions(html, json));
1234 assert_eq!(mention_names(&spans), vec!["Ada Lovelace", "Bob"]);
1235 }
1236
1237 #[test]
1238 fn different_users_next_to_each_other_stay_two_mentions() {
1239 let json = r#"[
1240 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1241 {"user_id":"U2","name":"Bob","id":1,"target_id":"U2"}
1242 ]"#;
1243 let html = r#"<at id="0">Ada</at> <at id="1">Bob</at>"#;
1244 let spans = message_spans(&with_mentions(html, json));
1245 assert_eq!(mention_names(&spans), vec!["Ada", "Bob"]);
1246 }
1247
1248 #[test]
1249 fn nested_split_mentions_merge() {
1250 let json = r#"[
1251 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1252 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"}
1253 ]"#;
1254 let html = r#"<b><at id="0">Ada</at> <at id="1">Lovelace</at></b>"#;
1255 let spans = message_spans(&with_mentions(html, json));
1256 let [Span::Bold(children)] = spans.as_slice() else {
1257 panic!("bold expected: {spans:?}")
1258 };
1259 assert_eq!(mention_names(children), vec!["Ada Lovelace"]);
1260 }
1261
1262 #[test]
1263 fn old_mention_json_without_ids_merges_users_by_position() {
1264 let json = r#"[{"user_id":"U1","name":"Ada"},{"user_id":"U1","name":"Lovelace"},{"user_id":null,"name":"Tip"},{"user_id":null,"name":"day"}]"#;
1265 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Tip</at> <at id="3">day</at>"#;
1266 let stored = with_mentions(html, json);
1267 let parsed = mentions(&stored);
1268 assert_eq!(
1269 (parsed[1].id, parsed[1].target_id.as_deref()),
1270 (Some(1), Some("U1"))
1271 );
1272 assert_eq!(
1273 mention_names(&message_spans(&stored)),
1274 vec!["Ada Lovelace", "Tip", "day"]
1275 );
1276 }
1277
1278 #[test]
1279 fn edit_mentions_follow_the_merged_names() {
1280 let json = r#"[
1281 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
1282 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
1283 {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
1284 ]"#;
1285 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> and <at id="2">Bob</at>"#;
1286 assert_eq!(
1287 user_mention_inputs(&with_mentions(html, json)),
1288 vec![
1289 MentionInput::user("U1", "Ada Lovelace"),
1290 MentionInput::user("U2", "Bob"),
1291 ]
1292 );
1293 }
1294}