BlueGit

ict rusty-teams

Files

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

mapping.rs

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