BlueGit

ict rusty-teams

Files

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

preview.rs

preview.rs 19.3 KiB Download Raw
1use graph::Message;
2use serde_json::Value;
3use store::{ChatPreview, MessageRecord};
4
5use crate::call_event::{CallEvent, CallPhase, call_event};
6use crate::external_image::is_giphy_url;
7use crate::forwarded::FORWARDED_CONTENT_TYPE;
8use crate::roster_event::{RosterChange, roster_event};
9use crate::spans::{Span, html_to_spans};
10use crate::stored::{AttachmentInfo, attachments};
11
12const MAX_PREVIEW_CHARS: usize = 200;
13
14pub const IMAGE_PREVIEW: &str = "Sent an image";
15pub const GIF_PREVIEW: &str = "\u{1F4F7} GIF";
16pub const VIDEO_PREVIEW: &str = "\u{1F3A5} Video";
17pub const FILE_PREVIEW: &str = "Sent a file";
18pub const CARD_PREVIEW: &str = "Sent a card";
19pub const FORWARD_PREVIEW: &str = "Forwarded a message";
20pub const AUDIO_PREVIEW: &str = "\u{1F399} Audio message";
21pub const LOOP_PREVIEW: &str = "Loop component";
22pub const RECORDING_STARTED_PREVIEW: &str = "Recording has started";
23pub const RECORDING_STOPPED_PREVIEW: &str = "Recording has stopped";
24pub const RECORDING_READY_PREVIEW: &str = "Recording is ready";
25pub const TRANSCRIPT_PREVIEW: &str = "Transcript is available";
26pub const USER_ADDED_PREVIEW: &str = "User added";
27pub const USER_JOINED_PREVIEW: &str = "User joined";
28const EVENT_PREVIEWS: [&str; 6] = [
29 RECORDING_STARTED_PREVIEW,
30 RECORDING_STOPPED_PREVIEW,
31 RECORDING_READY_PREVIEW,
32 TRANSCRIPT_PREVIEW,
33 USER_ADDED_PREVIEW,
34 USER_JOINED_PREVIEW,
35];
36
37const AUDIO_CARD_TYPE: &str = "application/vnd.microsoft.card.audio";
38const LOOP_CARD_TYPE: &str = "application/vnd.microsoft.card.fluidEmbedCard";
39const FILE_CONTENT_TYPE: &str = "reference";
40const RECORDING_TYPE: &str = "#microsoft.graph.callRecordingEventMessageDetail";
41const TRANSCRIPT_TYPE: &str = "#microsoft.graph.callTranscriptEventMessageDetail";
42const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
43const MEMBERS_JOINED_TYPE: &str = "#microsoft.graph.membersJoinedEventMessageDetail";
44
45#[derive(Default)]
46struct BodyParts {
47 text: String,
48 images: usize,
49 gifs: usize,
50}
51
52/// Plain text of a message body as the chat list shows it: emoji as glyphs, mentions by name, reply quotes and images dropped.
53pub fn preview_text(html: &str) -> Option<String> {
54 let mut parts = BodyParts::default();
55 collect(&html_to_spans(html), &mut parts);
56 collapse(&parts.text)
57}
58
59pub fn is_event_preview(text: &str) -> bool {
60 EVENT_PREVIEWS.contains(&text)
61}
62
63/// The chat list line for a message, with the Teams labels for bodies without text.
64pub fn message_preview(html: &str, attachments: &[AttachmentInfo]) -> Option<String> {
65 if html.contains("<video") {
66 return Some(VIDEO_PREVIEW.to_owned());
67 }
68 let mut parts = BodyParts::default();
69 collect(&html_to_spans(html), &mut parts);
70 if let Some(text) = collapse(&parts.text) {
71 return Some(text);
72 }
73 if parts.gifs > 0 {
74 return Some(GIF_PREVIEW.to_owned());
75 }
76 if parts.images > 0 {
77 return Some(IMAGE_PREVIEW.to_owned());
78 }
79 attachment_label(attachments).map(str::to_owned)
80}
81
82fn attachment_label(attachments: &[AttachmentInfo]) -> Option<&'static str> {
83 let has_type = |wanted: &str| {
84 attachments
85 .iter()
86 .any(|attachment| attachment.content_type.as_deref() == Some(wanted))
87 };
88 if has_type(FORWARDED_CONTENT_TYPE) {
89 Some(FORWARD_PREVIEW)
90 } else if has_type(FILE_CONTENT_TYPE) {
91 Some(FILE_PREVIEW)
92 } else if has_type(AUDIO_CARD_TYPE) {
93 Some(AUDIO_PREVIEW)
94 } else if has_type(LOOP_CARD_TYPE) {
95 Some(LOOP_PREVIEW)
96 } else if attachments.iter().any(AttachmentInfo::is_card) {
97 Some(CARD_PREVIEW)
98 } else {
99 None
100 }
101}
102
103fn collect(spans: &[Span], parts: &mut BodyParts) {
104 for span in spans {
105 match span {
106 Span::Text(value) | Span::Code(value) => parts.text.push_str(value),
107 Span::CodeBlock { code, .. } => {
108 parts.text.push(' ');
109 parts.text.push_str(code);
110 parts.text.push(' ');
111 }
112 Span::Mention { name, .. } => parts.text.push_str(name),
113 Span::Quote { .. } => {}
114 Span::Image { hosted_content_url } if is_giphy_url(hosted_content_url) => {
115 parts.gifs += 1
116 }
117 Span::Image { .. } => parts.images += 1,
118 Span::LineBreak | Span::Rule => parts.text.push(' '),
119 Span::Bold(children)
120 | Span::Italic(children)
121 | Span::Strike(children)
122 | Span::Superscript(children)
123 | Span::Subscript(children)
124 | Span::Sized(_, children)
125 | Span::Underline(children)
126 | Span::Colored { children, .. }
127 | Span::Indent { children, .. }
128 | Span::Link { children, .. } => collect(children, parts),
129 Span::Heading { children, .. } | Span::BlockQuote(children) => {
130 parts.text.push(' ');
131 collect(children, parts);
132 parts.text.push(' ');
133 }
134 Span::List { items, .. } => {
135 for item in items {
136 parts.text.push(' ');
137 collect(item, parts);
138 }
139 parts.text.push(' ');
140 }
141 Span::Table { rows, .. } => {
142 for cell in rows.iter().flatten() {
143 parts.text.push(' ');
144 collect(cell, parts);
145 }
146 parts.text.push(' ');
147 }
148 }
149 }
150}
151
152fn collapse(text: &str) -> Option<String> {
153 let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" ");
154 if collapsed.is_empty() {
155 return None;
156 }
157 Some(collapsed.chars().take(MAX_PREVIEW_CHARS).collect())
158}
159
160fn system_event_preview(detail: &Value) -> Option<&'static str> {
161 match detail.get("@odata.type")?.as_str()? {
162 RECORDING_TYPE => match detail.get("callRecordingStatus")?.as_str()? {
163 "initial" => Some(RECORDING_STARTED_PREVIEW),
164 "chunkFinished" => Some(RECORDING_STOPPED_PREVIEW),
165 "success" => Some(RECORDING_READY_PREVIEW),
166 _ => None,
167 },
168 TRANSCRIPT_TYPE => Some(TRANSCRIPT_PREVIEW),
169 MEMBERS_JOINED_TYPE => Some(USER_JOINED_PREVIEW),
170 MEMBERS_ADDED_TYPE if added_only_self(detail) => Some(USER_JOINED_PREVIEW),
171 MEMBERS_ADDED_TYPE => Some(USER_ADDED_PREVIEW),
172 _ => None,
173 }
174}
175
176fn call_phase_preview(phase: CallPhase) -> Option<&'static str> {
177 match phase {
178 CallPhase::RecordingStarted => Some(RECORDING_STARTED_PREVIEW),
179 CallPhase::RecordingStopped => Some(RECORDING_STOPPED_PREVIEW),
180 CallPhase::RecordingSaved => Some(RECORDING_READY_PREVIEW),
181 CallPhase::TranscriptStarted => Some(TRANSCRIPT_PREVIEW),
182 CallPhase::Started | CallPhase::Ended => None,
183 }
184}
185
186/// Teams leaves call start and end out of the chat list line; recordings and transcripts stay in it.
187pub(crate) fn keeps_previous_line(record: &MessageRecord) -> bool {
188 call_event(record).is_some_and(|event| event.phase.is_call())
189}
190
191fn added_only_self(detail: &Value) -> bool {
192 let Some(initiator) = detail.pointer("/initiator/user/id").and_then(Value::as_str) else {
193 return false;
194 };
195 let members = detail
196 .get("members")
197 .and_then(Value::as_array)
198 .map(Vec::as_slice)
199 .unwrap_or_default();
200 !members.is_empty()
201 && members
202 .iter()
203 .all(|member| member.get("id").and_then(Value::as_str) == Some(initiator))
204}
205
206pub(crate) struct OwnedPreview {
207 pub text: Option<String>,
208 pub sender_id: Option<String>,
209 pub sender_name: Option<String>,
210 pub deleted: bool,
211 pub system: bool,
212 pub call: bool,
213}
214
215impl OwnedPreview {
216 pub(crate) fn from_graph(message: &Message) -> Self {
217 let regular = message
218 .message_type
219 .as_deref()
220 .is_none_or(|kind| kind == "message");
221 let deleted = message.is_deleted();
222 let detail = message.event_detail.as_ref().filter(|_| !regular);
223 let call = detail
224 .and_then(CallEvent::from_graph)
225 .is_some_and(|event| event.phase.is_call());
226 let text = if deleted {
227 None
228 } else if regular {
229 message
230 .body
231 .as_ref()
232 .and_then(|body| body.content.as_deref())
233 .and_then(|html| message_preview(html, &[]))
234 } else {
235 detail.and_then(system_event_preview).map(str::to_owned)
236 };
237 let sender = message.from.as_ref().filter(|_| regular);
238 OwnedPreview {
239 text,
240 sender_id: sender
241 .and_then(|sender| sender.user_id())
242 .map(str::to_owned),
243 sender_name: sender
244 .and_then(|sender| sender.display_name())
245 .map(str::to_owned),
246 deleted,
247 system: !regular,
248 call,
249 }
250 }
251
252 pub(crate) fn from_record(record: &MessageRecord) -> Self {
253 let event = call_event(record);
254 let roster = roster_event(record);
255 let text = if record.deleted {
256 None
257 } else if let Some(event) = &event {
258 call_phase_preview(event.phase).map(str::to_owned)
259 } else if let Some(roster) = &roster {
260 (roster.change == RosterChange::Added).then(|| USER_ADDED_PREVIEW.to_owned())
261 } else {
262 message_preview(&record.body_html, &attachments(record))
263 };
264 let sender = event.is_none() && roster.is_none();
265 OwnedPreview {
266 text,
267 sender_id: record.sender_id.clone().filter(|_| sender),
268 sender_name: record.sender_name.clone().filter(|_| sender),
269 deleted: record.deleted,
270 system: !sender,
271 call: event.is_some_and(|event| event.phase.is_call()),
272 }
273 }
274
275 pub(crate) fn as_store(&self) -> ChatPreview<'_> {
276 ChatPreview {
277 text: self.text.as_deref(),
278 sender_id: self.sender_id.as_deref(),
279 sender_name: self.sender_name.as_deref(),
280 deleted: self.deleted,
281 }
282 }
283}
284
285#[cfg(test)]
286mod tests {
287 use super::*;
288
289 fn attachment(content_type: &str) -> AttachmentInfo {
290 serde_json::from_value(serde_json::json!({
291 "content_type": content_type,
292 "name": null,
293 "url": null,
294 "text": null,
295 }))
296 .unwrap()
297 }
298
299 fn graph_message(value: serde_json::Value) -> Message {
300 serde_json::from_value(value).unwrap()
301 }
302
303 #[test]
304 fn strips_tags_and_collapses_whitespace() {
305 assert_eq!(
306 preview_text("<p>Hello <b>big</b>\n world</p><p>second</p>").as_deref(),
307 Some("Hello big world second")
308 );
309 }
310
311 #[test]
312 fn image_only_bodies_are_empty() {
313 assert_eq!(preview_text("<p><img src=\"x\"></p>"), None);
314 assert_eq!(preview_text(" "), None);
315 }
316
317 #[test]
318 fn long_text_is_cut_to_the_limit() {
319 let long = "a ".repeat(400);
320 assert_eq!(
321 preview_text(&long).unwrap().chars().count(),
322 MAX_PREVIEW_CHARS
323 );
324 }
325
326 #[test]
327 fn plain_text_bodies_keep_entities_decoded() {
328 assert_eq!(preview_text("a &amp; b").as_deref(), Some("a & b"));
329 }
330
331 #[test]
332 fn emoji_and_mentions_read_like_teams() {
333 let html = r#"<p><at id="0">Robin Beck</at>&nbsp;kannst du?&nbsp;<emoji id="smile" alt="🙂" title="Smile"></emoji></p>"#;
334 assert_eq!(
335 preview_text(html).as_deref(),
336 Some("Robin Beck kannst du? 🙂")
337 );
338 }
339
340 #[test]
341 fn reply_quotes_are_left_out() {
342 let html = r#"<blockquote itemtype="http://schema.skype.com/Reply" itemid="1"><strong>Ada</strong><p>old</p></blockquote><p>new</p>"#;
343 assert_eq!(preview_text(html).as_deref(), Some("new"));
344 }
345
346 #[test]
347 fn image_only_message_says_sent_an_image() {
348 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>"#;
349 assert_eq!(message_preview(html, &[]).as_deref(), Some(IMAGE_PREVIEW));
350 }
351
352 #[test]
353 fn text_with_an_image_keeps_only_the_text() {
354 let html = r#"<p>this is from QA:</p><p><img src="https://graph.microsoft.com/v1.0/x/$value"></p><p>&nbsp;</p>"#;
355 assert_eq!(
356 message_preview(html, &[]).as_deref(),
357 Some("this is from QA:")
358 );
359 }
360
361 #[test]
362 fn giphy_reads_as_gif() {
363 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>"#;
364 assert_eq!(message_preview(html, &[]).as_deref(), Some(GIF_PREVIEW));
365 }
366
367 #[test]
368 fn inline_video_reads_as_video() {
369 let html = r#"<p>look</p><video src="https://x/v.mp4"></video>"#;
370 assert_eq!(message_preview(html, &[]).as_deref(), Some(VIDEO_PREVIEW));
371 }
372
373 #[test]
374 fn attachment_only_bodies_get_a_label() {
375 let body = r#"<attachment id="1792149081221"></attachment>"#;
376 let cases = [
377 (FORWARDED_CONTENT_TYPE, FORWARD_PREVIEW),
378 ("reference", FILE_PREVIEW),
379 ("application/vnd.microsoft.card.adaptive", CARD_PREVIEW),
380 ("application/vnd.microsoft.card.hero", CARD_PREVIEW),
381 (AUDIO_CARD_TYPE, AUDIO_PREVIEW),
382 (LOOP_CARD_TYPE, LOOP_PREVIEW),
383 ];
384 for (content_type, expected) in cases {
385 assert_eq!(
386 message_preview(body, &[attachment(content_type)]).as_deref(),
387 Some(expected),
388 "{content_type}"
389 );
390 }
391 assert_eq!(message_preview(body, &[]), None);
392 }
393
394 #[test]
395 fn a_file_with_text_shows_the_text() {
396 let body = r#"Hi Philipp,<br>Kann's dir zeigen.<attachment id="0cf57a46"></attachment>"#;
397 assert_eq!(
398 message_preview(body, &[attachment("reference")]).as_deref(),
399 Some("Hi Philipp, Kann's dir zeigen.")
400 );
401 }
402
403 #[test]
404 fn a_reply_shows_the_reply_text() {
405 let body = "<attachment id=\"1792136042729\"></attachment>\nwas war mit dependabot?";
406 assert_eq!(
407 message_preview(body, &[attachment("messageReference")]).as_deref(),
408 Some("was war mit dependabot?")
409 );
410 }
411
412 #[test]
413 fn graph_recording_and_transcript_events_have_teams_text() {
414 let event = |detail: serde_json::Value| {
415 OwnedPreview::from_graph(&graph_message(serde_json::json!({
416 "id": "1",
417 "messageType": "systemEventMessage",
418 "body": {"contentType": "html", "content": "<systemEventMessage/>"},
419 "from": {"user": {"id": "u1", "displayName": "Ada Lovelace"}},
420 "eventDetail": detail,
421 })))
422 };
423 let ready = event(serde_json::json!({
424 "@odata.type": RECORDING_TYPE,
425 "callId": "a64b5e71",
426 "callRecordingDisplayName": "Call with Echo-20261015_120906-Meeting Recording.mp4",
427 "callRecordingStatus": "success",
428 }));
429 assert_eq!(ready.text.as_deref(), Some(RECORDING_READY_PREVIEW));
430 assert!(ready.system && !ready.call);
431 assert_eq!(ready.sender_name, None);
432 let started = event(serde_json::json!({
433 "@odata.type": RECORDING_TYPE,
434 "callRecordingStatus": "initial",
435 }));
436 assert_eq!(started.text.as_deref(), Some(RECORDING_STARTED_PREVIEW));
437 let transcript = event(serde_json::json!({"@odata.type": TRANSCRIPT_TYPE}));
438 assert_eq!(transcript.text.as_deref(), Some(TRANSCRIPT_PREVIEW));
439 }
440
441 #[test]
442 fn graph_member_events_say_added_or_joined() {
443 let added = |members: serde_json::Value| {
444 OwnedPreview::from_graph(&graph_message(serde_json::json!({
445 "id": "1",
446 "messageType": "systemEventMessage",
447 "eventDetail": {
448 "@odata.type": MEMBERS_ADDED_TYPE,
449 "members": members,
450 "initiator": {"user": {"id": "me"}},
451 },
452 })))
453 .text
454 };
455 assert_eq!(
456 added(serde_json::json!([{"id": "other"}])).as_deref(),
457 Some(USER_ADDED_PREVIEW)
458 );
459 assert_eq!(
460 added(serde_json::json!([{"id": "me"}])).as_deref(),
461 Some(USER_JOINED_PREVIEW)
462 );
463 }
464
465 #[test]
466 fn graph_call_events_are_marked_to_keep_the_previous_line() {
467 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
468 "id": "1",
469 "messageType": "systemEventMessage",
470 "eventDetail": {
471 "@odata.type": "#microsoft.graph.callEndedEventMessageDetail",
472 "callId": "c1",
473 "callDuration": "PT30S",
474 "callEventType": "call",
475 },
476 })));
477 assert!(preview.call);
478 assert_eq!(preview.text, None);
479 }
480
481 #[test]
482 fn graph_deleted_flag_marks_the_preview_deleted() {
483 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
484 "id": "1",
485 "messageType": "message",
486 "isDeleted": true,
487 "body": {"contentType": "html", "content": "secret"},
488 })));
489 assert!(preview.deleted);
490 assert_eq!(preview.text, None);
491 }
492
493 #[test]
494 fn graph_image_preview_says_sent_an_image() {
495 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
496 "id": "1",
497 "messageType": "message",
498 "body": {"contentType": "html", "content": "<p><img src=\"https://graph.microsoft.com/x/$value\"></p>"},
499 "from": {"user": {"id": "u1", "displayName": "Lukas Berg"}},
500 })));
501 assert_eq!(preview.text.as_deref(), Some(IMAGE_PREVIEW));
502 assert_eq!(preview.sender_name.as_deref(), Some("Lukas Berg"));
503 }
504
505 fn call_record(phase: &str) -> MessageRecord {
506 MessageRecord {
507 conversation_id: "19:chat".into(),
508 message_id: "1".into(),
509 sender_id: Some("u1".into()),
510 sender_name: Some("Ada Lovelace".into()),
511 call_event_json: Some(
512 serde_json::json!({
513 "phase": phase,
514 "call_type": "Call",
515 "call_id": "c1",
516 "duration_seconds": null,
517 "initiator_id": null,
518 "initiator_name": null,
519 "participant_ids": [],
520 })
521 .to_string(),
522 ),
523 ..Default::default()
524 }
525 }
526
527 #[test]
528 fn stored_recordings_fill_the_line_and_calls_keep_the_previous_one() {
529 let saved = call_record("RecordingSaved");
530 assert!(!keeps_previous_line(&saved));
531 let preview = OwnedPreview::from_record(&saved);
532 assert_eq!(preview.text.as_deref(), Some(RECORDING_READY_PREVIEW));
533 assert_eq!(preview.sender_name, None);
534 assert!(!preview.call);
535 let transcript = OwnedPreview::from_record(&call_record("TranscriptStarted"));
536 assert_eq!(transcript.text.as_deref(), Some(TRANSCRIPT_PREVIEW));
537 let ended = call_record("Ended");
538 assert!(keeps_previous_line(&ended));
539 assert!(OwnedPreview::from_record(&ended).call);
540 }
541}