BlueGit

ict rusty-teams

Files

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

mapping.rs

mapping.rs 12.2 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::links::EMPTY_LINKS;
7use crate::markdown::plain_text_to_html;
8use crate::preview::OwnedPreview;
9use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
10
11const NO_NAME: &str = "?";
12
13pub fn chat_record(chat: &Chat, my_user_id: &str) -> Option<ChatRecord> {
14 if chat
15 .viewpoint
16 .as_ref()
17 .and_then(|viewpoint| viewpoint.is_hidden)
18 == Some(true)
19 {
20 return None;
21 }
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 Some(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 and messages without a creation time.
116pub fn message_record(conversation_id: &str, message: &Message) -> Option<MessageRecord> {
117 if message
118 .message_type
119 .as_deref()
120 .is_some_and(|kind| kind != "message")
121 {
122 return None;
123 }
124 let created_at = message.created_date_time?;
125 let deleted = message.is_deleted();
126 let sender = message.from.as_ref();
127 Some(MessageRecord {
128 conversation_id: conversation_id.to_owned(),
129 message_id: message.id.clone(),
130 reply_to_id: message.reply_to_id.clone(),
131 sender_id: sender
132 .and_then(|sender| sender.user_id())
133 .map(str::to_owned),
134 sender_name: sender
135 .and_then(|sender| sender.display_name())
136 .map(str::to_owned),
137 sender_application_id: sender
138 .and_then(|sender| sender.application_id())
139 .map(str::to_owned),
140 created_at,
141 edited_at: message.last_edited_date_time,
142 deleted,
143 body_html: if deleted {
144 String::new()
145 } else {
146 body_html(message)
147 },
148 attachments_json: to_json(
149 &message
150 .attachments
151 .iter()
152 .map(attachment_info)
153 .collect::<Vec<_>>(),
154 ),
155 reactions_json: to_json(
156 &message
157 .reactions
158 .iter()
159 .map(reaction_info)
160 .collect::<Vec<_>>(),
161 ),
162 mentions_json: to_json(
163 &message
164 .mentions
165 .iter()
166 .filter_map(mention_info)
167 .collect::<Vec<_>>(),
168 ),
169 links_json: EMPTY_LINKS.to_owned(),
170 subject: message
171 .subject
172 .as_deref()
173 .map(str::trim)
174 .filter(|subject| !subject.is_empty())
175 .map(str::to_owned),
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(|_| is_card || attachment.content_type.as_deref() == Some("messageReference")),
226 }
227}
228
229fn content_size(content: &str) -> Option<u64> {
230 serde_json::from_str::<serde_json::Value>(content)
231 .ok()?
232 .get("size")?
233 .as_u64()
234}
235
236fn quote_info(content: &str) -> Option<QuoteInfo> {
237 let value: serde_json::Value = serde_json::from_str(content).ok()?;
238 Some(QuoteInfo {
239 message_id: value.get("messageId")?.as_str()?.to_owned(),
240 preview: value
241 .get("messagePreview")
242 .and_then(serde_json::Value::as_str)
243 .unwrap_or_default()
244 .to_owned(),
245 sender_name: value
246 .pointer("/messageSender/user/displayName")
247 .and_then(serde_json::Value::as_str)
248 .map(str::to_owned),
249 })
250}
251
252fn reaction_info(reaction: &Reaction) -> ReactionInfo {
253 ReactionInfo {
254 reaction_type: reaction.reaction_type.clone(),
255 user_id: reaction
256 .user
257 .as_ref()
258 .and_then(|sender| sender.user_id())
259 .map(str::to_owned),
260 user_name: reaction
261 .user
262 .as_ref()
263 .and_then(|sender| sender.display_name())
264 .map(str::to_owned),
265 created_at: reaction.created_date_time,
266 }
267}
268
269fn mention_info(mention: &Mention) -> Option<MentionInfo> {
270 let mentioned = mention.mentioned.as_ref();
271 let name = mention.mention_text.clone().or_else(|| {
272 mentioned
273 .and_then(|sender| sender.display_name())
274 .map(str::to_owned)
275 })?;
276 Some(MentionInfo {
277 user_id: mentioned
278 .and_then(|sender| sender.user_id())
279 .map(str::to_owned),
280 name,
281 id: mention.id,
282 target_id: mentioned
283 .and_then(|sender| sender.target_id())
284 .map(str::to_owned),
285 group: mentioned.is_some_and(|sender| sender.is_group()),
286 })
287}
288
289fn to_json<T: serde::Serialize>(values: &[T]) -> String {
290 serde_json::to_string(values).unwrap_or_else(|_| "[]".to_owned())
291}
292
293#[cfg(test)]
294mod tests {
295 use serde_json::json;
296
297 use super::*;
298
299 fn chat_with_preview(preview: serde_json::Value) -> Chat {
300 serde_json::from_value(json!({
301 "id": "19:meeting@thread.v2",
302 "chatType": "meeting",
303 "viewpoint": {"lastMessageReadDateTime": "2026-10-06T09:00:00Z"},
304 "lastMessagePreview": preview,
305 }))
306 .unwrap()
307 }
308
309 #[test]
310 fn system_event_after_the_read_marker_is_not_unread() {
311 let chat = chat_with_preview(json!({
312 "id": "1",
313 "messageType": "unknownFutureValue",
314 "createdDateTime": "2026-10-06T10:00:00Z",
315 "from": null,
316 }));
317 let record = chat_record(&chat, "me").unwrap();
318 assert!(!record.unread);
319 assert!(record.last_event_system);
320 }
321
322 #[test]
323 fn regular_message_after_the_read_marker_is_unread() {
324 let chat = chat_with_preview(json!({
325 "id": "1",
326 "messageType": "message",
327 "createdDateTime": "2026-10-06T10:00:00Z",
328 "from": {"user": {"id": "other"}},
329 }));
330 let record = chat_record(&chat, "me").unwrap();
331 assert!(record.unread);
332 assert!(!record.last_event_system);
333 }
334
335 fn record_with_subject(subject: serde_json::Value) -> Option<String> {
336 let message: Message = serde_json::from_value(json!({
337 "id": "1",
338 "createdDateTime": "2026-10-06T09:00:00Z",
339 "subject": subject,
340 }))
341 .unwrap();
342 message_record("c", &message).unwrap().subject
343 }
344
345 #[test]
346 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
347 assert_eq!(
348 record_with_subject(json!(" Release plan ")).as_deref(),
349 Some("Release plan")
350 );
351 assert_eq!(record_with_subject(json!(" ")), None);
352 assert_eq!(record_with_subject(json!(null)), None);
353 }
354
355 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
356 let message: Message = serde_json::from_value(json!({
357 "id": "1",
358 "createdDateTime": "2026-10-06T09:00:00Z",
359 "mentions": [{"id": 0, "mentionText": "Target", "mentioned": mentioned}],
360 }))
361 .unwrap();
362 message_record("c", &message)
363 .map(|record| crate::stored::mentions(&record))
364 .unwrap()
365 }
366
367 #[test]
368 fn channel_team_and_tag_mentions_are_group_mentions() {
369 for mentioned in [
370 json!({"conversation": {"id": "19:chan@thread.tacv2", "conversationIdentityType": "channel"}}),
371 json!({"conversation": {"id": "team-1", "conversationIdentityType": "team"}}),
372 json!({"tag": {"id": "tag-1"}}),
373 ] {
374 let mentions = mentions_of(mentioned);
375 assert!(mentions[0].group);
376 assert_eq!(mentions[0].user_id, None);
377 assert!(mentions[0].target_id.is_some());
378 }
379 }
380
381 #[test]
382 fn user_and_application_mentions_are_not_group_mentions() {
383 for mentioned in [
384 json!({"user": {"id": "u1"}}),
385 json!({"application": {"id": "bot-1"}}),
386 ] {
387 assert!(!mentions_of(mentioned)[0].group);
388 }
389 }
390}