BlueGit

ict rusty-teams

fix(sidebar): chat list preview matches Teams for every message type

- Labels like Teams: Sent an image, 📷 GIF, 🎥 Video, Sent a file, Sent a card, Forwarded a message, Audio message, Loop component
- Recording started/stopped/ready, Transcript is available, User added/joined from Graph event details, no sender prefix
- Calls keep the previous line (Teams never makes Event/Call the last message)
- Graph isDeleted is read; deleted line says "This message was deleted"
- Emoji kept as glyphs, mentions without @, reply quotes dropped
- Demo chats show the new labels

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
ebc3b1de073bd49d998c30e873bba68946647b05
Parent
690046d5
12 files changed +466 −41
crates/app-state/src/agents/message_context.rs +1 −0
@@ -163,6 +163,7 @@ mod tests {
163 163 last_message_sender_name: None,
164 164 last_message_deleted: false,
165 165 last_event_system: false,
166 last_event_call: false,
166 167 });
167 168 state
168 169 }
@@ -163,6 +163,7 @@ mod tests {
163 last_message_sender_name: None,
163 last_message_sender_name: None,
164 last_message_deleted: false,
164 last_message_deleted: false,
165 last_event_system: false,
165 last_event_system: false,
166 last_event_call: false,
166 });
167 });
167 state
168 state
168 }
169 }
crates/app-state/src/demo.rs +6 −6
@@ -311,7 +311,7 @@ fn demo_chats() -> Vec<DemoChat> {
311 311 members: people(&[(PRIYA_ID, "Priya Nair")]),
312 312 time: at(0, 10, 47),
313 313 unread: false,
314 preview: Some((PRIYA_ID, "Priya Nair", "Image")),
314 preview: Some((PRIYA_ID, "Priya Nair", "Sent an image")),
315 315 deleted: false,
316 316 },
317 317 DemoChat {
@@ -321,7 +321,7 @@ fn demo_chats() -> Vec<DemoChat> {
321 321 members: people(&[(TOBIAS_ID, "Tobias Klein")]),
322 322 time: at(2, 9, 30),
323 323 unread: false,
324 preview: Some((TOBIAS_ID, "Tobias Klein", "ok")),
324 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Forwarded a message")),
325 325 deleted: false,
326 326 },
327 327 DemoChat {
@@ -361,7 +361,7 @@ fn demo_chats() -> Vec<DemoChat> {
361 361 members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),
362 362 time: at(0, 9, 45),
363 363 unread: true,
364 preview: Some((JONAS_ID, "Jonas Ortega", "Recording is available")),
364 preview: Some(("", "", "Recording is ready")),
365 365 deleted: false,
366 366 },
367 367 DemoChat {
@@ -381,7 +381,7 @@ fn demo_chats() -> Vec<DemoChat> {
381 381 members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]),
382 382 time: at(0, 12, 5),
383 383 unread: true,
384 preview: Some((JONAS_ID, "Jonas Ortega", "Pizza on Friday?")),
384 preview: Some((JONAS_ID, "Jonas Ortega", "\u{1F4F7} GIF")),
385 385 deleted: false,
386 386 },
387 387 DemoChat {
@@ -411,7 +411,7 @@ fn demo_chats() -> Vec<DemoChat> {
411 411 members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),
412 412 time: at(4, 8, 15),
413 413 unread: false,
414 preview: Some((TOBIAS_ID, "Tobias Klein", "Route map attached")),
414 preview: Some((TOBIAS_ID, "Tobias Klein", "Sent a file")),
415 415 deleted: false,
416 416 },
417 417 DemoChat {
@@ -421,7 +421,7 @@ fn demo_chats() -> Vec<DemoChat> {
421 421 members: group(&[(PRIYA_ID, "Priya Nair"), (LEA_ID, "Lea Schneider")]),
422 422 time: at(6, 19, 40),
423 423 unread: false,
424 preview: Some((PRIYA_ID, "Priya Nair", "Next pick: Dune")),
424 preview: Some((PRIYA_ID, "Priya Nair", "Sent a card")),
425 425 deleted: false,
426 426 },
427 427 DemoChat {
@@ -311,7 +311,7 @@ fn demo_chats() -> Vec<DemoChat> {
311 members: people(&[(PRIYA_ID, "Priya Nair")]),
311 members: people(&[(PRIYA_ID, "Priya Nair")]),
312 time: at(0, 10, 47),
312 time: at(0, 10, 47),
313 unread: false,
313 unread: false,
314 preview: Some((PRIYA_ID, "Priya Nair", "Image")),
314 preview: Some((PRIYA_ID, "Priya Nair", "Sent an image")),
315 deleted: false,
315 deleted: false,
316 },
316 },
317 DemoChat {
317 DemoChat {
@@ -321,7 +321,7 @@ fn demo_chats() -> Vec<DemoChat> {
321 members: people(&[(TOBIAS_ID, "Tobias Klein")]),
321 members: people(&[(TOBIAS_ID, "Tobias Klein")]),
322 time: at(2, 9, 30),
322 time: at(2, 9, 30),
323 unread: false,
323 unread: false,
324 preview: Some((TOBIAS_ID, "Tobias Klein", "ok")),
324 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Forwarded a message")),
325 deleted: false,
325 deleted: false,
326 },
326 },
327 DemoChat {
327 DemoChat {
@@ -361,7 +361,7 @@ fn demo_chats() -> Vec<DemoChat> {
361 members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),
361 members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),
362 time: at(0, 9, 45),
362 time: at(0, 9, 45),
363 unread: true,
363 unread: true,
364 preview: Some((JONAS_ID, "Jonas Ortega", "Recording is available")),
364 preview: Some(("", "", "Recording is ready")),
365 deleted: false,
365 deleted: false,
366 },
366 },
367 DemoChat {
367 DemoChat {
@@ -381,7 +381,7 @@ fn demo_chats() -> Vec<DemoChat> {
381 members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]),
381 members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]),
382 time: at(0, 12, 5),
382 time: at(0, 12, 5),
383 unread: true,
383 unread: true,
384 preview: Some((JONAS_ID, "Jonas Ortega", "Pizza on Friday?")),
384 preview: Some((JONAS_ID, "Jonas Ortega", "\u{1F4F7} GIF")),
385 deleted: false,
385 deleted: false,
386 },
386 },
387 DemoChat {
387 DemoChat {
@@ -411,7 +411,7 @@ fn demo_chats() -> Vec<DemoChat> {
411 members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),
411 members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),
412 time: at(4, 8, 15),
412 time: at(4, 8, 15),
413 unread: false,
413 unread: false,
414 preview: Some((TOBIAS_ID, "Tobias Klein", "Route map attached")),
414 preview: Some((TOBIAS_ID, "Tobias Klein", "Sent a file")),
415 deleted: false,
415 deleted: false,
416 },
416 },
417 DemoChat {
417 DemoChat {
@@ -421,7 +421,7 @@ fn demo_chats() -> Vec<DemoChat> {
421 members: group(&[(PRIYA_ID, "Priya Nair"), (LEA_ID, "Lea Schneider")]),
421 members: group(&[(PRIYA_ID, "Priya Nair"), (LEA_ID, "Lea Schneider")]),
422 time: at(6, 19, 40),
422 time: at(6, 19, 40),
423 unread: false,
423 unread: false,
424 preview: Some((PRIYA_ID, "Priya Nair", "Next pick: Dune")),
424 preview: Some((PRIYA_ID, "Priya Nair", "Sent a card")),
425 deleted: false,
425 deleted: false,
426 },
426 },
427 DemoChat {
427 DemoChat {
crates/app-state/src/sidebar_model.rs +1 −0
@@ -20,6 +20,7 @@ pub const MUTED_ID: &str = "muted_chats";
20 20 pub const SECTION_PAGE_SIZE: usize = 5;
21 21 pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
22 22 pub const DELETED_PREVIEW: &str = "Message deleted";
23 pub const DELETED_CHAT_PREVIEW: &str = "This message was deleted";
23 24 const OWN_PREFIX: &str = "You";
24 25 const GROUP_KIND: &str = "group";
25 26
@@ -20,6 +20,7 @@ pub const MUTED_ID: &str = "muted_chats";
20pub const SECTION_PAGE_SIZE: usize = 5;
20pub const SECTION_PAGE_SIZE: usize = 5;
21pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
21pub const EMPTY_FOLDER_HINT: &str = "Empty. Drag chats here.";
22pub const DELETED_PREVIEW: &str = "Message deleted";
22pub const DELETED_PREVIEW: &str = "Message deleted";
23pub const DELETED_CHAT_PREVIEW: &str = "This message was deleted";
23const OWN_PREFIX: &str = "You";
24const OWN_PREFIX: &str = "You";
24const GROUP_KIND: &str = "group";
25const GROUP_KIND: &str = "group";
25
26
crates/app/src/views/sidebar.rs +2 −12
@@ -28,7 +28,7 @@ use crate::format;
28 28 use crate::local_previews::LocalPreview;
29 29 use crate::notice::truncated;
30 30 use crate::sidebar_model::{
31 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,
31 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,
32 32 NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
33 33 channel_name_style, older_chats_trigger_resets, step_id, team_name_style, visible_channel_ids,
34 34 wants_older_chats,
@@ -490,7 +490,7 @@ pub struct SidebarView {
490 490 fn preview_text(preview: &Preview) -> Option<(String, bool)> {
491 491 match preview {
492 492 Preview::Empty => None,
493 Preview::Deleted => Some((DELETED_PREVIEW.to_owned(), true)),
493 Preview::Deleted => Some((DELETED_CHAT_PREVIEW.to_owned(), true)),
494 494 Preview::Typing(text) => Some((text.clone(), true)),
495 495 Preview::Text {
496 496 prefix: Some(prefix),
@@ -500,14 +500,6 @@ fn preview_text(preview: &Preview) -> Option<(String, bool)> {
500 500 }
501 501 }
502 502
503 fn preview_icon(text: &str) -> Option<IconName> {
504 match text.rsplit(": ").next()? {
505 "Image" => Some(IconName::Image),
506 "File" => Some(IconName::File),
507 _ => None,
508 }
509 }
510
511 503 fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
512 504 let row = h_flex()
513 505 .flex_1()
@@ -955,7 +947,6 @@ impl SidebarView {
955 947 ),
956 948 (None, Some(local)) => Some(local_preview_row(local, preview_color)),
957 949 (None, None) => preview_text(&item.preview).map(|(text, italic)| {
958 let glyph = preview_icon(&text);
959 950 h_flex()
960 951 .flex_1()
961 952 .min_w_0()
@@ -965,7 +956,6 @@ impl SidebarView {
965 956 .text_size(px(12.5))
966 957 .when(italic, |preview| preview.italic())
967 958 .text_color(preview_color)
968 .children(glyph.map(|name| icon(name, 12., preview_color)))
969 959 .child(div().truncate().child(text))
970 960 }),
971 961 };
@@ -28,7 +28,7 @@ use crate::format;
28use crate::local_previews::LocalPreview;
28use crate::local_previews::LocalPreview;
29use crate::notice::truncated;
29use crate::notice::truncated;
30use crate::sidebar_model::{
30use crate::sidebar_model::{
31 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,
31 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_CHAT_PREVIEW, EMPTY_FOLDER_HINT, NameStyle,
32 NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
32 NameWeight, Preview, Section, SectionInput, SectionKind, Step, build_sections,
33 channel_name_style, older_chats_trigger_resets, step_id, team_name_style, visible_channel_ids,
33 channel_name_style, older_chats_trigger_resets, step_id, team_name_style, visible_channel_ids,
34 wants_older_chats,
34 wants_older_chats,
@@ -490,7 +490,7 @@ pub struct SidebarView {
490fn preview_text(preview: &Preview) -> Option<(String, bool)> {
490fn preview_text(preview: &Preview) -> Option<(String, bool)> {
491 match preview {
491 match preview {
492 Preview::Empty => None,
492 Preview::Empty => None,
493 Preview::Deleted => Some((DELETED_PREVIEW.to_owned(), true)),
493 Preview::Deleted => Some((DELETED_CHAT_PREVIEW.to_owned(), true)),
494 Preview::Typing(text) => Some((text.clone(), true)),
494 Preview::Typing(text) => Some((text.clone(), true)),
495 Preview::Text {
495 Preview::Text {
496 prefix: Some(prefix),
496 prefix: Some(prefix),
@@ -500,14 +500,6 @@ fn preview_text(preview: &Preview) -> Option<(String, bool)> {
500 }
500 }
501}
501}
502
502
503fn preview_icon(text: &str) -> Option<IconName> {
504 match text.rsplit(": ").next()? {
505 "Image" => Some(IconName::Image),
506 "File" => Some(IconName::File),
507 _ => None,
508 }
509}
510
511fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
503fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
512 let row = h_flex()
504 let row = h_flex()
513 .flex_1()
505 .flex_1()
@@ -955,7 +947,6 @@ impl SidebarView {
955 ),
947 ),
956 (None, Some(local)) => Some(local_preview_row(local, preview_color)),
948 (None, Some(local)) => Some(local_preview_row(local, preview_color)),
957 (None, None) => preview_text(&item.preview).map(|(text, italic)| {
949 (None, None) => preview_text(&item.preview).map(|(text, italic)| {
958 let glyph = preview_icon(&text);
959 h_flex()
950 h_flex()
960 .flex_1()
951 .flex_1()
961 .min_w_0()
952 .min_w_0()
@@ -965,7 +956,6 @@ impl SidebarView {
965 .text_size(px(12.5))
956 .text_size(px(12.5))
966 .when(italic, |preview| preview.italic())
957 .when(italic, |preview| preview.italic())
967 .text_color(preview_color)
958 .text_color(preview_color)
968 .children(glyph.map(|name| icon(name, 12., preview_color)))
969 .child(div().truncate().child(text))
959 .child(div().truncate().child(text))
970 }),
960 }),
971 };
961 };
crates/core/src/engine.rs +5 −1
@@ -493,7 +493,11 @@ impl<R: Remote> SyncEngine<R> {
493 493 }
494 494
495 495 pub(crate) fn update_chat_preview(&self, records: &[MessageRecord]) -> Result<()> {
496 let Some(newest) = records.iter().max_by_key(|record| record.created_at) else {
496 let Some(newest) = records
497 .iter()
498 .filter(|record| record.call_event_json.is_none())
499 .max_by_key(|record| record.created_at)
500 else {
497 501 return Ok(());
498 502 };
499 503 let preview = OwnedPreview::from_record(newest);
@@ -493,7 +493,11 @@ impl<R: Remote> SyncEngine<R> {
493 }
493 }
494
494
495 pub(crate) fn update_chat_preview(&self, records: &[MessageRecord]) -> Result<()> {
495 pub(crate) fn update_chat_preview(&self, records: &[MessageRecord]) -> Result<()> {
496 let Some(newest) = records.iter().max_by_key(|record| record.created_at) else {
496 let Some(newest) = records
497 .iter()
498 .filter(|record| record.call_event_json.is_none())
499 .max_by_key(|record| record.created_at)
500 else {
497 return Ok(());
501 return Ok(());
498 };
502 };
499 let preview = OwnedPreview::from_record(newest);
503 let preview = OwnedPreview::from_record(newest);
crates/core/src/mapping.rs +3 −0
@@ -41,6 +41,8 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
41 41 .as_ref()
42 42 .map(OwnedPreview::from_graph);
43 43 let last_event_system = preview.as_ref().is_some_and(|preview| preview.system);
44 // Teams leaves calls out of the chat list line: the line of the message before the call stays.
45 let last_event_call = preview.as_ref().is_some_and(|preview| preview.call);
44 46 ChatRecord {
45 47 id: chat.id.clone(),
46 48 kind: chat.chat_type.clone(),
@@ -72,6 +74,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
72 74 .as_ref()
73 75 .and_then(|preview| preview.sender_name.clone()),
74 76 last_event_system,
77 last_event_call,
75 78 }
76 79 }
77 80
@@ -41,6 +41,8 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
41 .as_ref()
41 .as_ref()
42 .map(OwnedPreview::from_graph);
42 .map(OwnedPreview::from_graph);
43 let last_event_system = preview.as_ref().is_some_and(|preview| preview.system);
43 let last_event_system = preview.as_ref().is_some_and(|preview| preview.system);
44 // Teams leaves calls out of the chat list line: the line of the message before the call stays.
45 let last_event_call = preview.as_ref().is_some_and(|preview| preview.call);
44 ChatRecord {
46 ChatRecord {
45 id: chat.id.clone(),
47 id: chat.id.clone(),
46 kind: chat.chat_type.clone(),
48 kind: chat.chat_type.clone(),
@@ -72,6 +74,7 @@ pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
72 .as_ref()
74 .as_ref()
73 .and_then(|preview| preview.sender_name.clone()),
75 .and_then(|preview| preview.sender_name.clone()),
74 last_event_system,
76 last_event_system,
77 last_event_call,
75 }
78 }
76}
79}
77
80
crates/core/src/preview.rs +368 −16
@@ -1,29 +1,186 @@
1 1 use graph::Message;
2 use scraper::Html;
2 use serde_json::Value;
3 3 use store::{ChatPreview, MessageRecord};
4 4
5 use crate::call_event::CallEvent;
6 use crate::external_image::is_giphy_url;
7 use crate::forwarded::FORWARDED_CONTENT_TYPE;
8 use crate::spans::{Span, html_to_spans};
9 use crate::stored::{AttachmentInfo, attachments};
10
5 11 const MAX_PREVIEW_CHARS: usize = 200;
6 12
13 pub const IMAGE_PREVIEW: &str = "Sent an image";
14 pub const GIF_PREVIEW: &str = "\u{1F4F7} GIF";
15 pub const VIDEO_PREVIEW: &str = "\u{1F3A5} Video";
16 pub const FILE_PREVIEW: &str = "Sent a file";
17 pub const CARD_PREVIEW: &str = "Sent a card";
18 pub const FORWARD_PREVIEW: &str = "Forwarded a message";
19 pub const AUDIO_PREVIEW: &str = "\u{1F399} Audio message";
20 pub const LOOP_PREVIEW: &str = "Loop component";
21 pub const RECORDING_STARTED_PREVIEW: &str = "Recording has started";
22 pub const RECORDING_STOPPED_PREVIEW: &str = "Recording has stopped";
23 pub const RECORDING_READY_PREVIEW: &str = "Recording is ready";
24 pub const TRANSCRIPT_PREVIEW: &str = "Transcript is available";
25 pub const USER_ADDED_PREVIEW: &str = "User added";
26 pub const USER_JOINED_PREVIEW: &str = "User joined";
27
28 const AUDIO_CARD_TYPE: &str = "application/vnd.microsoft.card.audio";
29 const LOOP_CARD_TYPE: &str = "application/vnd.microsoft.card.fluidEmbedCard";
30 const FILE_CONTENT_TYPE: &str = "reference";
31 const RECORDING_TYPE: &str = "#microsoft.graph.callRecordingEventMessageDetail";
32 const TRANSCRIPT_TYPE: &str = "#microsoft.graph.callTranscriptEventMessageDetail";
33 const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
34 const MEMBERS_JOINED_TYPE: &str = "#microsoft.graph.membersJoinedEventMessageDetail";
35
36 #[derive(Default)]
37 struct BodyParts {
38 text: String,
39 images: usize,
40 gifs: usize,
41 }
42
43 /// Plain text of a message body as the chat list shows it: emoji as glyphs, mentions by name, reply quotes and images dropped.
7 44 pub fn preview_text(html: &str) -> Option<String> {
8 let fragment = Html::parse_fragment(html);
9 let collapsed = fragment
10 .root_element()
11 .text()
12 .flat_map(str::split_whitespace)
13 .collect::<Vec<_>>()
14 .join(" ");
45 let mut parts = BodyParts::default();
46 collect(&html_to_spans(html), &mut parts);
47 collapse(&parts.text)
48 }
49
50 /// The chat list line for a message, with the Teams labels for bodies without text.
51 pub fn message_preview(html: &str, attachments: &[AttachmentInfo]) -> Option<String> {
52 if html.contains("<video") {
53 return Some(VIDEO_PREVIEW.to_owned());
54 }
55 let mut parts = BodyParts::default();
56 collect(&html_to_spans(html), &mut parts);
57 if let Some(text) = collapse(&parts.text) {
58 return Some(text);
59 }
60 if parts.gifs > 0 {
61 return Some(GIF_PREVIEW.to_owned());
62 }
63 if parts.images > 0 {
64 return Some(IMAGE_PREVIEW.to_owned());
65 }
66 attachment_label(attachments).map(str::to_owned)
67 }
68
69 fn attachment_label(attachments: &[AttachmentInfo]) -> Option<&'static str> {
70 let has_type = |wanted: &str| {
71 attachments
72 .iter()
73 .any(|attachment| attachment.content_type.as_deref() == Some(wanted))
74 };
75 if has_type(FORWARDED_CONTENT_TYPE) {
76 Some(FORWARD_PREVIEW)
77 } else if has_type(FILE_CONTENT_TYPE) {
78 Some(FILE_PREVIEW)
79 } else if has_type(AUDIO_CARD_TYPE) {
80 Some(AUDIO_PREVIEW)
81 } else if has_type(LOOP_CARD_TYPE) {
82 Some(LOOP_PREVIEW)
83 } else if attachments.iter().any(AttachmentInfo::is_card) {
84 Some(CARD_PREVIEW)
85 } else {
86 None
87 }
88 }
89
90 fn collect(spans: &[Span], parts: &mut BodyParts) {
91 for span in spans {
92 match span {
93 Span::Text(value) | Span::Code(value) => parts.text.push_str(value),
94 Span::CodeBlock { code, .. } => {
95 parts.text.push(' ');
96 parts.text.push_str(code);
97 parts.text.push(' ');
98 }
99 Span::Mention { name, .. } => parts.text.push_str(name),
100 Span::Quote { .. } => {}
101 Span::Image { hosted_content_url } if is_giphy_url(hosted_content_url) => {
102 parts.gifs += 1
103 }
104 Span::Image { .. } => parts.images += 1,
105 Span::LineBreak | Span::Rule => parts.text.push(' '),
106 Span::Bold(children)
107 | Span::Italic(children)
108 | Span::Strike(children)
109 | Span::Superscript(children)
110 | Span::Subscript(children)
111 | Span::Sized(_, children)
112 | Span::Underline(children)
113 | Span::Colored { children, .. }
114 | Span::Link { children, .. } => collect(children, parts),
115 Span::Heading { children, .. } | Span::BlockQuote(children) => {
116 parts.text.push(' ');
117 collect(children, parts);
118 parts.text.push(' ');
119 }
120 Span::List { items, .. } => {
121 for item in items {
122 parts.text.push(' ');
123 collect(item, parts);
124 }
125 parts.text.push(' ');
126 }
127 Span::Table { rows, .. } => {
128 for cell in rows.iter().flatten() {
129 parts.text.push(' ');
130 collect(cell, parts);
131 }
132 parts.text.push(' ');
133 }
134 }
135 }
136 }
137
138 fn collapse(text: &str) -> Option<String> {
139 let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" ");
15 140 if collapsed.is_empty() {
16 141 return None;
17 142 }
18 143 Some(collapsed.chars().take(MAX_PREVIEW_CHARS).collect())
19 144 }
20 145
146 fn system_event_preview(detail: &Value) -> Option<&'static str> {
147 match detail.get("@odata.type")?.as_str()? {
148 RECORDING_TYPE => match detail.get("callRecordingStatus")?.as_str()? {
149 "initial" => Some(RECORDING_STARTED_PREVIEW),
150 "chunkFinished" => Some(RECORDING_STOPPED_PREVIEW),
151 "success" => Some(RECORDING_READY_PREVIEW),
152 _ => None,
153 },
154 TRANSCRIPT_TYPE => Some(TRANSCRIPT_PREVIEW),
155 MEMBERS_JOINED_TYPE => Some(USER_JOINED_PREVIEW),
156 MEMBERS_ADDED_TYPE if added_only_self(detail) => Some(USER_JOINED_PREVIEW),
157 MEMBERS_ADDED_TYPE => Some(USER_ADDED_PREVIEW),
158 _ => None,
159 }
160 }
161
162 fn added_only_self(detail: &Value) -> bool {
163 let Some(initiator) = detail.pointer("/initiator/user/id").and_then(Value::as_str) else {
164 return false;
165 };
166 let members = detail
167 .get("members")
168 .and_then(Value::as_array)
169 .map(Vec::as_slice)
170 .unwrap_or_default();
171 !members.is_empty()
172 && members
173 .iter()
174 .all(|member| member.get("id").and_then(Value::as_str) == Some(initiator))
175 }
176
21 177 pub(crate) struct OwnedPreview {
22 178 pub text: Option<String>,
23 179 pub sender_id: Option<String>,
24 180 pub sender_name: Option<String>,
25 181 pub deleted: bool,
26 182 pub system: bool,
183 pub call: bool,
27 184 }
28 185
29 186 impl OwnedPreview {
@@ -33,13 +190,20 @@ impl OwnedPreview {
33 190 .as_deref()
34 191 .is_none_or(|kind| kind == "message");
35 192 let deleted = message.is_deleted();
36 let text = message
37 .body
38 .as_ref()
39 .and_then(|body| body.content.as_deref())
40 .filter(|_| regular && !deleted)
41 .and_then(preview_text);
42 let sender = message.from.as_ref();
193 let detail = message.event_detail.as_ref().filter(|_| !regular);
194 let call = detail.and_then(CallEvent::from_graph).is_some();
195 let text = if deleted {
196 None
197 } else if regular {
198 message
199 .body
200 .as_ref()
201 .and_then(|body| body.content.as_deref())
202 .and_then(|html| message_preview(html, &[]))
203 } else {
204 detail.and_then(system_event_preview).map(str::to_owned)
205 };
206 let sender = message.from.as_ref().filter(|_| regular);
43 207 OwnedPreview {
44 208 text,
45 209 sender_id: sender
@@ -50,6 +214,7 @@ impl OwnedPreview {
50 214 .map(str::to_owned),
51 215 deleted,
52 216 system: !regular,
217 call,
53 218 }
54 219 }
55 220
@@ -58,12 +223,13 @@ impl OwnedPreview {
58 223 text: if record.deleted {
59 224 None
60 225 } else {
61 preview_text(&record.body_html)
226 message_preview(&record.body_html, &attachments(record))
62 227 },
63 228 sender_id: record.sender_id.clone(),
64 229 sender_name: record.sender_name.clone(),
65 230 deleted: record.deleted,
66 231 system: false,
232 call: record.call_event_json.is_some(),
67 233 }
68 234 }
69 235
@@ -81,6 +247,20 @@ impl OwnedPreview {
81 247 mod tests {
82 248 use super::*;
83 249
250 fn attachment(content_type: &str) -> AttachmentInfo {
251 serde_json::from_value(serde_json::json!({
252 "content_type": content_type,
253 "name": null,
254 "url": null,
255 "text": null,
256 }))
257 .unwrap()
258 }
259
260 fn graph_message(value: serde_json::Value) -> Message {
261 serde_json::from_value(value).unwrap()
262 }
263
84 264 #[test]
85 265 fn strips_tags_and_collapses_whitespace() {
86 266 assert_eq!(
@@ -108,4 +288,176 @@ mod tests {
108 288 fn plain_text_bodies_keep_entities_decoded() {
109 289 assert_eq!(preview_text("a &amp; b").as_deref(), Some("a & b"));
110 290 }
291
292 #[test]
293 fn emoji_and_mentions_read_like_teams() {
294 let html = r#"<p><at id="0">Robin Beck</at>&nbsp;kannst du?&nbsp;<emoji id="smile" alt="🙂" title="Smile"></emoji></p>"#;
295 assert_eq!(
296 preview_text(html).as_deref(),
297 Some("Robin Beck kannst du? 🙂")
298 );
299 }
300
301 #[test]
302 fn reply_quotes_are_left_out() {
303 let html = r#"<blockquote itemtype="http://schema.skype.com/Reply" itemid="1"><strong>Ada</strong><p>old</p></blockquote><p>new</p>"#;
304 assert_eq!(preview_text(html).as_deref(), Some("new"));
305 }
306
307 #[test]
308 fn image_only_message_says_sent_an_image() {
309 let html = r#"<p><img src="https://graph.microsoft.com/v1.0/chats/19:x/messages/1/hostedContents/aWQ9/$value" alt="image" width="447" height="250" itemid="0-nde-d3-x"></p>"#;
310 assert_eq!(message_preview(html, &[]).as_deref(), Some(IMAGE_PREVIEW));
311 }
312
313 #[test]
314 fn text_with_an_image_keeps_only_the_text() {
315 let html = r#"<p>this is from QA:</p><p><img src="https://graph.microsoft.com/v1.0/x/$value"></p><p>&nbsp;</p>"#;
316 assert_eq!(
317 message_preview(html, &[]).as_deref(),
318 Some("this is from QA:")
319 );
320 }
321
322 #[test]
323 fn giphy_reads_as_gif() {
324 let html = r#"<p>&nbsp;</p><img alt="Happy Birthday Reaction GIF by The Office (GIF Image)" height="250" width="300" src="https://media2.giphy.com/media/g5R9dok94mrIvplmZd/giphy.gif?cid=x&amp;ct=g"><p>&nbsp;</p>"#;
325 assert_eq!(message_preview(html, &[]).as_deref(), Some(GIF_PREVIEW));
326 }
327
328 #[test]
329 fn inline_video_reads_as_video() {
330 let html = r#"<p>look</p><video src="https://x/v.mp4"></video>"#;
331 assert_eq!(message_preview(html, &[]).as_deref(), Some(VIDEO_PREVIEW));
332 }
333
334 #[test]
335 fn attachment_only_bodies_get_a_label() {
336 let body = r#"<attachment id="1792149081221"></attachment>"#;
337 let cases = [
338 (FORWARDED_CONTENT_TYPE, FORWARD_PREVIEW),
339 ("reference", FILE_PREVIEW),
340 ("application/vnd.microsoft.card.adaptive", CARD_PREVIEW),
341 ("application/vnd.microsoft.card.hero", CARD_PREVIEW),
342 (AUDIO_CARD_TYPE, AUDIO_PREVIEW),
343 (LOOP_CARD_TYPE, LOOP_PREVIEW),
344 ];
345 for (content_type, expected) in cases {
346 assert_eq!(
347 message_preview(body, &[attachment(content_type)]).as_deref(),
348 Some(expected),
349 "{content_type}"
350 );
351 }
352 assert_eq!(message_preview(body, &[]), None);
353 }
354
355 #[test]
356 fn a_file_with_text_shows_the_text() {
357 let body = r#"Hi Philipp,<br>Kann's dir zeigen.<attachment id="0cf57a46"></attachment>"#;
358 assert_eq!(
359 message_preview(body, &[attachment("reference")]).as_deref(),
360 Some("Hi Philipp, Kann's dir zeigen.")
361 );
362 }
363
364 #[test]
365 fn a_reply_shows_the_reply_text() {
366 let body = "<attachment id=\"1792136042729\"></attachment>\nwas war mit dependabot?";
367 assert_eq!(
368 message_preview(body, &[attachment("messageReference")]).as_deref(),
369 Some("was war mit dependabot?")
370 );
371 }
372
373 #[test]
374 fn graph_recording_and_transcript_events_have_teams_text() {
375 let event = |detail: serde_json::Value| {
376 OwnedPreview::from_graph(&graph_message(serde_json::json!({
377 "id": "1",
378 "messageType": "systemEventMessage",
379 "body": {"contentType": "html", "content": "<systemEventMessage/>"},
380 "from": {"user": {"id": "u1", "displayName": "Ada Lovelace"}},
381 "eventDetail": detail,
382 })))
383 };
384 let ready = event(serde_json::json!({
385 "@odata.type": RECORDING_TYPE,
386 "callRecordingStatus": "success",
387 }));
388 assert_eq!(ready.text.as_deref(), Some(RECORDING_READY_PREVIEW));
389 assert!(ready.system && !ready.call);
390 assert_eq!(ready.sender_name, None);
391 let started = event(serde_json::json!({
392 "@odata.type": RECORDING_TYPE,
393 "callRecordingStatus": "initial",
394 }));
395 assert_eq!(started.text.as_deref(), Some(RECORDING_STARTED_PREVIEW));
396 let transcript = event(serde_json::json!({"@odata.type": TRANSCRIPT_TYPE}));
397 assert_eq!(transcript.text.as_deref(), Some(TRANSCRIPT_PREVIEW));
398 }
399
400 #[test]
401 fn graph_member_events_say_added_or_joined() {
402 let added = |members: serde_json::Value| {
403 OwnedPreview::from_graph(&graph_message(serde_json::json!({
404 "id": "1",
405 "messageType": "systemEventMessage",
406 "eventDetail": {
407 "@odata.type": MEMBERS_ADDED_TYPE,
408 "members": members,
409 "initiator": {"user": {"id": "me"}},
410 },
411 })))
412 .text
413 };
414 assert_eq!(
415 added(serde_json::json!([{"id": "other"}])).as_deref(),
416 Some(USER_ADDED_PREVIEW)
417 );
418 assert_eq!(
419 added(serde_json::json!([{"id": "me"}])).as_deref(),
420 Some(USER_JOINED_PREVIEW)
421 );
422 }
423
424 #[test]
425 fn graph_call_events_are_marked_to_keep_the_previous_line() {
426 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
427 "id": "1",
428 "messageType": "systemEventMessage",
429 "eventDetail": {
430 "@odata.type": "#microsoft.graph.callEndedEventMessageDetail",
431 "callId": "c1",
432 "callDuration": "PT30S",
433 "callEventType": "call",
434 },
435 })));
436 assert!(preview.call);
437 assert_eq!(preview.text, None);
438 }
439
440 #[test]
441 fn graph_deleted_flag_marks_the_preview_deleted() {
442 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
443 "id": "1",
444 "messageType": "message",
445 "isDeleted": true,
446 "body": {"contentType": "html", "content": "secret"},
447 })));
448 assert!(preview.deleted);
449 assert_eq!(preview.text, None);
450 }
451
452 #[test]
453 fn graph_image_preview_says_sent_an_image() {
454 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
455 "id": "1",
456 "messageType": "message",
457 "body": {"contentType": "html", "content": "<p><img src=\"https://graph.microsoft.com/x/$value\"></p>"},
458 "from": {"user": {"id": "u1", "displayName": "Lukas Berg"}},
459 })));
460 assert_eq!(preview.text.as_deref(), Some(IMAGE_PREVIEW));
461 assert_eq!(preview.sender_name.as_deref(), Some("Lukas Berg"));
462 }
111 463 }
@@ -1,29 +1,186 @@
1use graph::Message;
1use graph::Message;
2use scraper::Html;
2use serde_json::Value;
3use store::{ChatPreview, MessageRecord};
3use store::{ChatPreview, MessageRecord};
4
4
5use crate::call_event::CallEvent;
6use crate::external_image::is_giphy_url;
7use crate::forwarded::FORWARDED_CONTENT_TYPE;
8use crate::spans::{Span, html_to_spans};
9use crate::stored::{AttachmentInfo, attachments};
10
5const MAX_PREVIEW_CHARS: usize = 200;
11const MAX_PREVIEW_CHARS: usize = 200;
6
12
13pub const IMAGE_PREVIEW: &str = "Sent an image";
14pub const GIF_PREVIEW: &str = "\u{1F4F7} GIF";
15pub const VIDEO_PREVIEW: &str = "\u{1F3A5} Video";
16pub const FILE_PREVIEW: &str = "Sent a file";
17pub const CARD_PREVIEW: &str = "Sent a card";
18pub const FORWARD_PREVIEW: &str = "Forwarded a message";
19pub const AUDIO_PREVIEW: &str = "\u{1F399} Audio message";
20pub const LOOP_PREVIEW: &str = "Loop component";
21pub const RECORDING_STARTED_PREVIEW: &str = "Recording has started";
22pub const RECORDING_STOPPED_PREVIEW: &str = "Recording has stopped";
23pub const RECORDING_READY_PREVIEW: &str = "Recording is ready";
24pub const TRANSCRIPT_PREVIEW: &str = "Transcript is available";
25pub const USER_ADDED_PREVIEW: &str = "User added";
26pub const USER_JOINED_PREVIEW: &str = "User joined";
27
28const AUDIO_CARD_TYPE: &str = "application/vnd.microsoft.card.audio";
29const LOOP_CARD_TYPE: &str = "application/vnd.microsoft.card.fluidEmbedCard";
30const FILE_CONTENT_TYPE: &str = "reference";
31const RECORDING_TYPE: &str = "#microsoft.graph.callRecordingEventMessageDetail";
32const TRANSCRIPT_TYPE: &str = "#microsoft.graph.callTranscriptEventMessageDetail";
33const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
34const MEMBERS_JOINED_TYPE: &str = "#microsoft.graph.membersJoinedEventMessageDetail";
35
36#[derive(Default)]
37struct BodyParts {
38 text: String,
39 images: usize,
40 gifs: usize,
41}
42
43/// Plain text of a message body as the chat list shows it: emoji as glyphs, mentions by name, reply quotes and images dropped.
7pub fn preview_text(html: &str) -> Option<String> {
44pub fn preview_text(html: &str) -> Option<String> {
8 let fragment = Html::parse_fragment(html);
45 let mut parts = BodyParts::default();
9 let collapsed = fragment
46 collect(&html_to_spans(html), &mut parts);
10 .root_element()
47 collapse(&parts.text)
11 .text()
48}
12 .flat_map(str::split_whitespace)
49
13 .collect::<Vec<_>>()
50/// The chat list line for a message, with the Teams labels for bodies without text.
14 .join(" ");
51pub fn message_preview(html: &str, attachments: &[AttachmentInfo]) -> Option<String> {
52 if html.contains("<video") {
53 return Some(VIDEO_PREVIEW.to_owned());
54 }
55 let mut parts = BodyParts::default();
56 collect(&html_to_spans(html), &mut parts);
57 if let Some(text) = collapse(&parts.text) {
58 return Some(text);
59 }
60 if parts.gifs > 0 {
61 return Some(GIF_PREVIEW.to_owned());
62 }
63 if parts.images > 0 {
64 return Some(IMAGE_PREVIEW.to_owned());
65 }
66 attachment_label(attachments).map(str::to_owned)
67}
68
69fn attachment_label(attachments: &[AttachmentInfo]) -> Option<&'static str> {
70 let has_type = |wanted: &str| {
71 attachments
72 .iter()
73 .any(|attachment| attachment.content_type.as_deref() == Some(wanted))
74 };
75 if has_type(FORWARDED_CONTENT_TYPE) {
76 Some(FORWARD_PREVIEW)
77 } else if has_type(FILE_CONTENT_TYPE) {
78 Some(FILE_PREVIEW)
79 } else if has_type(AUDIO_CARD_TYPE) {
80 Some(AUDIO_PREVIEW)
81 } else if has_type(LOOP_CARD_TYPE) {
82 Some(LOOP_PREVIEW)
83 } else if attachments.iter().any(AttachmentInfo::is_card) {
84 Some(CARD_PREVIEW)
85 } else {
86 None
87 }
88}
89
90fn collect(spans: &[Span], parts: &mut BodyParts) {
91 for span in spans {
92 match span {
93 Span::Text(value) | Span::Code(value) => parts.text.push_str(value),
94 Span::CodeBlock { code, .. } => {
95 parts.text.push(' ');
96 parts.text.push_str(code);
97 parts.text.push(' ');
98 }
99 Span::Mention { name, .. } => parts.text.push_str(name),
100 Span::Quote { .. } => {}
101 Span::Image { hosted_content_url } if is_giphy_url(hosted_content_url) => {
102 parts.gifs += 1
103 }
104 Span::Image { .. } => parts.images += 1,
105 Span::LineBreak | Span::Rule => parts.text.push(' '),
106 Span::Bold(children)
107 | Span::Italic(children)
108 | Span::Strike(children)
109 | Span::Superscript(children)
110 | Span::Subscript(children)
111 | Span::Sized(_, children)
112 | Span::Underline(children)
113 | Span::Colored { children, .. }
114 | Span::Link { children, .. } => collect(children, parts),
115 Span::Heading { children, .. } | Span::BlockQuote(children) => {
116 parts.text.push(' ');
117 collect(children, parts);
118 parts.text.push(' ');
119 }
120 Span::List { items, .. } => {
121 for item in items {
122 parts.text.push(' ');
123 collect(item, parts);
124 }
125 parts.text.push(' ');
126 }
127 Span::Table { rows, .. } => {
128 for cell in rows.iter().flatten() {
129 parts.text.push(' ');
130 collect(cell, parts);
131 }
132 parts.text.push(' ');
133 }
134 }
135 }
136}
137
138fn collapse(text: &str) -> Option<String> {
139 let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" ");
15 if collapsed.is_empty() {
140 if collapsed.is_empty() {
16 return None;
141 return None;
17 }
142 }
18 Some(collapsed.chars().take(MAX_PREVIEW_CHARS).collect())
143 Some(collapsed.chars().take(MAX_PREVIEW_CHARS).collect())
19}
144}
20
145
146fn system_event_preview(detail: &Value) -> Option<&'static str> {
147 match detail.get("@odata.type")?.as_str()? {
148 RECORDING_TYPE => match detail.get("callRecordingStatus")?.as_str()? {
149 "initial" => Some(RECORDING_STARTED_PREVIEW),
150 "chunkFinished" => Some(RECORDING_STOPPED_PREVIEW),
151 "success" => Some(RECORDING_READY_PREVIEW),
152 _ => None,
153 },
154 TRANSCRIPT_TYPE => Some(TRANSCRIPT_PREVIEW),
155 MEMBERS_JOINED_TYPE => Some(USER_JOINED_PREVIEW),
156 MEMBERS_ADDED_TYPE if added_only_self(detail) => Some(USER_JOINED_PREVIEW),
157 MEMBERS_ADDED_TYPE => Some(USER_ADDED_PREVIEW),
158 _ => None,
159 }
160}
161
162fn added_only_self(detail: &Value) -> bool {
163 let Some(initiator) = detail.pointer("/initiator/user/id").and_then(Value::as_str) else {
164 return false;
165 };
166 let members = detail
167 .get("members")
168 .and_then(Value::as_array)
169 .map(Vec::as_slice)
170 .unwrap_or_default();
171 !members.is_empty()
172 && members
173 .iter()
174 .all(|member| member.get("id").and_then(Value::as_str) == Some(initiator))
175}
176
21pub(crate) struct OwnedPreview {
177pub(crate) struct OwnedPreview {
22 pub text: Option<String>,
178 pub text: Option<String>,
23 pub sender_id: Option<String>,
179 pub sender_id: Option<String>,
24 pub sender_name: Option<String>,
180 pub sender_name: Option<String>,
25 pub deleted: bool,
181 pub deleted: bool,
26 pub system: bool,
182 pub system: bool,
183 pub call: bool,
27}
184}
28
185
29impl OwnedPreview {
186impl OwnedPreview {
@@ -33,13 +190,20 @@ impl OwnedPreview {
33 .as_deref()
190 .as_deref()
34 .is_none_or(|kind| kind == "message");
191 .is_none_or(|kind| kind == "message");
35 let deleted = message.is_deleted();
192 let deleted = message.is_deleted();
36 let text = message
193 let detail = message.event_detail.as_ref().filter(|_| !regular);
37 .body
194 let call = detail.and_then(CallEvent::from_graph).is_some();
38 .as_ref()
195 let text = if deleted {
39 .and_then(|body| body.content.as_deref())
196 None
40 .filter(|_| regular && !deleted)
197 } else if regular {
41 .and_then(preview_text);
198 message
42 let sender = message.from.as_ref();
199 .body
200 .as_ref()
201 .and_then(|body| body.content.as_deref())
202 .and_then(|html| message_preview(html, &[]))
203 } else {
204 detail.and_then(system_event_preview).map(str::to_owned)
205 };
206 let sender = message.from.as_ref().filter(|_| regular);
43 OwnedPreview {
207 OwnedPreview {
44 text,
208 text,
45 sender_id: sender
209 sender_id: sender
@@ -50,6 +214,7 @@ impl OwnedPreview {
50 .map(str::to_owned),
214 .map(str::to_owned),
51 deleted,
215 deleted,
52 system: !regular,
216 system: !regular,
217 call,
53 }
218 }
54 }
219 }
55
220
@@ -58,12 +223,13 @@ impl OwnedPreview {
58 text: if record.deleted {
223 text: if record.deleted {
59 None
224 None
60 } else {
225 } else {
61 preview_text(&record.body_html)
226 message_preview(&record.body_html, &attachments(record))
62 },
227 },
63 sender_id: record.sender_id.clone(),
228 sender_id: record.sender_id.clone(),
64 sender_name: record.sender_name.clone(),
229 sender_name: record.sender_name.clone(),
65 deleted: record.deleted,
230 deleted: record.deleted,
66 system: false,
231 system: false,
232 call: record.call_event_json.is_some(),
67 }
233 }
68 }
234 }
69
235
@@ -81,6 +247,20 @@ impl OwnedPreview {
81mod tests {
247mod tests {
82 use super::*;
248 use super::*;
83
249
250 fn attachment(content_type: &str) -> AttachmentInfo {
251 serde_json::from_value(serde_json::json!({
252 "content_type": content_type,
253 "name": null,
254 "url": null,
255 "text": null,
256 }))
257 .unwrap()
258 }
259
260 fn graph_message(value: serde_json::Value) -> Message {
261 serde_json::from_value(value).unwrap()
262 }
263
84 #[test]
264 #[test]
85 fn strips_tags_and_collapses_whitespace() {
265 fn strips_tags_and_collapses_whitespace() {
86 assert_eq!(
266 assert_eq!(
@@ -108,4 +288,176 @@ mod tests {
108 fn plain_text_bodies_keep_entities_decoded() {
288 fn plain_text_bodies_keep_entities_decoded() {
109 assert_eq!(preview_text("a &amp; b").as_deref(), Some("a & b"));
289 assert_eq!(preview_text("a &amp; b").as_deref(), Some("a & b"));
110 }
290 }
291
292 #[test]
293 fn emoji_and_mentions_read_like_teams() {
294 let html = r#"<p><at id="0">Robin Beck</at>&nbsp;kannst du?&nbsp;<emoji id="smile" alt="🙂" title="Smile"></emoji></p>"#;
295 assert_eq!(
296 preview_text(html).as_deref(),
297 Some("Robin Beck kannst du? 🙂")
298 );
299 }
300
301 #[test]
302 fn reply_quotes_are_left_out() {
303 let html = r#"<blockquote itemtype="http://schema.skype.com/Reply" itemid="1"><strong>Ada</strong><p>old</p></blockquote><p>new</p>"#;
304 assert_eq!(preview_text(html).as_deref(), Some("new"));
305 }
306
307 #[test]
308 fn image_only_message_says_sent_an_image() {
309 let html = r#"<p><img src="https://graph.microsoft.com/v1.0/chats/19:x/messages/1/hostedContents/aWQ9/$value" alt="image" width="447" height="250" itemid="0-nde-d3-x"></p>"#;
310 assert_eq!(message_preview(html, &[]).as_deref(), Some(IMAGE_PREVIEW));
311 }
312
313 #[test]
314 fn text_with_an_image_keeps_only_the_text() {
315 let html = r#"<p>this is from QA:</p><p><img src="https://graph.microsoft.com/v1.0/x/$value"></p><p>&nbsp;</p>"#;
316 assert_eq!(
317 message_preview(html, &[]).as_deref(),
318 Some("this is from QA:")
319 );
320 }
321
322 #[test]
323 fn giphy_reads_as_gif() {
324 let html = r#"<p>&nbsp;</p><img alt="Happy Birthday Reaction GIF by The Office (GIF Image)" height="250" width="300" src="https://media2.giphy.com/media/g5R9dok94mrIvplmZd/giphy.gif?cid=x&amp;ct=g"><p>&nbsp;</p>"#;
325 assert_eq!(message_preview(html, &[]).as_deref(), Some(GIF_PREVIEW));
326 }
327
328 #[test]
329 fn inline_video_reads_as_video() {
330 let html = r#"<p>look</p><video src="https://x/v.mp4"></video>"#;
331 assert_eq!(message_preview(html, &[]).as_deref(), Some(VIDEO_PREVIEW));
332 }
333
334 #[test]
335 fn attachment_only_bodies_get_a_label() {
336 let body = r#"<attachment id="1792149081221"></attachment>"#;
337 let cases = [
338 (FORWARDED_CONTENT_TYPE, FORWARD_PREVIEW),
339 ("reference", FILE_PREVIEW),
340 ("application/vnd.microsoft.card.adaptive", CARD_PREVIEW),
341 ("application/vnd.microsoft.card.hero", CARD_PREVIEW),
342 (AUDIO_CARD_TYPE, AUDIO_PREVIEW),
343 (LOOP_CARD_TYPE, LOOP_PREVIEW),
344 ];
345 for (content_type, expected) in cases {
346 assert_eq!(
347 message_preview(body, &[attachment(content_type)]).as_deref(),
348 Some(expected),
349 "{content_type}"
350 );
351 }
352 assert_eq!(message_preview(body, &[]), None);
353 }
354
355 #[test]
356 fn a_file_with_text_shows_the_text() {
357 let body = r#"Hi Philipp,<br>Kann's dir zeigen.<attachment id="0cf57a46"></attachment>"#;
358 assert_eq!(
359 message_preview(body, &[attachment("reference")]).as_deref(),
360 Some("Hi Philipp, Kann's dir zeigen.")
361 );
362 }
363
364 #[test]
365 fn a_reply_shows_the_reply_text() {
366 let body = "<attachment id=\"1792136042729\"></attachment>\nwas war mit dependabot?";
367 assert_eq!(
368 message_preview(body, &[attachment("messageReference")]).as_deref(),
369 Some("was war mit dependabot?")
370 );
371 }
372
373 #[test]
374 fn graph_recording_and_transcript_events_have_teams_text() {
375 let event = |detail: serde_json::Value| {
376 OwnedPreview::from_graph(&graph_message(serde_json::json!({
377 "id": "1",
378 "messageType": "systemEventMessage",
379 "body": {"contentType": "html", "content": "<systemEventMessage/>"},
380 "from": {"user": {"id": "u1", "displayName": "Ada Lovelace"}},
381 "eventDetail": detail,
382 })))
383 };
384 let ready = event(serde_json::json!({
385 "@odata.type": RECORDING_TYPE,
386 "callRecordingStatus": "success",
387 }));
388 assert_eq!(ready.text.as_deref(), Some(RECORDING_READY_PREVIEW));
389 assert!(ready.system && !ready.call);
390 assert_eq!(ready.sender_name, None);
391 let started = event(serde_json::json!({
392 "@odata.type": RECORDING_TYPE,
393 "callRecordingStatus": "initial",
394 }));
395 assert_eq!(started.text.as_deref(), Some(RECORDING_STARTED_PREVIEW));
396 let transcript = event(serde_json::json!({"@odata.type": TRANSCRIPT_TYPE}));
397 assert_eq!(transcript.text.as_deref(), Some(TRANSCRIPT_PREVIEW));
398 }
399
400 #[test]
401 fn graph_member_events_say_added_or_joined() {
402 let added = |members: serde_json::Value| {
403 OwnedPreview::from_graph(&graph_message(serde_json::json!({
404 "id": "1",
405 "messageType": "systemEventMessage",
406 "eventDetail": {
407 "@odata.type": MEMBERS_ADDED_TYPE,
408 "members": members,
409 "initiator": {"user": {"id": "me"}},
410 },
411 })))
412 .text
413 };
414 assert_eq!(
415 added(serde_json::json!([{"id": "other"}])).as_deref(),
416 Some(USER_ADDED_PREVIEW)
417 );
418 assert_eq!(
419 added(serde_json::json!([{"id": "me"}])).as_deref(),
420 Some(USER_JOINED_PREVIEW)
421 );
422 }
423
424 #[test]
425 fn graph_call_events_are_marked_to_keep_the_previous_line() {
426 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
427 "id": "1",
428 "messageType": "systemEventMessage",
429 "eventDetail": {
430 "@odata.type": "#microsoft.graph.callEndedEventMessageDetail",
431 "callId": "c1",
432 "callDuration": "PT30S",
433 "callEventType": "call",
434 },
435 })));
436 assert!(preview.call);
437 assert_eq!(preview.text, None);
438 }
439
440 #[test]
441 fn graph_deleted_flag_marks_the_preview_deleted() {
442 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
443 "id": "1",
444 "messageType": "message",
445 "isDeleted": true,
446 "body": {"contentType": "html", "content": "secret"},
447 })));
448 assert!(preview.deleted);
449 assert_eq!(preview.text, None);
450 }
451
452 #[test]
453 fn graph_image_preview_says_sent_an_image() {
454 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
455 "id": "1",
456 "messageType": "message",
457 "body": {"contentType": "html", "content": "<p><img src=\"https://graph.microsoft.com/x/$value\"></p>"},
458 "from": {"user": {"id": "u1", "displayName": "Lukas Berg"}},
459 })));
460 assert_eq!(preview.text.as_deref(), Some(IMAGE_PREVIEW));
461 assert_eq!(preview.sender_name.as_deref(), Some("Lukas Berg"));
462 }
111}
463}
crates/core/tests/engine.rs +34 −1
@@ -2483,7 +2483,10 @@ async fn sidebar_sync_fills_the_last_message_preview() {
2483 2483 let gone = by_id("c-gone");
2484 2484 assert!(gone.last_message_deleted);
2485 2485 assert_eq!(gone.last_message_preview, None);
2486 assert_eq!(by_id("c-image").last_message_preview, None);
2486 assert_eq!(
2487 by_id("c-image").last_message_preview.as_deref(),
2488 Some("Sent an image")
2489 );
2487 2490 assert_eq!(
2488 2491 by_id("c-text")
2489 2492 .last_message_preview
@@ -2524,6 +2527,36 @@ async fn a_newer_message_updates_the_preview_and_announces_the_sidebar() {
2524 2527 assert!(seen.contains(&CoreEvent::SidebarChanged));
2525 2528 }
2526 2529
2530 #[tokio::test]
2531 async fn a_newer_call_event_leaves_the_preview_alone() {
2532 let fake = Arc::new(Fake::default());
2533 let mut before = numbered(3);
2534 before.push(message(4, 30, "<p>before the call</p>"));
2535 fake.set_chat_messages(before.clone());
2536 let engine = chat_engine(&fake, SyncConfig::default()).await;
2537 engine.fetch_newer(CHAT).await.unwrap();
2538 let call: Message = serde_json::from_value(json!({
2539 "id": "call", "messageType": "systemEventMessage",
2540 "createdDateTime": (base() + Duration::minutes(40)).to_rfc3339(),
2541 "body": {"contentType": "html", "content": "<systemEventMessage/>"},
2542 "eventDetail": {
2543 "@odata.type": "#microsoft.graph.callEndedEventMessageDetail",
2544 "callId": "c1", "callDuration": "PT1M2S", "callEventType": "call",
2545 "callParticipants": [],
2546 },
2547 }))
2548 .unwrap();
2549 before.push(call);
2550 fake.set_chat_messages(before);
2551 engine.fetch_newer(CHAT).await.unwrap();
2552 let record = engine.sidebar().unwrap().chats.remove(0);
2553 assert_eq!(
2554 record.last_message_preview.as_deref(),
2555 Some("before the call")
2556 );
2557 assert_eq!(record.last_message_at, Some(base() + Duration::minutes(30)));
2558 }
2559
2527 2560 #[tokio::test]
2528 2561 async fn an_edited_old_message_leaves_the_preview_alone() {
2529 2562 let fake = Arc::new(Fake::default());
@@ -2483,7 +2483,10 @@ async fn sidebar_sync_fills_the_last_message_preview() {
2483 let gone = by_id("c-gone");
2483 let gone = by_id("c-gone");
2484 assert!(gone.last_message_deleted);
2484 assert!(gone.last_message_deleted);
2485 assert_eq!(gone.last_message_preview, None);
2485 assert_eq!(gone.last_message_preview, None);
2486 assert_eq!(by_id("c-image").last_message_preview, None);
2486 assert_eq!(
2487 by_id("c-image").last_message_preview.as_deref(),
2488 Some("Sent an image")
2489 );
2487 assert_eq!(
2490 assert_eq!(
2488 by_id("c-text")
2491 by_id("c-text")
2489 .last_message_preview
2492 .last_message_preview
@@ -2524,6 +2527,36 @@ async fn a_newer_message_updates_the_preview_and_announces_the_sidebar() {
2524 assert!(seen.contains(&CoreEvent::SidebarChanged));
2527 assert!(seen.contains(&CoreEvent::SidebarChanged));
2525}
2528}
2526
2529
2530#[tokio::test]
2531async fn a_newer_call_event_leaves_the_preview_alone() {
2532 let fake = Arc::new(Fake::default());
2533 let mut before = numbered(3);
2534 before.push(message(4, 30, "<p>before the call</p>"));
2535 fake.set_chat_messages(before.clone());
2536 let engine = chat_engine(&fake, SyncConfig::default()).await;
2537 engine.fetch_newer(CHAT).await.unwrap();
2538 let call: Message = serde_json::from_value(json!({
2539 "id": "call", "messageType": "systemEventMessage",
2540 "createdDateTime": (base() + Duration::minutes(40)).to_rfc3339(),
2541 "body": {"contentType": "html", "content": "<systemEventMessage/>"},
2542 "eventDetail": {
2543 "@odata.type": "#microsoft.graph.callEndedEventMessageDetail",
2544 "callId": "c1", "callDuration": "PT1M2S", "callEventType": "call",
2545 "callParticipants": [],
2546 },
2547 }))
2548 .unwrap();
2549 before.push(call);
2550 fake.set_chat_messages(before);
2551 engine.fetch_newer(CHAT).await.unwrap();
2552 let record = engine.sidebar().unwrap().chats.remove(0);
2553 assert_eq!(
2554 record.last_message_preview.as_deref(),
2555 Some("before the call")
2556 );
2557 assert_eq!(record.last_message_at, Some(base() + Duration::minutes(30)));
2558}
2559
2527#[tokio::test]
2560#[tokio::test]
2528async fn an_edited_old_message_leaves_the_preview_alone() {
2561async fn an_edited_old_message_leaves_the_preview_alone() {
2529 let fake = Arc::new(Fake::default());
2562 let fake = Arc::new(Fake::default());
crates/graph/src/models.rs +2 −1
@@ -109,6 +109,7 @@ pub struct Message {
109 109 pub last_modified_date_time: Option<DateTime<Utc>>,
110 110 pub last_edited_date_time: Option<DateTime<Utc>>,
111 111 pub deleted_date_time: Option<DateTime<Utc>>,
112 pub is_deleted: Option<bool>,
112 113 pub reply_to_id: Option<String>,
113 114 pub subject: Option<String>,
114 115 pub from: Option<Sender>,
@@ -126,7 +127,7 @@ pub struct Message {
126 127
127 128 impl Message {
128 129 pub fn is_deleted(&self) -> bool {
129 self.deleted_date_time.is_some()
130 self.deleted_date_time.is_some() || self.is_deleted == Some(true)
130 131 }
131 132 }
132 133
@@ -109,6 +109,7 @@ pub struct Message {
109 pub last_modified_date_time: Option<DateTime<Utc>>,
109 pub last_modified_date_time: Option<DateTime<Utc>>,
110 pub last_edited_date_time: Option<DateTime<Utc>>,
110 pub last_edited_date_time: Option<DateTime<Utc>>,
111 pub deleted_date_time: Option<DateTime<Utc>>,
111 pub deleted_date_time: Option<DateTime<Utc>>,
112 pub is_deleted: Option<bool>,
112 pub reply_to_id: Option<String>,
113 pub reply_to_id: Option<String>,
113 pub subject: Option<String>,
114 pub subject: Option<String>,
114 pub from: Option<Sender>,
115 pub from: Option<Sender>,
@@ -126,7 +127,7 @@ pub struct Message {
126
127
127impl Message {
128impl Message {
128 pub fn is_deleted(&self) -> bool {
129 pub fn is_deleted(&self) -> bool {
129 self.deleted_date_time.is_some()
130 self.deleted_date_time.is_some() || self.is_deleted == Some(true)
130 }
131 }
131}
132}
132
133
crates/store/src/chats.rs +7 −4
@@ -31,10 +31,11 @@ impl Store {
31 31 excluded.last_message_at IS NULL
32 32 OR COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at) IS NULL
33 33 OR excluded.last_message_at > COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at)
34 ) END, last_message_preview = excluded.last_message_preview,
35 last_message_sender_id = excluded.last_message_sender_id,
36 last_message_sender_name = excluded.last_message_sender_name,
37 last_message_deleted = excluded.last_message_deleted",
34 ) END,
35 last_message_preview = CASE WHEN ?13 THEN chats.last_message_preview ELSE excluded.last_message_preview END,
36 last_message_sender_id = CASE WHEN ?13 THEN chats.last_message_sender_id ELSE excluded.last_message_sender_id END,
37 last_message_sender_name = CASE WHEN ?13 THEN chats.last_message_sender_name ELSE excluded.last_message_sender_name END,
38 last_message_deleted = CASE WHEN ?13 THEN chats.last_message_deleted ELSE excluded.last_message_deleted END",
38 39 )?;
39 40 let mut clear_members =
40 41 transaction.prepare_cached("DELETE FROM chat_members WHERE chat_id = ?1")?;
@@ -55,6 +56,7 @@ impl Store {
55 56 chat.last_message_sender_name,
56 57 chat.last_message_deleted,
57 58 chat.last_event_system,
59 chat.last_event_call,
58 60 ])?;
59 61 clear_members.execute([&chat.id])?;
60 62 for (position, member) in chat.members.iter().enumerate() {
@@ -214,6 +216,7 @@ fn chat_from_row(row: &Row<'_>) -> rusqlite::Result<ChatRecord> {
214 216 last_message_deleted: row.get(10)?,
215 217 muted: row.get(11)?,
216 218 last_event_system: false,
219 last_event_call: false,
217 220 })
218 221 }
219 222
@@ -31,10 +31,11 @@ impl Store {
31 excluded.last_message_at IS NULL
31 excluded.last_message_at IS NULL
32 OR COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at) IS NULL
32 OR COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at) IS NULL
33 OR excluded.last_message_at > COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at)
33 OR excluded.last_message_at > COALESCE(MAX(chats.last_read_at, excluded.last_read_at), chats.last_read_at, excluded.last_read_at)
34 ) END, last_message_preview = excluded.last_message_preview,
34 ) END,
35 last_message_sender_id = excluded.last_message_sender_id,
35 last_message_preview = CASE WHEN ?13 THEN chats.last_message_preview ELSE excluded.last_message_preview END,
36 last_message_sender_name = excluded.last_message_sender_name,
36 last_message_sender_id = CASE WHEN ?13 THEN chats.last_message_sender_id ELSE excluded.last_message_sender_id END,
37 last_message_deleted = excluded.last_message_deleted",
37 last_message_sender_name = CASE WHEN ?13 THEN chats.last_message_sender_name ELSE excluded.last_message_sender_name END,
38 last_message_deleted = CASE WHEN ?13 THEN chats.last_message_deleted ELSE excluded.last_message_deleted END",
38 )?;
39 )?;
39 let mut clear_members =
40 let mut clear_members =
40 transaction.prepare_cached("DELETE FROM chat_members WHERE chat_id = ?1")?;
41 transaction.prepare_cached("DELETE FROM chat_members WHERE chat_id = ?1")?;
@@ -55,6 +56,7 @@ impl Store {
55 chat.last_message_sender_name,
56 chat.last_message_sender_name,
56 chat.last_message_deleted,
57 chat.last_message_deleted,
57 chat.last_event_system,
58 chat.last_event_system,
59 chat.last_event_call,
58 ])?;
60 ])?;
59 clear_members.execute([&chat.id])?;
61 clear_members.execute([&chat.id])?;
60 for (position, member) in chat.members.iter().enumerate() {
62 for (position, member) in chat.members.iter().enumerate() {
@@ -214,6 +216,7 @@ fn chat_from_row(row: &Row<'_>) -> rusqlite::Result<ChatRecord> {
214 last_message_deleted: row.get(10)?,
216 last_message_deleted: row.get(10)?,
215 muted: row.get(11)?,
217 muted: row.get(11)?,
216 last_event_system: false,
218 last_event_system: false,
219 last_event_call: false,
217 })
220 })
218}
221}
219
222
crates/store/src/models.rs +1 −0
@@ -24,6 +24,7 @@ pub struct ChatRecord {
24 24 pub last_message_sender_name: Option<String>,
25 25 pub last_message_deleted: bool,
26 26 pub last_event_system: bool,
27 pub last_event_call: bool,
27 28 }
28 29
29 30 impl ChatRecord {
@@ -24,6 +24,7 @@ pub struct ChatRecord {
24 pub last_message_sender_name: Option<String>,
24 pub last_message_sender_name: Option<String>,
25 pub last_message_deleted: bool,
25 pub last_message_deleted: bool,
26 pub last_event_system: bool,
26 pub last_event_system: bool,
27 pub last_event_call: bool,
27}
28}
28
29
29impl ChatRecord {
30impl ChatRecord {
crates/store/tests/store.rs +36 −0
@@ -23,6 +23,42 @@ fn a_system_event_keeps_the_previous_unread_state() {
23 23 }
24 24 }
25 25
26 #[test]
27 fn a_call_event_keeps_the_previous_preview() {
28 let store = Store::open_in_memory().unwrap();
29 let mut seeded = chat("chat-call", "Planning", Some(at(5)));
30 seeded.last_message_preview = Some("See you there".to_owned());
31 seeded.last_message_sender_id = Some("user-ada".to_owned());
32 seeded.last_message_sender_name = Some("Ada Example".to_owned());
33 store.upsert_chats(&[seeded]).unwrap();
34
35 let mut call = chat("chat-call", "Planning", Some(at(12)));
36 call.last_event_system = true;
37 call.last_event_call = true;
38 store.upsert_chats(&[call]).unwrap();
39 let stored = store.chat("chat-call").unwrap().unwrap();
40 assert_eq!(
41 stored.last_message_preview.as_deref(),
42 Some("See you there")
43 );
44 assert_eq!(
45 stored.last_message_sender_name.as_deref(),
46 Some("Ada Example")
47 );
48 assert_eq!(stored.last_message_at, Some(at(12)));
49
50 let mut recording = chat("chat-call", "Planning", Some(at(14)));
51 recording.last_event_system = true;
52 recording.last_message_preview = Some("Recording is ready".to_owned());
53 store.upsert_chats(&[recording]).unwrap();
54 let stored = store.chat("chat-call").unwrap().unwrap();
55 assert_eq!(
56 stored.last_message_preview.as_deref(),
57 Some("Recording is ready")
58 );
59 assert_eq!(stored.last_message_sender_name, None);
60 }
61
26 62 fn at(minute: u32) -> DateTime<Utc> {
27 63 Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap()
28 64 }
@@ -23,6 +23,42 @@ fn a_system_event_keeps_the_previous_unread_state() {
23 }
23 }
24}
24}
25
25
26#[test]
27fn a_call_event_keeps_the_previous_preview() {
28 let store = Store::open_in_memory().unwrap();
29 let mut seeded = chat("chat-call", "Planning", Some(at(5)));
30 seeded.last_message_preview = Some("See you there".to_owned());
31 seeded.last_message_sender_id = Some("user-ada".to_owned());
32 seeded.last_message_sender_name = Some("Ada Example".to_owned());
33 store.upsert_chats(&[seeded]).unwrap();
34
35 let mut call = chat("chat-call", "Planning", Some(at(12)));
36 call.last_event_system = true;
37 call.last_event_call = true;
38 store.upsert_chats(&[call]).unwrap();
39 let stored = store.chat("chat-call").unwrap().unwrap();
40 assert_eq!(
41 stored.last_message_preview.as_deref(),
42 Some("See you there")
43 );
44 assert_eq!(
45 stored.last_message_sender_name.as_deref(),
46 Some("Ada Example")
47 );
48 assert_eq!(stored.last_message_at, Some(at(12)));
49
50 let mut recording = chat("chat-call", "Planning", Some(at(14)));
51 recording.last_event_system = true;
52 recording.last_message_preview = Some("Recording is ready".to_owned());
53 store.upsert_chats(&[recording]).unwrap();
54 let stored = store.chat("chat-call").unwrap().unwrap();
55 assert_eq!(
56 stored.last_message_preview.as_deref(),
57 Some("Recording is ready")
58 );
59 assert_eq!(stored.last_message_sender_name, None);
60}
61
26fn at(minute: u32) -> DateTime<Utc> {
62fn at(minute: u32) -> DateTime<Utc> {
27 Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap()
63 Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap()
28}
64}