BlueGit

ict rusty-teams

Files

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

mapping.rs

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