BlueGit

ict rusty-teams

Files

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

stored.rs

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