BlueGit

ict rusty-teams

Files

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

mapping.rs

mapping.rs 19.7 KiB Download Raw
1use chrono::{DateTime, Utc};
2use graph::{Attachment, Chat, Mention, Message, Reaction};
3use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
4
5use crate::adaptive_card::card_content_text;
6use crate::call_event::CallEvent;
7use crate::forwarded::FORWARDED_CONTENT_TYPE;
8use crate::links::EMPTY_LINKS;
9use crate::markdown::plain_text_to_html;
10use crate::preview::OwnedPreview;
11use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
12
13const NO_NAME: &str = "?";
14
15pub fn graph_hidden(chat: &Chat) -> bool {
16 chat.viewpoint
17 .as_ref()
18 .and_then(|viewpoint| viewpoint.is_hidden)
19 == Some(true)
20}
21
22pub fn chat_record(chat: &Chat, my_user_id: &str) -> ChatRecord {
23 let others: Vec<&graph::Member> = chat
24 .members
25 .iter()
26 .filter(|member| member.user_id.as_deref() != Some(my_user_id))
27 .collect();
28 let last_message_at = chat.last_message_time().or(chat.last_updated_date_time);
29 let last_read_at = chat
30 .viewpoint
31 .as_ref()
32 .and_then(|viewpoint| viewpoint.last_message_read_date_time);
33 let last_from_me = chat
34 .last_message_preview
35 .as_ref()
36 .and_then(|preview| preview.from.as_ref())
37 .and_then(|sender| sender.user_id())
38 == Some(my_user_id);
39 let preview = chat
40 .last_message_preview
41 .as_ref()
42 .map(OwnedPreview::from_graph);
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);
46 ChatRecord {
47 id: chat.id.clone(),
48 kind: chat.chat_type.clone(),
49 title: chat.title(my_user_id),
50 member_summary: others
51 .iter()
52 .map(|member| member_name(member))
53 .collect::<Vec<_>>()
54 .join(", "),
55 last_message_at,
56 last_read_at,
57 unread: !last_event_system
58 && is_unread(chat.last_message_time(), last_read_at, last_from_me),
59 muted: false,
60 members: chat
61 .members
62 .iter()
63 .map(|member| MemberRecord {
64 user_id: member.user_id.clone(),
65 display_name: member_name(member).to_owned(),
66 })
67 .collect(),
68 last_message_deleted: preview.as_ref().is_some_and(|preview| preview.deleted),
69 last_message_preview: preview.as_ref().and_then(|preview| preview.text.clone()),
70 last_message_sender_id: preview
71 .as_ref()
72 .and_then(|preview| preview.sender_id.clone()),
73 last_message_sender_name: preview
74 .as_ref()
75 .and_then(|preview| preview.sender_name.clone()),
76 last_event_system,
77 last_event_call,
78 }
79}
80
81fn member_name(member: &graph::Member) -> &str {
82 member
83 .display_name
84 .as_deref()
85 .or(member.email.as_deref())
86 .unwrap_or(NO_NAME)
87}
88
89fn is_unread(
90 last_message: Option<DateTime<Utc>>,
91 last_read: Option<DateTime<Utc>>,
92 last_from_me: bool,
93) -> bool {
94 match (last_message, last_read) {
95 (Some(message), Some(read)) => message > read && !last_from_me,
96 (Some(_), None) => !last_from_me,
97 _ => false,
98 }
99}
100
101pub fn team_record(team: &graph::Team) -> TeamRecord {
102 TeamRecord {
103 id: team.id.clone(),
104 name: team.display_name.clone(),
105 }
106}
107
108pub fn channel_record(team_id: &str, channel: &graph::Channel) -> ChannelRecord {
109 ChannelRecord {
110 id: channel.id.clone(),
111 team_id: team_id.to_owned(),
112 name: channel.display_name.clone(),
113 membership_type: channel.membership_type.clone(),
114 last_message_at: None,
115 unread: false,
116 }
117}
118
119/// `None` for system events other than calls and messages without a creation time.
120pub fn message_record(conversation_id: &str, message: &Message) -> Option<MessageRecord> {
121 let is_system = message
122 .message_type
123 .as_deref()
124 .is_some_and(|kind| kind != "message");
125 let call_event = message
126 .event_detail
127 .as_ref()
128 .and_then(CallEvent::from_graph)
129 .filter(|_| is_system);
130 if is_system && call_event.is_none() {
131 return None;
132 }
133 let created_at = message.created_date_time?;
134 let deleted = message.is_deleted();
135 let sender = message.from.as_ref();
136 Some(MessageRecord {
137 conversation_id: conversation_id.to_owned(),
138 message_id: message.id.clone(),
139 reply_to_id: message.reply_to_id.clone(),
140 sender_id: sender
141 .and_then(|sender| sender.user_id())
142 .map(str::to_owned),
143 sender_name: sender
144 .and_then(|sender| sender.display_name())
145 .map(str::to_owned),
146 sender_application_id: sender
147 .and_then(|sender| sender.application_id())
148 .map(str::to_owned),
149 created_at,
150 edited_at: message.last_edited_date_time,
151 deleted,
152 body_html: if deleted || call_event.is_some() {
153 String::new()
154 } else {
155 body_html(message)
156 },
157 attachments_json: to_json(
158 &message
159 .attachments
160 .iter()
161 .map(attachment_info)
162 .collect::<Vec<_>>(),
163 ),
164 reactions_json: to_json(
165 &message
166 .reactions
167 .iter()
168 .map(reaction_info)
169 .collect::<Vec<_>>(),
170 ),
171 mentions_json: to_json(
172 &message
173 .mentions
174 .iter()
175 .filter_map(mention_info)
176 .collect::<Vec<_>>(),
177 ),
178 links_json: EMPTY_LINKS.to_owned(),
179 subject: message
180 .subject
181 .as_deref()
182 .map(str::trim)
183 .filter(|subject| !subject.is_empty())
184 .map(str::to_owned),
185 call_event_json: call_event.as_ref().map(CallEvent::to_json),
186 })
187}
188
189pub fn flatten_thread(conversation_id: &str, thread: &Message) -> Vec<MessageRecord> {
190 std::iter::once(thread)
191 .chain(thread.replies.iter())
192 .filter_map(|message| message_record(conversation_id, message))
193 .collect()
194}
195
196fn body_html(message: &Message) -> String {
197 let Some(body) = message.body.as_ref() else {
198 return String::new();
199 };
200 let content = body.content.as_deref().unwrap_or_default();
201 if body.content_type.eq_ignore_ascii_case("html") {
202 content.to_owned()
203 } else {
204 plain_text_to_html(content.trim())
205 }
206}
207
208pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {
209 let is_card = attachment
210 .content_type
211 .as_deref()
212 .is_some_and(|kind| kind.contains("card"));
213 let text = match (&attachment.content, is_card) {
214 (Some(content), true) => card_content_text(content),
215 _ => attachment
216 .name
217 .as_ref()
218 .map(|name| format!("[attachment: {name}]")),
219 };
220 AttachmentInfo {
221 content_type: attachment.content_type.clone(),
222 name: attachment.name.clone(),
223 url: attachment.content_url.clone(),
224 text,
225 size: attachment.content.as_deref().and_then(content_size),
226 quote: attachment
227 .content
228 .as_deref()
229 .filter(|_| attachment.content_type.as_deref() == Some("messageReference"))
230 .and_then(quote_info),
231 id: attachment.id.clone(),
232 content: attachment
233 .content
234 .clone()
235 .filter(|_| {
236 is_card
237 || matches!(
238 attachment.content_type.as_deref(),
239 Some("messageReference" | FORWARDED_CONTENT_TYPE)
240 )
241 }),
242 }
243}
244
245fn content_size(content: &str) -> Option<u64> {
246 serde_json::from_str::<serde_json::Value>(content)
247 .ok()?
248 .get("size")?
249 .as_u64()
250}
251
252fn quote_info(content: &str) -> Option<QuoteInfo> {
253 let value: serde_json::Value = serde_json::from_str(content).ok()?;
254 Some(QuoteInfo {
255 message_id: value.get("messageId")?.as_str()?.to_owned(),
256 preview: value
257 .get("messagePreview")
258 .and_then(serde_json::Value::as_str)
259 .unwrap_or_default()
260 .to_owned(),
261 sender_name: value
262 .pointer("/messageSender/user/displayName")
263 .and_then(serde_json::Value::as_str)
264 .map(str::to_owned),
265 })
266}
267
268fn reaction_info(reaction: &Reaction) -> ReactionInfo {
269 ReactionInfo {
270 reaction_type: reaction.reaction_type.clone(),
271 user_id: reaction
272 .user
273 .as_ref()
274 .and_then(|sender| sender.user_id())
275 .map(str::to_owned),
276 user_name: reaction
277 .user
278 .as_ref()
279 .and_then(|sender| sender.display_name())
280 .map(str::to_owned),
281 created_at: reaction.created_date_time,
282 }
283}
284
285fn mention_info(mention: &Mention) -> Option<MentionInfo> {
286 let mentioned = mention.mentioned.as_ref();
287 let name = mention.mention_text.clone().or_else(|| {
288 mentioned
289 .and_then(|sender| sender.display_name())
290 .map(str::to_owned)
291 })?;
292 Some(MentionInfo {
293 user_id: mentioned
294 .and_then(|sender| sender.user_id())
295 .map(str::to_owned),
296 name,
297 id: mention.id,
298 target_id: mentioned
299 .and_then(|sender| sender.target_id())
300 .map(str::to_owned),
301 group: mentioned.is_some_and(|sender| sender.is_group()),
302 })
303}
304
305fn to_json<T: serde::Serialize>(values: &[T]) -> String {
306 serde_json::to_string(values).unwrap_or_else(|_| "[]".to_owned())
307}
308
309#[cfg(test)]
310mod tests {
311 use serde_json::json;
312
313 use super::*;
314 use crate::call_event::{CallPhase, CallType};
315
316 fn chat_with_preview(preview: serde_json::Value) -> Chat {
317 serde_json::from_value(json!({
318 "id": "19:meeting@thread.v2",
319 "chatType": "meeting",
320 "viewpoint": {"lastMessageReadDateTime": "2026-10-06T09:00:00Z"},
321 "lastMessagePreview": preview,
322 }))
323 .unwrap()
324 }
325
326 #[test]
327 fn system_event_after_the_read_marker_is_not_unread() {
328 let chat = chat_with_preview(json!({
329 "id": "1",
330 "messageType": "unknownFutureValue",
331 "createdDateTime": "2026-10-06T10:00:00Z",
332 "from": null,
333 }));
334 let record = chat_record(&chat, "me");
335 assert!(!record.unread);
336 assert!(record.last_event_system);
337 }
338
339 #[test]
340 fn regular_message_after_the_read_marker_is_unread() {
341 let chat = chat_with_preview(json!({
342 "id": "1",
343 "messageType": "message",
344 "createdDateTime": "2026-10-06T10:00:00Z",
345 "from": {"user": {"id": "other"}},
346 }));
347 let record = chat_record(&chat, "me");
348 assert!(record.unread);
349 assert!(!record.last_event_system);
350 }
351
352 fn record_with_subject(subject: serde_json::Value) -> Option<String> {
353 let message: Message = serde_json::from_value(json!({
354 "id": "1",
355 "createdDateTime": "2026-10-06T09:00:00Z",
356 "subject": subject,
357 }))
358 .unwrap();
359 message_record("c", &message).unwrap().subject
360 }
361
362 #[test]
363 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
364 assert_eq!(
365 record_with_subject(json!(" Release plan ")).as_deref(),
366 Some("Release plan")
367 );
368 assert_eq!(record_with_subject(json!(" ")), None);
369 assert_eq!(record_with_subject(json!(null)), None);
370 }
371
372 fn user(id: &str) -> serde_json::Value {
373 json!({"user": {"id": id, "displayName": format!("Name {id}")}})
374 }
375
376 fn call_record(message_type: &str, detail: serde_json::Value) -> Option<MessageRecord> {
377 let message: Message = serde_json::from_value(json!({
378 "id": "1",
379 "messageType": message_type,
380 "createdDateTime": "2026-10-06T09:00:00Z",
381 "from": null,
382 "body": {"contentType": "html", "content": "<systemEventMessage/>"},
383 "eventDetail": detail,
384 }))
385 .unwrap();
386 message_record("c", &message)
387 }
388
389 fn ended(initiator: &str, participants: &[&str], duration: &str) -> serde_json::Value {
390 json!({
391 "@odata.type": "#microsoft.graph.callEndedEventMessageDetail",
392 "callId": "call-1",
393 "callEventType": "call",
394 "callDuration": duration,
395 "initiator": user(initiator),
396 "callParticipants": participants
397 .iter()
398 .map(|id| json!({"participant": user(id)}))
399 .collect::<Vec<_>>(),
400 })
401 }
402
403 fn event_of(record: &MessageRecord) -> CallEvent {
404 crate::call_event::call_event(record).unwrap()
405 }
406
407 #[test]
408 fn call_ended_by_me_is_kept_with_duration_and_participants() {
409 let record = call_record(
410 "unknownFutureValue",
411 ended("me", &["me", "other"], "PT12M3S"),
412 )
413 .unwrap();
414 let event = event_of(&record);
415 assert_eq!(event.phase, CallPhase::Ended);
416 assert_eq!(event.call_type, CallType::Call);
417 assert_eq!(event.call_id, "call-1");
418 assert_eq!(event.duration_seconds, Some(723));
419 assert_eq!(event.initiator_id.as_deref(), Some("me"));
420 assert_eq!(event.initiator_name.as_deref(), Some("Name me"));
421 assert_eq!(event.participant_ids, ["me", "other"]);
422 assert!(!event.missed(Some("me")));
423 assert!(record.body_html.is_empty());
424 assert_eq!(record.sender_id, None);
425 }
426
427 #[test]
428 fn call_ended_by_other_with_both_participants_is_not_missed() {
429 let record = call_record(
430 "systemEventMessage",
431 ended("other", &["other", "me"], "PT46S"),
432 )
433 .unwrap();
434 assert!(!event_of(&record).missed(Some("me")));
435 }
436
437 #[test]
438 fn unanswered_incoming_call_is_missed() {
439 let record = call_record("unknownFutureValue", ended("other", &["other"], "PT1M")).unwrap();
440 let event = event_of(&record);
441 assert!(event.missed(Some("me")));
442 assert_eq!(event.title(true), "Missed call");
443 assert_eq!(event.duration_seconds, Some(60));
444 assert!(!event.missed(None));
445 }
446
447 #[test]
448 fn guest_participant_counts_for_an_answered_call() {
449 let mut detail = ended("other", &["other"], "PT2M");
450 detail["callParticipants"]
451 .as_array_mut()
452 .unwrap()
453 .push(json!({"participant": {"guest": {"id": "guest-1", "displayName": "Guest"}}}));
454 let record = call_record("unknownFutureValue", detail).unwrap();
455 let event = event_of(&record);
456 assert_eq!(event.participant_ids, ["other", "guest-1"]);
457 assert!(!event.missed(Some("me")));
458 }
459
460 #[test]
461 fn unanswered_own_call_is_not_missed() {
462 let record = call_record("unknownFutureValue", ended("me", &["me"], "PT1M")).unwrap();
463 let event = event_of(&record);
464 assert!(!event.missed(Some("me")));
465 assert_eq!(event.plain_text(), "Call ended 1m");
466 }
467
468 #[test]
469 fn call_started_is_kept_without_duration() {
470 let record = call_record(
471 "unknownFutureValue",
472 json!({
473 "@odata.type": "#microsoft.graph.callStartedEventMessageDetail",
474 "callId": "call-1",
475 "callEventType": "call",
476 "initiator": {"user": {"id": "other", "displayName": null}},
477 }),
478 )
479 .unwrap();
480 let event = event_of(&record);
481 assert_eq!(event.phase, CallPhase::Started);
482 assert_eq!(event.initiator_id.as_deref(), Some("other"));
483 assert_eq!(event.initiator_name, None);
484 assert_eq!(event.duration_seconds, None);
485 assert_eq!(event.plain_text(), "Call started");
486 }
487
488 #[test]
489 fn meeting_ended_keeps_the_meeting_type() {
490 let mut detail = ended("me", &["me", "a", "b"], "PT1H2M3S");
491 detail["callEventType"] = json!("meeting");
492 let event = event_of(&call_record("unknownFutureValue", detail).unwrap());
493 assert_eq!(event.call_type, CallType::Meeting);
494 assert_eq!(event.duration_seconds, Some(3723));
495 assert_eq!(event.plain_text(), "Meeting ended 1h 2m 3s");
496 }
497
498 #[test]
499 fn screen_share_is_treated_as_a_call() {
500 let mut detail = ended("me", &["me", "a"], "PT5S");
501 detail["callEventType"] = json!("screenShare");
502 let event = event_of(&call_record("unknownFutureValue", detail).unwrap());
503 assert_eq!(event.call_type, CallType::Call);
504 }
505
506 #[test]
507 fn other_system_events_are_still_dropped() {
508 let detail = json!({
509 "@odata.type": "#microsoft.graph.membersAddedEventMessageDetail",
510 "members": [],
511 });
512 assert!(call_record("unknownFutureValue", detail).is_none());
513 assert!(call_record("systemEventMessage", json!(null)).is_none());
514 }
515
516 #[test]
517 fn regular_messages_never_become_call_events() {
518 let record = call_record("message", ended("me", &["me"], "PT1M")).unwrap();
519 assert_eq!(record.call_event_json, None);
520 }
521
522 #[test]
523 fn durations_parse_from_iso_8601() {
524 use crate::call_event::parse_duration_seconds as parse;
525 assert_eq!(parse("PT46S"), Some(46));
526 assert_eq!(parse("PT1M"), Some(60));
527 assert_eq!(parse("PT1M18S"), Some(78));
528 assert_eq!(parse("PT1H2M3S"), Some(3723));
529 assert_eq!(parse("PT40M19.26S"), Some(2419));
530 assert_eq!(parse("P1DT1S"), Some(86_401));
531 for garbage in ["", "P", "PT", "46S", "PT1X", "PTM", "PT12", "nonsense"] {
532 assert_eq!(parse(garbage), None, "{garbage}");
533 }
534 }
535
536 #[test]
537 fn durations_format_like_teams() {
538 use crate::call_event::format_duration as format;
539 assert_eq!(format(3723), "1h 2m 3s");
540 assert_eq!(format(723), "12m 3s");
541 assert_eq!(format(45), "45s");
542 assert_eq!(format(60), "1m");
543 assert_eq!(format(3600), "1h");
544 assert_eq!(format(3605), "1h 0m 5s");
545 assert_eq!(format(0), "0s");
546 }
547
548 #[test]
549 fn unparseable_duration_leaves_no_duration() {
550 let record = call_record("unknownFutureValue", ended("me", &["me", "a"], "soon")).unwrap();
551 let event = event_of(&record);
552 assert_eq!(event.duration_seconds, None);
553 assert_eq!(event.plain_text(), "Call ended");
554 }
555
556 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
557 let message: Message = serde_json::from_value(json!({
558 "id": "1",
559 "createdDateTime": "2026-10-06T09:00:00Z",
560 "mentions": [{"id": 0, "mentionText": "Target", "mentioned": mentioned}],
561 }))
562 .unwrap();
563 message_record("c", &message)
564 .map(|record| crate::stored::mentions(&record))
565 .unwrap()
566 }
567
568 #[test]
569 fn channel_team_and_tag_mentions_are_group_mentions() {
570 for mentioned in [
571 json!({"conversation": {"id": "19:chan@thread.tacv2", "conversationIdentityType": "channel"}}),
572 json!({"conversation": {"id": "team-1", "conversationIdentityType": "team"}}),
573 json!({"tag": {"id": "tag-1"}}),
574 ] {
575 let mentions = mentions_of(mentioned);
576 assert!(mentions[0].group);
577 assert_eq!(mentions[0].user_id, None);
578 assert!(mentions[0].target_id.is_some());
579 }
580 }
581
582 #[test]
583 fn user_and_application_mentions_are_not_group_mentions() {
584 for mentioned in [
585 json!({"user": {"id": "u1"}}),
586 json!({"application": {"id": "bot-1"}}),
587 ] {
588 assert!(!mentions_of(mentioned)[0].group);
589 }
590 }
591}