BlueGit

ict rusty-teams

Files

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

stored.rs

stored.rs 29.5 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 created_at: Utc::now(),
556 edited_at: None,
557 deleted: false,
558 body_html: body_html.to_owned(),
559 attachments_json: attachments_json.to_owned(),
560 reactions_json: "[]".to_owned(),
561 mentions_json: "[]".to_owned(),
562 }
563 }
564
565 #[test]
566 fn reaction_without_created_at_still_parses() {
567 let mut stored = record("", "[]");
568 stored.reactions_json =
569 r#"[{"reaction_type":"like","user_id":"u","user_name":null}]"#.to_owned();
570 let parsed = reactions(&stored);
571 assert_eq!(parsed.len(), 1);
572 assert_eq!(parsed[0].created_at, None);
573 }
574
575 #[test]
576 fn images_cover_hosted_contents_and_ams_and_skip_emoji() {
577 let html = concat!(
578 r#"<p>a</p><img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value" style="width:300px; height: 120px">"#,
579 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">"#,
580 r#"<img itemtype="http://schema.skype.com/Emoji" src="https://x/e.png" alt="x">"#,
581 r#"<img src="https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aWQ9/$value">"#,
582 );
583 let found = images(&record(html, "[]"));
584 assert_eq!(found.len(), 2);
585 assert_eq!(
586 (found[0].id.as_str(), found[0].width, found[0].height),
587 ("aWQ9", Some(300), Some(120))
588 );
589 assert_eq!(
590 (found[1].id.as_str(), found[1].width, found[1].height),
591 ("0-weu-d1-abc", Some(64), None)
592 );
593 }
594
595 #[test]
596 fn deleted_messages_have_no_images() {
597 let mut deleted = record(r#"<img src="https://x/y">"#, "[]");
598 deleted.deleted = true;
599 assert!(images(&deleted).is_empty());
600 }
601
602 #[test]
603 fn edits_keep_images_and_match_files_to_their_attachment_tags() {
604 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>";
605 let attachments = r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"G1"}]"#;
606 let preserved = edit_preserved(&record(html, attachments));
607 assert!(
608 preserved
609 .images_html
610 .starts_with("<p><img src=\"https://graph.microsoft.com/")
611 );
612 assert!(!preserved.images_html.contains("text"));
613 assert_eq!(preserved.files.len(), 1);
614 assert_eq!(preserved.files[0].attachment_id, "G1");
615 assert_eq!(preserved.files[0].content_url, "https://x/a.pdf");
616 assert_eq!(preserved.files[0].name, "a.pdf");
617 assert!(preserved.kept.is_empty());
618 }
619
620 const QUOTED_HTML: &str =
621 "<attachment id=\"Q1\"></attachment><p>answer</p><attachment id=\"F1\"></attachment>";
622
623 #[test]
624 fn a_quoted_reply_keeps_its_quote_and_pairs_the_file_by_id() {
625 let attachments = r#"[
626 {"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}},
627 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null,"id":"F1"}
628 ]"#;
629 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
630 assert_eq!(preserved.files.len(), 1);
631 assert_eq!(preserved.files[0].attachment_id, "F1");
632 assert_eq!(preserved.kept.len(), 1);
633 assert_eq!(preserved.kept[0].id, "Q1");
634 assert_eq!(
635 preserved.kept[0].content_type.as_deref(),
636 Some("messageReference")
637 );
638 assert!(
639 preserved.kept[0]
640 .content
641 .as_deref()
642 .unwrap()
643 .contains("messagePreview")
644 );
645 }
646
647 #[test]
648 fn records_cached_before_content_was_stored_leave_the_quote_out() {
649 let attachments = r#"[
650 {"content_type":"messageReference","name":null,"url":null,"text":null,"quote":{"message_id":"Q1","preview":"hi","sender_name":null}},
651 {"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null}
652 ]"#;
653 let preserved = edit_preserved(&record(QUOTED_HTML, attachments));
654 assert_eq!(preserved.files[0].attachment_id, "F1");
655 assert!(preserved.kept.is_empty());
656 }
657
658 #[test]
659 fn file_kind_follows_the_extension_then_the_content_type() {
660 let kind = |name: Option<&str>, content_type: &str| {
661 AttachmentInfo {
662 content_type: Some(content_type.to_owned()),
663 name: name.map(str::to_owned),
664 url: None,
665 text: None,
666 size: None,
667 quote: None,
668 id: None,
669 content: None,
670 }
671 .file_kind()
672 };
673 assert_eq!(kind(Some("Plan.DOCX"), "reference"), FileKind::Word);
674 assert_eq!(kind(Some("a.xlsx"), "reference"), FileKind::Excel);
675 assert_eq!(kind(Some("a.pptx"), "reference"), FileKind::PowerPoint);
676 assert_eq!(kind(Some("a.pdf"), "reference"), FileKind::Pdf);
677 assert_eq!(kind(Some("a.PNG"), "reference"), FileKind::Image);
678 assert_eq!(kind(Some("a.zip"), "reference"), FileKind::Archive);
679 assert_eq!(kind(Some("a.bin"), "reference"), FileKind::Other);
680 assert_eq!(kind(None, "image/png"), FileKind::Image);
681 assert_eq!(kind(Some("noextension"), "reference"), FileKind::Other);
682 }
683
684 #[test]
685 fn files_expose_name_kind_and_open_url() {
686 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}]"#;
687 let found = files(&record("", json));
688 assert_eq!(found.len(), 1);
689 assert_eq!(
690 (found[0].name.as_str(), found[0].kind),
691 ("Plan.docx", FileKind::Word)
692 );
693 assert_eq!(found[0].open_url, "https://x/Plan.docx");
694 assert_eq!(found[0].size, None);
695 }
696
697 #[test]
698 fn copy_text_flattens_markup_and_keeps_mentions_and_lines() {
699 let html = r#"<p>Hi <at id="0">Ada</at>, <b>look</b></p><p>second <a href="https://x">link</a></p>"#;
700 let text = copy_text(&record(html, "[]"));
701 assert!(text.starts_with("Hi @Ada, look"), "{text}");
702 assert!(text.contains("second link"), "{text}");
703 assert!(text.contains('\n'));
704 }
705
706 #[test]
707 fn old_cached_attachments_still_parse() {
708 let parsed = attachments(&record(
709 "",
710 r#"[{"content_type":"reference","name":"a.pdf","url":"u","text":null}]"#,
711 ));
712 assert_eq!(parsed.len(), 1);
713 assert!(parsed[0].is_file());
714 assert_eq!(parsed[0].size, None);
715 }
716
717 #[test]
718 fn quote_references_are_extracted_from_the_message_reference_attachment() {
719 let attachment = graph::Attachment {
720 id: Some("1".to_owned()),
721 content_type: Some("messageReference".to_owned()),
722 content_url: None,
723 name: None,
724 content: Some(
725 r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),
726 ),
727 };
728 let info = crate::mapping::attachment_info(&attachment);
729 assert_eq!(
730 info.quote,
731 Some(QuoteInfo {
732 message_id: "1728".to_owned(),
733 preview: "Hello".to_owned(),
734 sender_name: Some("Adele".to_owned())
735 })
736 );
737 let stored = record("", &serde_json::to_string(&[info]).unwrap());
738 assert_eq!(quotes(&stored).len(), 1);
739 }
740
741 fn with_mentions(body_html: &str, mentions_json: &str) -> MessageRecord {
742 let mut stored = record(body_html, "[]");
743 stored.mentions_json = mentions_json.to_owned();
744 stored
745 }
746
747 fn mention_names(spans: &[Span]) -> Vec<&str> {
748 spans
749 .iter()
750 .filter_map(|span| match span {
751 Span::Mention { name, .. } => Some(name.as_str()),
752 _ => None,
753 })
754 .collect()
755 }
756
757 #[test]
758 fn a_tag_mention_split_per_word_merges_into_one() {
759 let json = r#"[
760 {"user_id":null,"name":"Tip","id":0,"target_id":"T1"},
761 {"user_id":null,"name":"of","id":1,"target_id":"T1"},
762 {"user_id":null,"name":"the","id":2,"target_id":"T1"},
763 {"user_id":null,"name":"day","id":3,"target_id":"T1"}
764 ]"#;
765 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>"#;
766 let spans = message_spans(&with_mentions(html, json));
767 assert_eq!(mention_names(&spans), vec!["Tip of the day"]);
768 assert_eq!(
769 copy_text(&with_mentions(html, json)),
770 "Hey @Tip of the day!"
771 );
772 }
773
774 #[test]
775 fn a_two_word_user_name_merges_but_different_users_stay_apart() {
776 let json = r#"[
777 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
778 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
779 {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
780 ]"#;
781 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Bob</at>"#;
782 let spans = message_spans(&with_mentions(html, json));
783 assert_eq!(mention_names(&spans), vec!["Ada Lovelace", "Bob"]);
784 }
785
786 #[test]
787 fn different_users_next_to_each_other_stay_two_mentions() {
788 let json = r#"[
789 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
790 {"user_id":"U2","name":"Bob","id":1,"target_id":"U2"}
791 ]"#;
792 let html = r#"<at id="0">Ada</at> <at id="1">Bob</at>"#;
793 let spans = message_spans(&with_mentions(html, json));
794 assert_eq!(mention_names(&spans), vec!["Ada", "Bob"]);
795 }
796
797 #[test]
798 fn nested_split_mentions_merge() {
799 let json = r#"[
800 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
801 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"}
802 ]"#;
803 let html = r#"<b><at id="0">Ada</at> <at id="1">Lovelace</at></b>"#;
804 let spans = message_spans(&with_mentions(html, json));
805 let [Span::Bold(children)] = spans.as_slice() else {
806 panic!("bold expected: {spans:?}")
807 };
808 assert_eq!(mention_names(children), vec!["Ada Lovelace"]);
809 }
810
811 #[test]
812 fn old_mention_json_without_ids_merges_users_by_position() {
813 let json = r#"[{"user_id":"U1","name":"Ada"},{"user_id":"U1","name":"Lovelace"},{"user_id":null,"name":"Tip"},{"user_id":null,"name":"day"}]"#;
814 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> <at id="2">Tip</at> <at id="3">day</at>"#;
815 let stored = with_mentions(html, json);
816 let parsed = mentions(&stored);
817 assert_eq!(
818 (parsed[1].id, parsed[1].target_id.as_deref()),
819 (Some(1), Some("U1"))
820 );
821 assert_eq!(
822 mention_names(&message_spans(&stored)),
823 vec!["Ada Lovelace", "Tip", "day"]
824 );
825 }
826
827 #[test]
828 fn edit_mentions_follow_the_merged_names() {
829 let json = r#"[
830 {"user_id":"U1","name":"Ada","id":0,"target_id":"U1"},
831 {"user_id":"U1","name":"Lovelace","id":1,"target_id":"U1"},
832 {"user_id":"U2","name":"Bob","id":2,"target_id":"U2"}
833 ]"#;
834 let html = r#"<at id="0">Ada</at> <at id="1">Lovelace</at> and <at id="2">Bob</at>"#;
835 assert_eq!(
836 user_mention_inputs(&with_mentions(html, json)),
837 vec![
838 MentionInput::user("U1", "Ada Lovelace"),
839 MentionInput::user("U2", "Bob"),
840 ]
841 );
842 }
843}