BlueGit

ict rusty-teams

Files

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

preview.rs

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