BlueGit

ict rusty-teams

Files

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

stored.rs

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