BlueGit

ict rusty-teams

Files

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

stored.rs

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