BlueGit

ict rusty-teams

Files

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

stored.rs

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