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 unavailable: false,
233 }
234}
235
236fn content_size(content: &str) -> Option<u64> {
237 serde_json::from_str::<serde_json::Value>(content)
238 .ok()?
239 .get("size")?
240 .as_u64()
241}
242
243fn quote_info(content: &str) -> Option<QuoteInfo> {
244 let value: serde_json::Value = serde_json::from_str(content).ok()?;
245 Some(QuoteInfo {
246 message_id: value.get("messageId")?.as_str()?.to_owned(),
247 preview: value
248 .get("messagePreview")
249 .and_then(serde_json::Value::as_str)
250 .unwrap_or_default()
251 .to_owned(),
252 sender_name: value
253 .pointer("/messageSender/user/displayName")
254 .and_then(serde_json::Value::as_str)
255 .map(str::to_owned),
256 })
257}
258
259fn reaction_info(reaction: &Reaction) -> ReactionInfo {
260 ReactionInfo {
261 reaction_type: reaction.reaction_type.clone(),
262 user_id: reaction
263 .user
264 .as_ref()
265 .and_then(|sender| sender.user_id())
266 .map(str::to_owned),
267 user_name: reaction
268 .user
269 .as_ref()
270 .and_then(|sender| sender.display_name())
271 .map(str::to_owned),
272 created_at: reaction.created_date_time,
273 }
274}
275
276fn mention_info(mention: &Mention) -> Option<MentionInfo> {
277 let mentioned = mention.mentioned.as_ref();
278 let name = mention.mention_text.clone().or_else(|| {
279 mentioned
280 .and_then(|sender| sender.display_name())
281 .map(str::to_owned)
282 })?;
283 Some(MentionInfo {
284 user_id: mentioned
285 .and_then(|sender| sender.user_id())
286 .map(str::to_owned),
287 name,
288 id: mention.id,
289 target_id: mentioned
290 .and_then(|sender| sender.target_id())
291 .map(str::to_owned),
292 group: mentioned.is_some_and(|sender| sender.is_group()),
293 })
294}
295
296fn to_json<T: serde::Serialize>(values: &[T]) -> String {
297 serde_json::to_string(values).unwrap_or_else(|_| "[]".to_owned())
298}
299
300#[cfg(test)]
301mod tests {
302 use serde_json::json;
303
304 use super::*;
305 use crate::call_event::{CallPhase, CallType};
306
307 fn chat_with_preview(preview: serde_json::Value) -> Chat {
308 serde_json::from_value(json!({
309 "id": "19:meeting@thread.v2",
310 "chatType": "meeting",
311 "viewpoint": {"lastMessageReadDateTime": "2026-10-06T09:00:00Z"},
312 "lastMessagePreview": preview,
313 }))
314 .unwrap()
315 }
316
317 #[test]
318 fn system_event_after_the_read_marker_is_not_unread() {
319 let chat = chat_with_preview(json!({
320 "id": "1",
321 "messageType": "unknownFutureValue",
322 "createdDateTime": "2026-10-06T10:00:00Z",
323 "from": null,
324 }));
325 let record = chat_record(&chat, "me");
326 assert!(!record.unread);
327 assert!(record.last_event_system);
328 }
329
330 #[test]
331 fn regular_message_after_the_read_marker_is_unread() {
332 let chat = chat_with_preview(json!({
333 "id": "1",
334 "messageType": "message",
335 "createdDateTime": "2026-10-06T10:00:00Z",
336 "from": {"user": {"id": "other"}},
337 }));
338 let record = chat_record(&chat, "me");
339 assert!(record.unread);
340 assert!(!record.last_event_system);
341 }
342
343 #[test]
344 fn a_member_without_name_or_email_is_an_unknown_user() {
345 let chat: Chat = serde_json::from_value(json!({
346 "id": "19:group@thread.v2",
347 "chatType": "group",
348 "members": [
349 {"userId": "me", "displayName": "Daniel"},
350 {"userId": "gone", "displayName": null, "email": ""},
351 {"userId": "mail", "displayName": " ", "email": "anna@example.com"},
352 ],
353 }))
354 .unwrap();
355 let record = chat_record(&chat, "me");
356 let names: Vec<&str> = record
357 .members
358 .iter()
359 .map(|member| member.display_name.as_str())
360 .collect();
361 assert_eq!(names, ["Daniel", "Unknown User", "anna@example.com"]);
362 assert_eq!(record.title, "Unknown User, anna@example.com");
363 assert_eq!(graph::UNKNOWN_USER_NAME, store::UNKNOWN_USER_NAME);
364 }
365
366 fn record_with_subject(subject: serde_json::Value) -> Option<String> {
367 let message: Message = serde_json::from_value(json!({
368 "id": "1",
369 "createdDateTime": "2026-10-06T09:00:00Z",
370 "subject": subject,
371 }))
372 .unwrap();
373 message_record("c", &message).unwrap().subject
374 }
375
376 #[test]
377 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
378 assert_eq!(
379 record_with_subject(json!(" Release plan ")).as_deref(),
380 Some("Release plan")
381 );
382 assert_eq!(record_with_subject(json!(" ")), None);
383 assert_eq!(record_with_subject(json!(null)), None);
384 }
385
386 fn user(id: &str) -> serde_json::Value {
387 json!({"user": {"id": id, "displayName": format!("Name {id}")}})
388 }
389
390 fn call_record(message_type: &str, detail: serde_json::Value) -> Option<MessageRecord> {
391 let message: Message = serde_json::from_value(json!({
392 "id": "1",
393 "messageType": message_type,
394 "createdDateTime": "2026-10-06T09:00:00Z",
395 "from": null,
396 "body": {"contentType": "html", "content": "<systemEventMessage/>"},
397 "eventDetail": detail,
398 }))
399 .unwrap();
400 message_record("c", &message)
401 }
402
403 fn ended(initiator: &str, participants: &[&str], duration: &str) -> serde_json::Value {
404 json!({
405 "@odata.type": "#microsoft.graph.callEndedEventMessageDetail",
406 "callId": "call-1",
407 "callEventType": "call",
408 "callDuration": duration,
409 "initiator": user(initiator),
410 "callParticipants": participants
411 .iter()
412 .map(|id| json!({"participant": user(id)}))
413 .collect::<Vec<_>>(),
414 })
415 }
416
417 fn event_of(record: &MessageRecord) -> CallEvent {
418 crate::call_event::call_event(record).unwrap()
419 }
420
421 #[test]
422 fn call_ended_by_me_is_kept_with_duration_and_participants() {
423 let record = call_record(
424 "unknownFutureValue",
425 ended("me", &["me", "other"], "PT12M3S"),
426 )
427 .unwrap();
428 let event = event_of(&record);
429 assert_eq!(event.phase, CallPhase::Ended);
430 assert_eq!(event.call_type, CallType::Call);
431 assert_eq!(event.call_id, "call-1");
432 assert_eq!(event.duration_seconds, Some(723));
433 assert_eq!(event.initiator_id.as_deref(), Some("me"));
434 assert_eq!(event.initiator_name.as_deref(), Some("Name me"));
435 assert_eq!(event.participant_ids, ["me", "other"]);
436 assert!(!event.missed(Some("me")));
437 assert!(record.body_html.is_empty());
438 assert_eq!(record.sender_id, None);
439 }
440
441 #[test]
442 fn call_ended_by_other_with_both_participants_is_not_missed() {
443 let record = call_record(
444 "systemEventMessage",
445 ended("other", &["other", "me"], "PT46S"),
446 )
447 .unwrap();
448 assert!(!event_of(&record).missed(Some("me")));
449 }
450
451 #[test]
452 fn unanswered_incoming_call_is_missed() {
453 let record = call_record("unknownFutureValue", ended("other", &["other"], "PT1M")).unwrap();
454 let event = event_of(&record);
455 assert!(event.missed(Some("me")));
456 assert_eq!(event.title(true), "Missed call");
457 assert_eq!(event.duration_seconds, Some(60));
458 assert!(!event.missed(None));
459 }
460
461 #[test]
462 fn guest_participant_counts_for_an_answered_call() {
463 let mut detail = ended("other", &["other"], "PT2M");
464 detail["callParticipants"]
465 .as_array_mut()
466 .unwrap()
467 .push(json!({"participant": {"guest": {"id": "guest-1", "displayName": "Guest"}}}));
468 let record = call_record("unknownFutureValue", detail).unwrap();
469 let event = event_of(&record);
470 assert_eq!(event.participant_ids, ["other", "guest-1"]);
471 assert!(!event.missed(Some("me")));
472 }
473
474 #[test]
475 fn unanswered_own_call_is_not_missed() {
476 let record = call_record("unknownFutureValue", ended("me", &["me"], "PT1M")).unwrap();
477 let event = event_of(&record);
478 assert!(!event.missed(Some("me")));
479 assert_eq!(event.plain_text(), "Call ended 1m");
480 }
481
482 #[test]
483 fn call_started_is_kept_without_duration() {
484 let record = call_record(
485 "unknownFutureValue",
486 json!({
487 "@odata.type": "#microsoft.graph.callStartedEventMessageDetail",
488 "callId": "call-1",
489 "callEventType": "call",
490 "initiator": {"user": {"id": "other", "displayName": null}},
491 }),
492 )
493 .unwrap();
494 let event = event_of(&record);
495 assert_eq!(event.phase, CallPhase::Started);
496 assert_eq!(event.initiator_id.as_deref(), Some("other"));
497 assert_eq!(event.initiator_name, None);
498 assert_eq!(event.duration_seconds, None);
499 assert_eq!(event.plain_text(), "Call started");
500 }
501
502 #[test]
503 fn meeting_ended_keeps_the_meeting_type() {
504 let mut detail = ended("me", &["me", "a", "b"], "PT1H2M3S");
505 detail["callEventType"] = json!("meeting");
506 let event = event_of(&call_record("unknownFutureValue", detail).unwrap());
507 assert_eq!(event.call_type, CallType::Meeting);
508 assert_eq!(event.duration_seconds, Some(3723));
509 assert_eq!(event.plain_text(), "Meeting ended 1h 2m 3s");
510 }
511
512 #[test]
513 fn screen_share_is_treated_as_a_call() {
514 let mut detail = ended("me", &["me", "a"], "PT5S");
515 detail["callEventType"] = json!("screenShare");
516 let event = event_of(&call_record("unknownFutureValue", detail).unwrap());
517 assert_eq!(event.call_type, CallType::Call);
518 }
519
520 #[test]
521 fn other_system_events_are_still_dropped() {
522 let detail = json!({
523 "@odata.type": "#microsoft.graph.membersAddedEventMessageDetail",
524 "members": [],
525 });
526 assert!(call_record("unknownFutureValue", detail).is_none());
527 assert!(call_record("systemEventMessage", json!(null)).is_none());
528 }
529
530 #[test]
531 fn regular_messages_never_become_call_events() {
532 let record = call_record("message", ended("me", &["me"], "PT1M")).unwrap();
533 assert_eq!(record.call_event_json, None);
534 }
535
536 #[test]
537 fn durations_parse_from_iso_8601() {
538 use crate::call_event::parse_duration_seconds as parse;
539 assert_eq!(parse("PT46S"), Some(46));
540 assert_eq!(parse("PT1M"), Some(60));
541 assert_eq!(parse("PT1M18S"), Some(78));
542 assert_eq!(parse("PT1H2M3S"), Some(3723));
543 assert_eq!(parse("PT40M19.26S"), Some(2419));
544 assert_eq!(parse("P1DT1S"), Some(86_401));
545 for garbage in ["", "P", "PT", "46S", "PT1X", "PTM", "PT12", "nonsense"] {
546 assert_eq!(parse(garbage), None, "{garbage}");
547 }
548 }
549
550 #[test]
551 fn durations_format_like_teams() {
552 use crate::call_event::format_duration as format;
553 assert_eq!(format(3723), "1h 2m 3s");
554 assert_eq!(format(723), "12m 3s");
555 assert_eq!(format(45), "45s");
556 assert_eq!(format(60), "1m");
557 assert_eq!(format(3600), "1h");
558 assert_eq!(format(3605), "1h 0m 5s");
559 assert_eq!(format(0), "0s");
560 }
561
562 #[test]
563 fn unparseable_duration_leaves_no_duration() {
564 let record = call_record("unknownFutureValue", ended("me", &["me", "a"], "soon")).unwrap();
565 let event = event_of(&record);
566 assert_eq!(event.duration_seconds, None);
567 assert_eq!(event.plain_text(), "Call ended");
568 }
569
570 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
571 let message: Message = serde_json::from_value(json!({
572 "id": "1",
573 "createdDateTime": "2026-10-06T09:00:00Z",
574 "mentions": [{"id": 0, "mentionText": "Target", "mentioned": mentioned}],
575 }))
576 .unwrap();
577 message_record("c", &message)
578 .map(|record| crate::stored::mentions(&record))
579 .unwrap()
580 }
581
582 #[test]
583 fn channel_team_and_tag_mentions_are_group_mentions() {
584 for mentioned in [
585 json!({"conversation": {"id": "19:chan@thread.tacv2", "conversationIdentityType": "channel"}}),
586 json!({"conversation": {"id": "team-1", "conversationIdentityType": "team"}}),
587 json!({"tag": {"id": "tag-1"}}),
588 ] {
589 let mentions = mentions_of(mentioned);
590 assert!(mentions[0].group);
591 assert_eq!(mentions[0].user_id, None);
592 assert!(mentions[0].target_id.is_some());
593 }
594 }
595
596 #[test]
597 fn user_and_application_mentions_are_not_group_mentions() {
598 for mentioned in [
599 json!({"user": {"id": "u1"}}),
600 json!({"application": {"id": "bot-1"}}),
601 ] {
602 assert!(!mentions_of(mentioned)[0].group);
603 }
604 }
605}