BlueGit

ict rusty-teams

Files

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

stored.rs

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