BlueGit

ict rusty-teams

Files

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

stored.rs

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