BlueGit

ict rusty-teams

Files

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

mapping.rs

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