BlueGit

ict rusty-teams

Files

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

stored.rs

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