BlueGit

ict rusty-teams

Files

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

preview.rs

16435fd3 History
preview.rs 19.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, 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::Link { children, .. } => collect(children, parts),
128 Span::Heading { children, .. } | Span::BlockQuote(children) => {
129 parts.text.push(' ');
130 collect(children, parts);
131 parts.text.push(' ');
132 }
133 Span::List { items, .. } => {
134 for item in items {
135 parts.text.push(' ');
136 collect(item, parts);
137 }
138 parts.text.push(' ');
139 }
140 Span::Table { rows, .. } => {
141 for cell in rows.iter().flatten() {
142 parts.text.push(' ');
143 collect(cell, parts);
144 }
145 parts.text.push(' ');
146 }
147 }
148 }
149}
150
151fn collapse(text: &str) -> Option<String> {
152 let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" ");
153 if collapsed.is_empty() {
154 return None;
155 }
156 Some(collapsed.chars().take(MAX_PREVIEW_CHARS).collect())
157}
158
159fn system_event_preview(detail: &Value) -> Option<&'static str> {
160 match detail.get("@odata.type")?.as_str()? {
161 RECORDING_TYPE => match detail.get("callRecordingStatus")?.as_str()? {
162 "initial" => Some(RECORDING_STARTED_PREVIEW),
163 "chunkFinished" => Some(RECORDING_STOPPED_PREVIEW),
164 "success" => Some(RECORDING_READY_PREVIEW),
165 _ => None,
166 },
167 TRANSCRIPT_TYPE => Some(TRANSCRIPT_PREVIEW),
168 MEMBERS_JOINED_TYPE => Some(USER_JOINED_PREVIEW),
169 MEMBERS_ADDED_TYPE if added_only_self(detail) => Some(USER_JOINED_PREVIEW),
170 MEMBERS_ADDED_TYPE => Some(USER_ADDED_PREVIEW),
171 _ => None,
172 }
173}
174
175fn call_phase_preview(phase: CallPhase) -> Option<&'static str> {
176 match phase {
177 CallPhase::RecordingStarted => Some(RECORDING_STARTED_PREVIEW),
178 CallPhase::RecordingStopped => Some(RECORDING_STOPPED_PREVIEW),
179 CallPhase::RecordingSaved => Some(RECORDING_READY_PREVIEW),
180 CallPhase::TranscriptStarted => Some(TRANSCRIPT_PREVIEW),
181 CallPhase::Started | CallPhase::Ended => None,
182 }
183}
184
185/// Teams leaves call start and end out of the chat list line; recordings and transcripts stay in it.
186pub(crate) fn keeps_previous_line(record: &MessageRecord) -> bool {
187 call_event(record).is_some_and(|event| event.phase.is_call())
188}
189
190fn added_only_self(detail: &Value) -> bool {
191 let Some(initiator) = detail.pointer("/initiator/user/id").and_then(Value::as_str) else {
192 return false;
193 };
194 let members = detail
195 .get("members")
196 .and_then(Value::as_array)
197 .map(Vec::as_slice)
198 .unwrap_or_default();
199 !members.is_empty()
200 && members
201 .iter()
202 .all(|member| member.get("id").and_then(Value::as_str) == Some(initiator))
203}
204
205pub(crate) struct OwnedPreview {
206 pub text: Option<String>,
207 pub sender_id: Option<String>,
208 pub sender_name: Option<String>,
209 pub deleted: bool,
210 pub system: bool,
211 pub call: bool,
212}
213
214impl OwnedPreview {
215 pub(crate) fn from_graph(message: &Message) -> Self {
216 let regular = message
217 .message_type
218 .as_deref()
219 .is_none_or(|kind| kind == "message");
220 let deleted = message.is_deleted();
221 let detail = message.event_detail.as_ref().filter(|_| !regular);
222 let call = detail
223 .and_then(CallEvent::from_graph)
224 .is_some_and(|event| event.phase.is_call());
225 let text = if deleted {
226 None
227 } else if regular {
228 message
229 .body
230 .as_ref()
231 .and_then(|body| body.content.as_deref())
232 .and_then(|html| message_preview(html, &[]))
233 } else {
234 detail.and_then(system_event_preview).map(str::to_owned)
235 };
236 let sender = message.from.as_ref().filter(|_| regular);
237 OwnedPreview {
238 text,
239 sender_id: sender
240 .and_then(|sender| sender.user_id())
241 .map(str::to_owned),
242 sender_name: sender
243 .and_then(|sender| sender.display_name())
244 .map(str::to_owned),
245 deleted,
246 system: !regular,
247 call,
248 }
249 }
250
251 pub(crate) fn from_record(record: &MessageRecord) -> Self {
252 let event = call_event(record);
253 let roster = roster_event(record);
254 let text = if record.deleted {
255 None
256 } else if let Some(event) = &event {
257 call_phase_preview(event.phase).map(str::to_owned)
258 } else if let Some(roster) = &roster {
259 (roster.change == RosterChange::Added).then(|| USER_ADDED_PREVIEW.to_owned())
260 } else {
261 message_preview(&record.body_html, &attachments(record))
262 };
263 let sender = event.is_none() && roster.is_none();
264 OwnedPreview {
265 text,
266 sender_id: record.sender_id.clone().filter(|_| sender),
267 sender_name: record.sender_name.clone().filter(|_| sender),
268 deleted: record.deleted,
269 system: !sender,
270 call: event.is_some_and(|event| event.phase.is_call()),
271 }
272 }
273
274 pub(crate) fn as_store(&self) -> ChatPreview<'_> {
275 ChatPreview {
276 text: self.text.as_deref(),
277 sender_id: self.sender_id.as_deref(),
278 sender_name: self.sender_name.as_deref(),
279 deleted: self.deleted,
280 }
281 }
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 fn attachment(content_type: &str) -> AttachmentInfo {
289 serde_json::from_value(serde_json::json!({
290 "content_type": content_type,
291 "name": null,
292 "url": null,
293 "text": null,
294 }))
295 .unwrap()
296 }
297
298 fn graph_message(value: serde_json::Value) -> Message {
299 serde_json::from_value(value).unwrap()
300 }
301
302 #[test]
303 fn strips_tags_and_collapses_whitespace() {
304 assert_eq!(
305 preview_text("<p>Hello <b>big</b>\n world</p><p>second</p>").as_deref(),
306 Some("Hello big world second")
307 );
308 }
309
310 #[test]
311 fn image_only_bodies_are_empty() {
312 assert_eq!(preview_text("<p><img src=\"x\"></p>"), None);
313 assert_eq!(preview_text(" "), None);
314 }
315
316 #[test]
317 fn long_text_is_cut_to_the_limit() {
318 let long = "a ".repeat(400);
319 assert_eq!(
320 preview_text(&long).unwrap().chars().count(),
321 MAX_PREVIEW_CHARS
322 );
323 }
324
325 #[test]
326 fn plain_text_bodies_keep_entities_decoded() {
327 assert_eq!(preview_text("a &amp; b").as_deref(), Some("a & b"));
328 }
329
330 #[test]
331 fn emoji_and_mentions_read_like_teams() {
332 let html = r#"<p><at id="0">Robin Beck</at>&nbsp;kannst du?&nbsp;<emoji id="smile" alt="🙂" title="Smile"></emoji></p>"#;
333 assert_eq!(
334 preview_text(html).as_deref(),
335 Some("Robin Beck kannst du? 🙂")
336 );
337 }
338
339 #[test]
340 fn reply_quotes_are_left_out() {
341 let html = r#"<blockquote itemtype="http://schema.skype.com/Reply" itemid="1"><strong>Ada</strong><p>old</p></blockquote><p>new</p>"#;
342 assert_eq!(preview_text(html).as_deref(), Some("new"));
343 }
344
345 #[test]
346 fn image_only_message_says_sent_an_image() {
347 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>"#;
348 assert_eq!(message_preview(html, &[]).as_deref(), Some(IMAGE_PREVIEW));
349 }
350
351 #[test]
352 fn text_with_an_image_keeps_only_the_text() {
353 let html = r#"<p>this is from QA:</p><p><img src="https://graph.microsoft.com/v1.0/x/$value"></p><p>&nbsp;</p>"#;
354 assert_eq!(
355 message_preview(html, &[]).as_deref(),
356 Some("this is from QA:")
357 );
358 }
359
360 #[test]
361 fn giphy_reads_as_gif() {
362 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>"#;
363 assert_eq!(message_preview(html, &[]).as_deref(), Some(GIF_PREVIEW));
364 }
365
366 #[test]
367 fn inline_video_reads_as_video() {
368 let html = r#"<p>look</p><video src="https://x/v.mp4"></video>"#;
369 assert_eq!(message_preview(html, &[]).as_deref(), Some(VIDEO_PREVIEW));
370 }
371
372 #[test]
373 fn attachment_only_bodies_get_a_label() {
374 let body = r#"<attachment id="1792149081221"></attachment>"#;
375 let cases = [
376 (FORWARDED_CONTENT_TYPE, FORWARD_PREVIEW),
377 ("reference", FILE_PREVIEW),
378 ("application/vnd.microsoft.card.adaptive", CARD_PREVIEW),
379 ("application/vnd.microsoft.card.hero", CARD_PREVIEW),
380 (AUDIO_CARD_TYPE, AUDIO_PREVIEW),
381 (LOOP_CARD_TYPE, LOOP_PREVIEW),
382 ];
383 for (content_type, expected) in cases {
384 assert_eq!(
385 message_preview(body, &[attachment(content_type)]).as_deref(),
386 Some(expected),
387 "{content_type}"
388 );
389 }
390 assert_eq!(message_preview(body, &[]), None);
391 }
392
393 #[test]
394 fn a_file_with_text_shows_the_text() {
395 let body = r#"Hi Philipp,<br>Kann's dir zeigen.<attachment id="0cf57a46"></attachment>"#;
396 assert_eq!(
397 message_preview(body, &[attachment("reference")]).as_deref(),
398 Some("Hi Philipp, Kann's dir zeigen.")
399 );
400 }
401
402 #[test]
403 fn a_reply_shows_the_reply_text() {
404 let body = "<attachment id=\"1792136042729\"></attachment>\nwas war mit dependabot?";
405 assert_eq!(
406 message_preview(body, &[attachment("messageReference")]).as_deref(),
407 Some("was war mit dependabot?")
408 );
409 }
410
411 #[test]
412 fn graph_recording_and_transcript_events_have_teams_text() {
413 let event = |detail: serde_json::Value| {
414 OwnedPreview::from_graph(&graph_message(serde_json::json!({
415 "id": "1",
416 "messageType": "systemEventMessage",
417 "body": {"contentType": "html", "content": "<systemEventMessage/>"},
418 "from": {"user": {"id": "u1", "displayName": "Ada Lovelace"}},
419 "eventDetail": detail,
420 })))
421 };
422 let ready = event(serde_json::json!({
423 "@odata.type": RECORDING_TYPE,
424 "callId": "a64b5e71",
425 "callRecordingDisplayName": "Call with Echo-20261015_120906-Meeting Recording.mp4",
426 "callRecordingStatus": "success",
427 }));
428 assert_eq!(ready.text.as_deref(), Some(RECORDING_READY_PREVIEW));
429 assert!(ready.system && !ready.call);
430 assert_eq!(ready.sender_name, None);
431 let started = event(serde_json::json!({
432 "@odata.type": RECORDING_TYPE,
433 "callRecordingStatus": "initial",
434 }));
435 assert_eq!(started.text.as_deref(), Some(RECORDING_STARTED_PREVIEW));
436 let transcript = event(serde_json::json!({"@odata.type": TRANSCRIPT_TYPE}));
437 assert_eq!(transcript.text.as_deref(), Some(TRANSCRIPT_PREVIEW));
438 }
439
440 #[test]
441 fn graph_member_events_say_added_or_joined() {
442 let added = |members: serde_json::Value| {
443 OwnedPreview::from_graph(&graph_message(serde_json::json!({
444 "id": "1",
445 "messageType": "systemEventMessage",
446 "eventDetail": {
447 "@odata.type": MEMBERS_ADDED_TYPE,
448 "members": members,
449 "initiator": {"user": {"id": "me"}},
450 },
451 })))
452 .text
453 };
454 assert_eq!(
455 added(serde_json::json!([{"id": "other"}])).as_deref(),
456 Some(USER_ADDED_PREVIEW)
457 );
458 assert_eq!(
459 added(serde_json::json!([{"id": "me"}])).as_deref(),
460 Some(USER_JOINED_PREVIEW)
461 );
462 }
463
464 #[test]
465 fn graph_call_events_are_marked_to_keep_the_previous_line() {
466 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
467 "id": "1",
468 "messageType": "systemEventMessage",
469 "eventDetail": {
470 "@odata.type": "#microsoft.graph.callEndedEventMessageDetail",
471 "callId": "c1",
472 "callDuration": "PT30S",
473 "callEventType": "call",
474 },
475 })));
476 assert!(preview.call);
477 assert_eq!(preview.text, None);
478 }
479
480 #[test]
481 fn graph_deleted_flag_marks_the_preview_deleted() {
482 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
483 "id": "1",
484 "messageType": "message",
485 "isDeleted": true,
486 "body": {"contentType": "html", "content": "secret"},
487 })));
488 assert!(preview.deleted);
489 assert_eq!(preview.text, None);
490 }
491
492 #[test]
493 fn graph_image_preview_says_sent_an_image() {
494 let preview = OwnedPreview::from_graph(&graph_message(serde_json::json!({
495 "id": "1",
496 "messageType": "message",
497 "body": {"contentType": "html", "content": "<p><img src=\"https://graph.microsoft.com/x/$value\"></p>"},
498 "from": {"user": {"id": "u1", "displayName": "Lukas Berg"}},
499 })));
500 assert_eq!(preview.text.as_deref(), Some(IMAGE_PREVIEW));
501 assert_eq!(preview.sender_name.as_deref(), Some("Lukas Berg"));
502 }
503
504 fn call_record(phase: &str) -> MessageRecord {
505 MessageRecord {
506 conversation_id: "19:chat".into(),
507 message_id: "1".into(),
508 sender_id: Some("u1".into()),
509 sender_name: Some("Ada Lovelace".into()),
510 call_event_json: Some(
511 serde_json::json!({
512 "phase": phase,
513 "call_type": "Call",
514 "call_id": "c1",
515 "duration_seconds": null,
516 "initiator_id": null,
517 "initiator_name": null,
518 "participant_ids": [],
519 })
520 .to_string(),
521 ),
522 ..Default::default()
523 }
524 }
525
526 #[test]
527 fn stored_recordings_fill_the_line_and_calls_keep_the_previous_one() {
528 let saved = call_record("RecordingSaved");
529 assert!(!keeps_previous_line(&saved));
530 let preview = OwnedPreview::from_record(&saved);
531 assert_eq!(preview.text.as_deref(), Some(RECORDING_READY_PREVIEW));
532 assert_eq!(preview.sender_name, None);
533 assert!(!preview.call);
534 let transcript = OwnedPreview::from_record(&call_record("TranscriptStarted"));
535 assert_eq!(transcript.text.as_deref(), Some(TRANSCRIPT_PREVIEW));
536 let ended = call_record("Ended");
537 assert!(keeps_previous_line(&ended));
538 assert!(OwnedPreview::from_record(&ended).call);
539 }
540}