BlueGit

ict rusty-teams

Files

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

mapping.rs

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