BlueGit

ict rusty-teams

Files

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

mapping.rs

mapping.rs 11.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::markdown::plain_text_to_html;
7use crate::preview::OwnedPreview;
8use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
9
10const NO_NAME: &str = "?";
11
12pub fn chat_record(chat: &Chat, my_user_id: &str) -> Option<ChatRecord> {
13 if chat
14 .viewpoint
15 .as_ref()
16 .and_then(|viewpoint| viewpoint.is_hidden)
17 == Some(true)
18 {
19 return None;
20 }
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 Some(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 members: chat
56 .members
57 .iter()
58 .map(|member| MemberRecord {
59 user_id: member.user_id.clone(),
60 display_name: member_name(member).to_owned(),
61 })
62 .collect(),
63 last_message_deleted: preview.as_ref().is_some_and(|preview| preview.deleted),
64 last_message_preview: preview.as_ref().and_then(|preview| preview.text.clone()),
65 last_message_sender_id: preview
66 .as_ref()
67 .and_then(|preview| preview.sender_id.clone()),
68 last_message_sender_name: preview
69 .as_ref()
70 .and_then(|preview| preview.sender_name.clone()),
71 last_event_system,
72 })
73}
74
75fn member_name(member: &graph::Member) -> &str {
76 member
77 .display_name
78 .as_deref()
79 .or(member.email.as_deref())
80 .unwrap_or(NO_NAME)
81}
82
83fn is_unread(
84 last_message: Option<DateTime<Utc>>,
85 last_read: Option<DateTime<Utc>>,
86 last_from_me: bool,
87) -> bool {
88 match (last_message, last_read) {
89 (Some(message), Some(read)) => message > read && !last_from_me,
90 (Some(_), None) => !last_from_me,
91 _ => false,
92 }
93}
94
95pub fn team_record(team: &graph::Team) -> TeamRecord {
96 TeamRecord {
97 id: team.id.clone(),
98 name: team.display_name.clone(),
99 }
100}
101
102pub fn channel_record(team_id: &str, channel: &graph::Channel) -> ChannelRecord {
103 ChannelRecord {
104 id: channel.id.clone(),
105 team_id: team_id.to_owned(),
106 name: channel.display_name.clone(),
107 membership_type: channel.membership_type.clone(),
108 last_message_at: None,
109 unread: false,
110 }
111}
112
113/// `None` for system events and messages without a creation time.
114pub fn message_record(conversation_id: &str, message: &Message) -> Option<MessageRecord> {
115 if message
116 .message_type
117 .as_deref()
118 .is_some_and(|kind| kind != "message")
119 {
120 return None;
121 }
122 let created_at = message.created_date_time?;
123 let deleted = message.is_deleted();
124 let sender = message.from.as_ref();
125 Some(MessageRecord {
126 conversation_id: conversation_id.to_owned(),
127 message_id: message.id.clone(),
128 reply_to_id: message.reply_to_id.clone(),
129 sender_id: sender
130 .and_then(|sender| sender.user_id())
131 .map(str::to_owned),
132 sender_name: sender
133 .and_then(|sender| sender.display_name())
134 .map(str::to_owned),
135 sender_application_id: sender
136 .and_then(|sender| sender.application_id())
137 .map(str::to_owned),
138 created_at,
139 edited_at: message.last_edited_date_time,
140 deleted,
141 body_html: if deleted {
142 String::new()
143 } else {
144 body_html(message)
145 },
146 attachments_json: to_json(
147 &message
148 .attachments
149 .iter()
150 .map(attachment_info)
151 .collect::<Vec<_>>(),
152 ),
153 reactions_json: to_json(
154 &message
155 .reactions
156 .iter()
157 .map(reaction_info)
158 .collect::<Vec<_>>(),
159 ),
160 mentions_json: to_json(
161 &message
162 .mentions
163 .iter()
164 .filter_map(mention_info)
165 .collect::<Vec<_>>(),
166 ),
167 })
168}
169
170pub fn flatten_thread(conversation_id: &str, thread: &Message) -> Vec<MessageRecord> {
171 std::iter::once(thread)
172 .chain(thread.replies.iter())
173 .filter_map(|message| message_record(conversation_id, message))
174 .collect()
175}
176
177fn body_html(message: &Message) -> String {
178 let Some(body) = message.body.as_ref() else {
179 return String::new();
180 };
181 let content = body.content.as_deref().unwrap_or_default();
182 if body.content_type.eq_ignore_ascii_case("html") {
183 content.to_owned()
184 } else {
185 plain_text_to_html(content.trim())
186 }
187}
188
189pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {
190 let is_card = attachment
191 .content_type
192 .as_deref()
193 .is_some_and(|kind| kind.contains("card"));
194 let text = match (&attachment.content, is_card) {
195 (Some(content), true) => card_content_text(content),
196 _ => attachment
197 .name
198 .as_ref()
199 .map(|name| format!("[attachment: {name}]")),
200 };
201 AttachmentInfo {
202 content_type: attachment.content_type.clone(),
203 name: attachment.name.clone(),
204 url: attachment.content_url.clone(),
205 text,
206 size: attachment.content.as_deref().and_then(content_size),
207 quote: attachment
208 .content
209 .as_deref()
210 .filter(|_| attachment.content_type.as_deref() == Some("messageReference"))
211 .and_then(quote_info),
212 id: attachment.id.clone(),
213 content: attachment
214 .content
215 .clone()
216 .filter(|_| is_card || attachment.content_type.as_deref() == Some("messageReference")),
217 }
218}
219
220fn content_size(content: &str) -> Option<u64> {
221 serde_json::from_str::<serde_json::Value>(content)
222 .ok()?
223 .get("size")?
224 .as_u64()
225}
226
227fn quote_info(content: &str) -> Option<QuoteInfo> {
228 let value: serde_json::Value = serde_json::from_str(content).ok()?;
229 Some(QuoteInfo {
230 message_id: value.get("messageId")?.as_str()?.to_owned(),
231 preview: value
232 .get("messagePreview")
233 .and_then(serde_json::Value::as_str)
234 .unwrap_or_default()
235 .to_owned(),
236 sender_name: value
237 .pointer("/messageSender/user/displayName")
238 .and_then(serde_json::Value::as_str)
239 .map(str::to_owned),
240 })
241}
242
243fn reaction_info(reaction: &Reaction) -> ReactionInfo {
244 ReactionInfo {
245 reaction_type: reaction.reaction_type.clone(),
246 user_id: reaction
247 .user
248 .as_ref()
249 .and_then(|sender| sender.user_id())
250 .map(str::to_owned),
251 user_name: reaction
252 .user
253 .as_ref()
254 .and_then(|sender| sender.display_name())
255 .map(str::to_owned),
256 created_at: reaction.created_date_time,
257 }
258}
259
260fn mention_info(mention: &Mention) -> Option<MentionInfo> {
261 let mentioned = mention.mentioned.as_ref();
262 let name = mention.mention_text.clone().or_else(|| {
263 mentioned
264 .and_then(|sender| sender.display_name())
265 .map(str::to_owned)
266 })?;
267 Some(MentionInfo {
268 user_id: mentioned
269 .and_then(|sender| sender.user_id())
270 .map(str::to_owned),
271 name,
272 id: mention.id,
273 target_id: mentioned
274 .and_then(|sender| sender.target_id())
275 .map(str::to_owned),
276 group: mentioned.is_some_and(|sender| sender.is_group()),
277 })
278}
279
280fn to_json<T: serde::Serialize>(values: &[T]) -> String {
281 serde_json::to_string(values).unwrap_or_else(|_| "[]".to_owned())
282}
283
284#[cfg(test)]
285mod tests {
286 use serde_json::json;
287
288 use super::*;
289
290 fn chat_with_preview(preview: serde_json::Value) -> Chat {
291 serde_json::from_value(json!({
292 "id": "19:meeting@thread.v2",
293 "chatType": "meeting",
294 "viewpoint": {"lastMessageReadDateTime": "2026-10-06T09:00:00Z"},
295 "lastMessagePreview": preview,
296 }))
297 .unwrap()
298 }
299
300 #[test]
301 fn system_event_after_the_read_marker_is_not_unread() {
302 let chat = chat_with_preview(json!({
303 "id": "1",
304 "messageType": "unknownFutureValue",
305 "createdDateTime": "2026-10-06T10:00:00Z",
306 "from": null,
307 }));
308 let record = chat_record(&chat, "me").unwrap();
309 assert!(!record.unread);
310 assert!(record.last_event_system);
311 }
312
313 #[test]
314 fn regular_message_after_the_read_marker_is_unread() {
315 let chat = chat_with_preview(json!({
316 "id": "1",
317 "messageType": "message",
318 "createdDateTime": "2026-10-06T10:00:00Z",
319 "from": {"user": {"id": "other"}},
320 }));
321 let record = chat_record(&chat, "me").unwrap();
322 assert!(record.unread);
323 assert!(!record.last_event_system);
324 }
325
326 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
327 let message: Message = serde_json::from_value(json!({
328 "id": "1",
329 "createdDateTime": "2026-10-06T09:00:00Z",
330 "mentions": [{"id": 0, "mentionText": "Target", "mentioned": mentioned}],
331 }))
332 .unwrap();
333 message_record("c", &message)
334 .map(|record| crate::stored::mentions(&record))
335 .unwrap()
336 }
337
338 #[test]
339 fn channel_team_and_tag_mentions_are_group_mentions() {
340 for mentioned in [
341 json!({"conversation": {"id": "19:chan@thread.tacv2", "conversationIdentityType": "channel"}}),
342 json!({"conversation": {"id": "team-1", "conversationIdentityType": "team"}}),
343 json!({"tag": {"id": "tag-1"}}),
344 ] {
345 let mentions = mentions_of(mentioned);
346 assert!(mentions[0].group);
347 assert_eq!(mentions[0].user_id, None);
348 assert!(mentions[0].target_id.is_some());
349 }
350 }
351
352 #[test]
353 fn user_and_application_mentions_are_not_group_mentions() {
354 for mentioned in [
355 json!({"user": {"id": "u1"}}),
356 json!({"application": {"id": "bot-1"}}),
357 ] {
358 assert!(!mentions_of(mentioned)[0].group);
359 }
360 }
361}