BlueGit

ict rusty-teams

Files

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

stored.rs

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