BlueGit

ict rusty-teams

Files

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

mapping.rs

mapping.rs 12.1 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 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 ChatRecord {
43 id: chat.id.clone(),
44 kind: chat.chat_type.clone(),
45 title: chat.title(my_user_id),
46 member_summary: others
47 .iter()
48 .map(|member| member_name(member))
49 .collect::<Vec<_>>()
50 .join(", "),
51 last_message_at,
52 last_read_at,
53 unread: !last_event_system
54 && is_unread(chat.last_message_time(), last_read_at, last_from_me),
55 muted: false,
56 members: chat
57 .members
58 .iter()
59 .map(|member| MemberRecord {
60 user_id: member.user_id.clone(),
61 display_name: member_name(member).to_owned(),
62 })
63 .collect(),
64 last_message_deleted: preview.as_ref().is_some_and(|preview| preview.deleted),
65 last_message_preview: preview.as_ref().and_then(|preview| preview.text.clone()),
66 last_message_sender_id: preview
67 .as_ref()
68 .and_then(|preview| preview.sender_id.clone()),
69 last_message_sender_name: preview
70 .as_ref()
71 .and_then(|preview| preview.sender_name.clone()),
72 last_event_system,
73 }
74}
75
76fn member_name(member: &graph::Member) -> &str {
77 member
78 .display_name
79 .as_deref()
80 .or(member.email.as_deref())
81 .unwrap_or(NO_NAME)
82}
83
84fn is_unread(
85 last_message: Option<DateTime<Utc>>,
86 last_read: Option<DateTime<Utc>>,
87 last_from_me: bool,
88) -> bool {
89 match (last_message, last_read) {
90 (Some(message), Some(read)) => message > read && !last_from_me,
91 (Some(_), None) => !last_from_me,
92 _ => false,
93 }
94}
95
96pub fn team_record(team: &graph::Team) -> TeamRecord {
97 TeamRecord {
98 id: team.id.clone(),
99 name: team.display_name.clone(),
100 }
101}
102
103pub fn channel_record(team_id: &str, channel: &graph::Channel) -> ChannelRecord {
104 ChannelRecord {
105 id: channel.id.clone(),
106 team_id: team_id.to_owned(),
107 name: channel.display_name.clone(),
108 membership_type: channel.membership_type.clone(),
109 last_message_at: None,
110 unread: false,
111 }
112}
113
114/// `None` for system events and messages without a creation time.
115pub fn message_record(conversation_id: &str, message: &Message) -> Option<MessageRecord> {
116 if message
117 .message_type
118 .as_deref()
119 .is_some_and(|kind| kind != "message")
120 {
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 {
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 })
176}
177
178pub fn flatten_thread(conversation_id: &str, thread: &Message) -> Vec<MessageRecord> {
179 std::iter::once(thread)
180 .chain(thread.replies.iter())
181 .filter_map(|message| message_record(conversation_id, message))
182 .collect()
183}
184
185fn body_html(message: &Message) -> String {
186 let Some(body) = message.body.as_ref() else {
187 return String::new();
188 };
189 let content = body.content.as_deref().unwrap_or_default();
190 if body.content_type.eq_ignore_ascii_case("html") {
191 content.to_owned()
192 } else {
193 plain_text_to_html(content.trim())
194 }
195}
196
197pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {
198 let is_card = attachment
199 .content_type
200 .as_deref()
201 .is_some_and(|kind| kind.contains("card"));
202 let text = match (&attachment.content, is_card) {
203 (Some(content), true) => card_content_text(content),
204 _ => attachment
205 .name
206 .as_ref()
207 .map(|name| format!("[attachment: {name}]")),
208 };
209 AttachmentInfo {
210 content_type: attachment.content_type.clone(),
211 name: attachment.name.clone(),
212 url: attachment.content_url.clone(),
213 text,
214 size: attachment.content.as_deref().and_then(content_size),
215 quote: attachment
216 .content
217 .as_deref()
218 .filter(|_| attachment.content_type.as_deref() == Some("messageReference"))
219 .and_then(quote_info),
220 id: attachment.id.clone(),
221 content: attachment
222 .content
223 .clone()
224 .filter(|_| is_card || attachment.content_type.as_deref() == Some("messageReference")),
225 }
226}
227
228fn content_size(content: &str) -> Option<u64> {
229 serde_json::from_str::<serde_json::Value>(content)
230 .ok()?
231 .get("size")?
232 .as_u64()
233}
234
235fn quote_info(content: &str) -> Option<QuoteInfo> {
236 let value: serde_json::Value = serde_json::from_str(content).ok()?;
237 Some(QuoteInfo {
238 message_id: value.get("messageId")?.as_str()?.to_owned(),
239 preview: value
240 .get("messagePreview")
241 .and_then(serde_json::Value::as_str)
242 .unwrap_or_default()
243 .to_owned(),
244 sender_name: value
245 .pointer("/messageSender/user/displayName")
246 .and_then(serde_json::Value::as_str)
247 .map(str::to_owned),
248 })
249}
250
251fn reaction_info(reaction: &Reaction) -> ReactionInfo {
252 ReactionInfo {
253 reaction_type: reaction.reaction_type.clone(),
254 user_id: reaction
255 .user
256 .as_ref()
257 .and_then(|sender| sender.user_id())
258 .map(str::to_owned),
259 user_name: reaction
260 .user
261 .as_ref()
262 .and_then(|sender| sender.display_name())
263 .map(str::to_owned),
264 created_at: reaction.created_date_time,
265 }
266}
267
268fn mention_info(mention: &Mention) -> Option<MentionInfo> {
269 let mentioned = mention.mentioned.as_ref();
270 let name = mention.mention_text.clone().or_else(|| {
271 mentioned
272 .and_then(|sender| sender.display_name())
273 .map(str::to_owned)
274 })?;
275 Some(MentionInfo {
276 user_id: mentioned
277 .and_then(|sender| sender.user_id())
278 .map(str::to_owned),
279 name,
280 id: mention.id,
281 target_id: mentioned
282 .and_then(|sender| sender.target_id())
283 .map(str::to_owned),
284 group: mentioned.is_some_and(|sender| sender.is_group()),
285 })
286}
287
288fn to_json<T: serde::Serialize>(values: &[T]) -> String {
289 serde_json::to_string(values).unwrap_or_else(|_| "[]".to_owned())
290}
291
292#[cfg(test)]
293mod tests {
294 use serde_json::json;
295
296 use super::*;
297
298 fn chat_with_preview(preview: serde_json::Value) -> Chat {
299 serde_json::from_value(json!({
300 "id": "19:meeting@thread.v2",
301 "chatType": "meeting",
302 "viewpoint": {"lastMessageReadDateTime": "2026-10-06T09:00:00Z"},
303 "lastMessagePreview": preview,
304 }))
305 .unwrap()
306 }
307
308 #[test]
309 fn system_event_after_the_read_marker_is_not_unread() {
310 let chat = chat_with_preview(json!({
311 "id": "1",
312 "messageType": "unknownFutureValue",
313 "createdDateTime": "2026-10-06T10:00:00Z",
314 "from": null,
315 }));
316 let record = chat_record(&chat, "me");
317 assert!(!record.unread);
318 assert!(record.last_event_system);
319 }
320
321 #[test]
322 fn regular_message_after_the_read_marker_is_unread() {
323 let chat = chat_with_preview(json!({
324 "id": "1",
325 "messageType": "message",
326 "createdDateTime": "2026-10-06T10:00:00Z",
327 "from": {"user": {"id": "other"}},
328 }));
329 let record = chat_record(&chat, "me");
330 assert!(record.unread);
331 assert!(!record.last_event_system);
332 }
333
334 fn record_with_subject(subject: serde_json::Value) -> Option<String> {
335 let message: Message = serde_json::from_value(json!({
336 "id": "1",
337 "createdDateTime": "2026-10-06T09:00:00Z",
338 "subject": subject,
339 }))
340 .unwrap();
341 message_record("c", &message).unwrap().subject
342 }
343
344 #[test]
345 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
346 assert_eq!(
347 record_with_subject(json!(" Release plan ")).as_deref(),
348 Some("Release plan")
349 );
350 assert_eq!(record_with_subject(json!(" ")), None);
351 assert_eq!(record_with_subject(json!(null)), None);
352 }
353
354 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
355 let message: Message = serde_json::from_value(json!({
356 "id": "1",
357 "createdDateTime": "2026-10-06T09:00:00Z",
358 "mentions": [{"id": 0, "mentionText": "Target", "mentioned": mentioned}],
359 }))
360 .unwrap();
361 message_record("c", &message)
362 .map(|record| crate::stored::mentions(&record))
363 .unwrap()
364 }
365
366 #[test]
367 fn channel_team_and_tag_mentions_are_group_mentions() {
368 for mentioned in [
369 json!({"conversation": {"id": "19:chan@thread.tacv2", "conversationIdentityType": "channel"}}),
370 json!({"conversation": {"id": "team-1", "conversationIdentityType": "team"}}),
371 json!({"tag": {"id": "tag-1"}}),
372 ] {
373 let mentions = mentions_of(mentioned);
374 assert!(mentions[0].group);
375 assert_eq!(mentions[0].user_id, None);
376 assert!(mentions[0].target_id.is_some());
377 }
378 }
379
380 #[test]
381 fn user_and_application_mentions_are_not_group_mentions() {
382 for mentioned in [
383 json!({"user": {"id": "u1"}}),
384 json!({"application": {"id": "bot-1"}}),
385 ] {
386 assert!(!mentions_of(mentioned)[0].group);
387 }
388 }
389}