BlueGit

ict rusty-teams

Files

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

stored.rs

stored.rs 32.3 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
439fn spans_with_mentions(record: &MessageRecord, infos: &[MentionInfo]) -> Vec<Span> {
440 let mut spans = html_to_spans(&with_inline_quotes(record));
441 merge_split_mentions(&mut spans, infos);
442 spans
443}
444
445fn with_inline_quotes(record: &MessageRecord) -> String {
446 let mut html = record.body_html.clone();
447 for attachment in attachments(record) {
448 let Some(quote) = attachment.quote else {
449 continue;
450 };
451 let id = attachment.id.unwrap_or_else(|| quote.message_id.clone());
452 let tag = format!("<attachment id=\"{id}\"></attachment>");
453 let block = quote_html(&quote);
454 if html.contains(&tag) {
455 html = html.replacen(&tag, &block, 1);
456 } else {
457 html.insert_str(0, &block);
458 }
459 }
460 html
461}
462
463fn quote_html(quote: &QuoteInfo) -> String {
464 let sender = quote
465 .sender_name
466 .as_deref()
467 .map(|name| format!("<strong itemprop=\"mri\">{}</strong>", escape_html(name)))
468 .unwrap_or_default();
469 format!(
470 "<blockquote itemscope=\"\" itemtype=\"http://{REPLY_ITEMTYPE}\" itemid=\"{}\">{sender}<p itemprop=\"preview\">{}</p></blockquote>",
471 escape_html(&quote.message_id),
472 escape_html(&quote.preview),
473 )
474}
475
476pub fn user_mention_inputs(record: &MessageRecord) -> Vec<MentionInput> {
477 let infos = mentions(record);
478 let mut inputs = Vec::new();
479 collect_user_mentions(&spans_with_mentions(record, &infos), &infos, &mut inputs);
480 inputs
481}
482
483fn collect_user_mentions(spans: &[Span], infos: &[MentionInfo], inputs: &mut Vec<MentionInput>) {
484 for span in spans {
485 match span {
486 Span::Bold(children)
487 | Span::Italic(children)
488 | Span::Strike(children)
489 | Span::Superscript(children)
490 | Span::Subscript(children)
491 | Span::Sized(_, children)
492 | Span::Underline(children)
493 | Span::Colored { children, .. }
494 | Span::Heading { children, .. }
495 | Span::Quote(children)
496 | Span::BlockQuote(children)
497 | Span::Link { children, .. } => collect_user_mentions(children, infos, inputs),
498 Span::List { items, .. } => items
499 .iter()
500 .for_each(|item| collect_user_mentions(item, infos, inputs)),
501 Span::Table { rows, .. } => rows
502 .iter()
503 .flatten()
504 .for_each(|cell| collect_user_mentions(cell, infos, inputs)),
505 Span::Mention { name, id } => {
506 let parsed: Option<i64> = id.as_deref().and_then(|id| id.parse().ok());
507 let user_id = infos
508 .iter()
509 .find(|info| parsed.is_some() && info.id == parsed)
510 .and_then(|info| info.user_id.as_deref());
511 if let Some(user_id) = user_id {
512 inputs.push(MentionInput::user(user_id, name));
513 }
514 }
515 _ => {}
516 }
517 }
518}
519
520fn merge_split_mentions(spans: &mut Vec<Span>, mentions: &[MentionInfo]) {
521 let target_of = |id: &Option<String>| -> Option<String> {
522 let parsed: i64 = id.as_deref()?.parse().ok()?;
523 mentions
524 .iter()
525 .find(|info| info.id == Some(parsed))?
526 .target_id
527 .clone()
528 };
529 let mut merged: Vec<Span> = Vec::with_capacity(spans.len());
530 for mut span in std::mem::take(spans) {
531 match &mut span {
532 Span::Bold(children)
533 | Span::Italic(children)
534 | Span::Strike(children)
535 | Span::Superscript(children)
536 | Span::Subscript(children)
537 | Span::Sized(_, children)
538 | Span::Underline(children)
539 | Span::Colored { children, .. }
540 | Span::Heading { children, .. }
541 | Span::Quote(children)
542 | Span::BlockQuote(children)
543 | Span::Link { children, .. } => merge_split_mentions(children, mentions),
544 Span::List { items, .. } => items
545 .iter_mut()
546 .for_each(|item| merge_split_mentions(item, mentions)),
547 Span::Table { rows, .. } => rows
548 .iter_mut()
549 .flatten()
550 .for_each(|cell| merge_split_mentions(cell, mentions)),
551 Span::Mention { name, id } => {
552 let continues = match merged.as_slice() {
553 [
554 ..,
555 Span::Mention {
556 id: previous_id, ..
557 },
558 Span::Text(gap),
559 ] => {
560 gap.trim().is_empty()
561 && target_of(id).is_some()
562 && target_of(previous_id) == target_of(id)
563 }
564 _ => false,
565 };
566 if continues {
567 merged.pop();
568 if let Some(Span::Mention {
569 name: previous_name,
570 ..
571 }) = merged.last_mut()
572 {
573 previous_name.push(' ');
574 previous_name.push_str(name);
575 }
576 continue;
577 }
578 }
579 _ => {}
580 }
581 merged.push(span);
582 }
583 *spans = merged;
584}
585
586#[cfg(test)]
587mod tests {
588 use chrono::Utc;
589
590 use super::*;
591
592 fn record(body_html: &str, attachments_json: &str) -> MessageRecord {
593 MessageRecord {
594 conversation_id: "c".to_owned(),
595 message_id: "m".to_owned(),
596 reply_to_id: None,
597 sender_id: Some("u".to_owned()),
598 sender_name: None,
599 sender_application_id: None,
600 links_json: "[]".to_owned(),
601 created_at: Utc::now(),
602 edited_at: None,
603 deleted: false,
604 body_html: body_html.to_owned(),
605 attachments_json: attachments_json.to_owned(),
606 reactions_json: "[]".to_owned(),
607 mentions_json: "[]".to_owned(),
608 }
609 }
610
611 #[test]
612 fn reaction_without_created_at_still_parses() {
613 let mut stored = record("", "[]");
614 stored.reactions_json =
615 r#"[{"reaction_type":"like","user_id":"u","user_name":null}]"#.to_owned();
616 let parsed = reactions(&stored);
617 assert_eq!(parsed.len(), 1);
618 assert_eq!(parsed[0].created_at, None);
619 }
620
621 #[test]
622 fn images_cover_hosted_contents_and_ams_and_skip_emoji() {
623 let html = concat!(
624 r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,
625 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">"#,
626 r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,
627 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
628 );
629 let found = images(&record(html, "[]"));
630 assert_eq!(found.len(), 2);
631 assert_eq!(
632 (found[0].id.as_str(), found[0].width, found[0].height),
633 ("aWQ9", Some(300), Some(120))
634 );
635 assert_eq!(
636 (found[1].id.as_str(), found[1].width, found[1].height),
637 ("0-weu-d1-abc", Some(64), None)
638 );
639 }
640
641 #[test]
642 fn deleted_messages_have_no_images() {
643 let mut deleted = record(r#"<img src="https://x/y">"#, "[]");
644 deleted.deleted = true;
645 assert!(images(&deleted).is_empty());
646 }
647
648 #[test]
649 fn edits_keep_images_and_match_files_to_their_attachment_tags() {
650 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>";
651 let attachments = r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"G1"}]"#;
652 let preserved = edit_preserved(&record(html, attachments));
653 assert!(
654 preserved
655 .images_html
656 .starts_with("<p><img src=\"https://graph.microsoft.com/")
657 );
658 assert!(!preserved.images_html.contains("text"));
659 assert_eq!(preserved.files.len(), 1);
660 assert_eq!(preserved.files[0].attachment_id, "G1");
661 assert_eq!(preserved.files[0].content_url, "https://x/a.pdf");
662 assert_eq!(preserved.files[0].name, "a.pdf");
663 assert!(preserved.kept.is_empty());
664 }
665
666 const QUOTED_HTML: &str =
667 "<attachment id=\"Q1\"></attachment><p>answer</p><attachment id=\"F1\"></attachment>";
668
669 #[test]
670 fn a_quoted_reply_keeps_its_quote_and_pairs_the_file_by_id() {
671 let attachments = r#"[
672 {"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}},
673 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"F1"}
674 ]"#;
675 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
676 assert_eq!(preserved.files.len(), 1);
677 assert_eq!(preserved.files[0].attachment_id, "F1");
678 assert_eq!(preserved.kept.len(), 1);
679 assert_eq!(preserved.kept[0].id, "Q1");
680 assert_eq!(
681 preserved.kept[0].content_type.as_deref(),
682 Some("messageReference")
683 );
684 assert!(
685 preserved.kept[0]
686 .content
687 .as_deref()
688 .unwrap()
689 .contains("messagePreview")
690 );
691 }
692
693 #[test]
694 fn records_cached_before_content_was_stored_leave_the_quote_out() {
695 let attachments = r#"[
696 {"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}},
697 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null}
698 ]"#;
699 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
700 assert_eq!(preserved.files[0].attachment_id, "F1");
701 assert!(preserved.kept.is_empty());
702 }
703
704 #[test]
705 fn file_kind_follows_the_extension_then_the_content_type() {
706 let kind = |name: Option<&str>, content_type: &str| {
707 AttachmentInfo {
708 content_type: Some(content_type.to_owned()),
709 name: name.map(str::to_owned),
710 url: None,
711 text: None,
712 size: None,
713 quote: None,
714 id: None,
715 content: None,
716 }
717 .file_kind()
718 };
719 assert_eq!(kind(Some("Plan.DOCX"), "reference"), FileKind::Word);
720 assert_eq!(kind(Some("a.xlsx"), "reference"), FileKind::Excel);
721 assert_eq!(kind(Some("a.pptx"), "reference"), FileKind::PowerPoint);
722 assert_eq!(kind(Some("a.pdf"), "reference"), FileKind::Pdf);
723 assert_eq!(kind(Some("a.PNG"), "reference"), FileKind::Image);
724 assert_eq!(kind(Some("a.zip"), "reference"), FileKind::Archive);
725 assert_eq!(kind(Some("a.bin"), "reference"), FileKind::Other);
726 assert_eq!(kind(None, "image/png"), FileKind::Image);
727 assert_eq!(kind(Some("noextension"), "reference"), FileKind::Other);
728 }
729
730 #[test]
731 fn files_expose_name_kind_and_open_url() {
732 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}]"#;
733 let found = files(&record("", json));
734 assert_eq!(found.len(), 1);
735 assert_eq!(
736 (found[0].name.as_str(), found[0].kind),
737 ("Plan.docx", FileKind::Word)
738 );
739 assert_eq!(found[0].open_url, "https://x/Plan.docx");
740 assert_eq!(found[0].size, None);
741 }
742
743 #[test]
744 fn copy_text_flattens_markup_and_keeps_mentions_and_lines() {
745 let html = r#"<p>Hi <at id="0">Ada</at>, <b>look</b></p><p>second <a href="https://x">link</a></p>"#;
746 let text = copy_text(&record(html, "[]"));
747 assert!(text.starts_with("Hi @Ada, look"), "{text}");
748 assert!(text.contains("second link"), "{text}");
749 assert!(text.contains('\n'));
750 }
751
752 #[test]
753 fn old_cached_attachments_still_parse() {
754 let parsed = attachments(&record(
755 "",
756 r#"[{"content_type":"reference","name":"a.pdf","url":"u","text":null}]"#,
757 ));
758 assert_eq!(parsed.len(), 1);
759 assert!(parsed[0].is_file());
760 assert_eq!(parsed[0].size, None);
761 }
762
763 #[test]
764 fn quote_references_are_extracted_from_the_message_reference_attachment() {
765 let attachment = graph::Attachment {
766 id: Some("1".to_owned()),
767 content_type: Some("messageReference".to_owned()),
768 content_url: None,
769 name: None,
770 content: Some(
771 r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),
772 ),
773 };
774 let info = crate::mapping::attachment_info(&attachment);
775 assert_eq!(
776 info.quote,
777 Some(QuoteInfo {
778 message_id: "1728".to_owned(),
779 preview: "Hello".to_owned(),
780 sender_name: Some("Adele".to_owned())
781 })
782 );
783 let stored = record("", &serde_json::to_string(&[info]).unwrap());
784 assert_eq!(quotes(&stored).len(), 1);
785 }
786
787 #[test]
788 fn a_message_reference_renders_as_a_reply_quote_where_its_tag_sits() {
789 let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"Q1","quote":{"message_id":"Q1","preview":"a < b","sender_name":"Ada"}}]"#;
790 let stored = record("<p></p><attachment id=\"Q1\"></attachment>\ntest<p></p>", json);
791 let spans = message_spans(&stored);
792 let Some(Span::Quote(children)) = spans.first() else {
793 panic!("expected a reply quote first, got {spans:?}");
794 };
795 let mut quoted = String::new();
796 push_plain(&mut quoted, children);
797 assert!(quoted.contains("Ada"));
798 assert!(quoted.contains("a < b"));
799 let mut own = String::new();
800 push_plain(&mut own, &spans[1..]);
801 assert_eq!(own.trim(), "test");
802 }
803
804 #[test]
805 fn a_message_reference_without_its_tag_still_shows_the_quote() {
806 let json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}}]"#;
807 let spans = message_spans(&record("<p>answer</p>", json));
808 assert!(matches!(spans.first(), Some(Span::Quote(_))));
809 }
810
811 fn with_mentions(body_html: &str, mentions_json: &str) -> MessageRecord {
812 let mut stored = record(body_html, "[]");
813 stored.mentions_json = mentions_json.to_owned();
814 stored
815 }
816
817 fn mention_names(spans: &[Span]) -> Vec<&str> {
818 spans
819 .iter()
820 .filter_map(|span| match span {
821 Span::Mention { name, .. } => Some(name.as_str()),
822 _ => None,
823 })
824 .collect()
825 }
826
827 #[test]
828 fn a_tag_mention_split_per_word_merges_into_one() {
829 let json = r#"[
830 {"user_id":null,"name":"Tip","id":0,"target_id":"T1"},
831 {"user_id":null,"name":"of","id":1,"target_id":"T1"},
832 {"user_id":null,"name":"the","id":2,"target_id":"T1"},
833 {"user_id":null,"name":"day","id":3,"target_id":"T1"}
834 ]"#;
835 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>"#;
836 let spans = message_spans(&with_mentions(html, json));
837 assert_eq!(mention_names(&spans), vec!["Tip of the day"]);
838 assert_eq!(
839 copy_text(&with_mentions(html, json)),
840 "Hey @Tip of the day!"
841 );
842 }
843
844 #[test]
845 fn a_two_word_user_name_merges_but_different_users_stay_apart() {
846 let json = r#"[
847 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
848 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
849 {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
850 ]"#;
851 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Bob</at>"#;
852 let spans = message_spans(&with_mentions(html, json));
853 assert_eq!(mention_names(&spans), vec!["Ada Lovelace", "Bob"]);
854 }
855
856 #[test]
857 fn different_users_next_to_each_other_stay_two_mentions() {
858 let json = r#"[
859 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
860 {"user_id":"U2","name":"Bob","id":1,"target_id":"U2"}
861 ]"#;
862 let html = r#"<at id="0">Ada</at> <at id="1">Bob</at>"#;
863 let spans = message_spans(&with_mentions(html, json));
864 assert_eq!(mention_names(&spans), vec!["Ada", "Bob"]);
865 }
866
867 #[test]
868 fn nested_split_mentions_merge() {
869 let json = r#"[
870 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
871 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"}
872 ]"#;
873 let html = r#"<b><at id="0">Ada</at> <at id="1">Lovelace</at></b>"#;
874 let spans = message_spans(&with_mentions(html, json));
875 let [Span::Bold(children)] = spans.as_slice() else {
876 panic!("bold expected: {spans:?}")
877 };
878 assert_eq!(mention_names(children), vec!["Ada Lovelace"]);
879 }
880
881 #[test]
882 fn old_mention_json_without_ids_merges_users_by_position() {
883 let json = r#"[{"user_id":"U1","name":"Ada"},{"user_id":"U1","name":"Lovelace"},{"user_id":null,"name":"Tip"},{"user_id":null,"name":"day"}]"#;
884 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Tip</at> <at id="3">day</at>"#;
885 let stored = with_mentions(html, json);
886 let parsed = mentions(&stored);
887 assert_eq!(
888 (parsed[1].id, parsed[1].target_id.as_deref()),
889 (Some(1), Some("U1"))
890 );
891 assert_eq!(
892 mention_names(&message_spans(&stored)),
893 vec!["Ada Lovelace", "Tip", "day"]
894 );
895 }
896
897 #[test]
898 fn edit_mentions_follow_the_merged_names() {
899 let json = r#"[
900 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
901 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
902 {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
903 ]"#;
904 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> and <at id="2">Bob</at>"#;
905 assert_eq!(
906 user_mention_inputs(&with_mentions(html, json)),
907 vec![
908 MentionInput::user("U1", "Ada Lovelace"),
909 MentionInput::user("U2", "Bob"),
910 ]
911 );
912 }
913}