BlueGit

ict rusty-teams

Files

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

stored.rs

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