BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / native / chat.rs

chat.rs

chat.rs 10.6 KiB Download Raw
1use chrono::{DateTime, Utc};
2use graph::Chat;
3use serde_json::{Value, json};
4
5use super::message::graph_message_json;
6
7const ORGID_PREFIX: &str = "8:orgid:";
8const ONE_ON_ONE_SUFFIX: &str = "@unq.gbl.spaces";
9const OWNER_ROLE: &str = "admin";
10
11/// A chat member before its name is known.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct NativeMember {
14 pub user_id: String,
15 pub owner: bool,
16 pub name: Option<String>,
17}
18
19/// Graph lists chats, meetings and 1:1s; channels, teams and the service streams stay out.
20pub fn chat_type(conversation: &Value) -> Option<&'static str> {
21 let id = conversation["id"].as_str()?;
22 if id.ends_with(ONE_ON_ONE_SUFFIX) {
23 return Some("oneOnOne");
24 }
25 let thread = &conversation["threadProperties"];
26 match thread["productThreadType"].as_str() {
27 Some("OneToOneChat") => return Some("oneOnOne"),
28 Some("Meeting") => return Some("meeting"),
29 Some("Chat") => return Some("group"),
30 Some(_) => return None,
31 None => {}
32 }
33 match thread["threadType"].as_str() {
34 Some("chat") if id.starts_with("19:") => Some("group"),
35 Some("meeting") => Some("meeting"),
36 _ => None,
37 }
38}
39
40/// The two user ids of a `19:{a}_{b}@unq.gbl.spaces` chat.
41pub fn one_on_one_ids(chat_id: &str) -> Option<[String; 2]> {
42 let pair = chat_id
43 .strip_prefix("19:")?
44 .strip_suffix(ONE_ON_ONE_SUFFIX)?;
45 let (first, second) = pair.split_once('_')?;
46 Some([first.to_owned(), second.to_owned()])
47}
48
49pub fn thread_members(thread: &Value) -> Vec<NativeMember> {
50 thread["members"]
51 .as_array()
52 .into_iter()
53 .flatten()
54 .filter_map(|member| {
55 let user_id = member["id"].as_str()?.strip_prefix(ORGID_PREFIX)?;
56 Some(NativeMember {
57 user_id: user_id.to_owned(),
58 owner: member["role"]
59 .as_str()
60 .is_some_and(|role| role.eq_ignore_ascii_case(OWNER_ROLE)),
61 name: None,
62 })
63 })
64 .collect()
65}
66
67pub fn graph_member(member: &NativeMember, email: Option<&str>) -> Value {
68 json!({
69 "id": member.user_id,
70 "userId": member.user_id,
71 "displayName": member.name,
72 "email": email,
73 "roles": if member.owner { vec!["owner"] } else { Vec::new() },
74 })
75}
76
77/// A chat service conversation in the shape of a Graph chat with `members` and `lastMessagePreview`.
78pub fn graph_chat(conversation: &Value, members: Vec<Value>) -> Option<Chat> {
79 let id = conversation["id"].as_str()?;
80 let kind = chat_type(conversation)?;
81 let thread = &conversation["threadProperties"];
82 let created = millis_text(&thread["createdat"]);
83 let read = chatsvc::ReadHorizon::from_conversation(conversation);
84 let preview = preview(id, &conversation["lastMessage"]);
85 let last_updated = preview
86 .as_ref()
87 .and_then(|preview| preview["createdDateTime"].as_str().map(str::to_owned))
88 .or_else(|| created.clone());
89 serde_json::from_value(json!({
90 "id": id,
91 "topic": thread["topic"].as_str().filter(|topic| !topic.trim().is_empty()),
92 "chatType": kind,
93 "createdDateTime": created,
94 "lastUpdatedDateTime": last_updated,
95 "members": members,
96 "lastMessagePreview": preview,
97 "viewpoint": {
98 "lastMessageReadDateTime": read_time(read.consumed_until_ms),
99 "isHidden": null,
100 },
101 }))
102 .ok()
103}
104
105/// One chat from the chat service aggregator (`teams/users/me/chats/{id}`), which also has the meeting link.
106pub fn graph_chat_from_aggregator(chat: &Value, members: Vec<Value>) -> Option<Chat> {
107 let id = chat["id"].as_str()?;
108 let kind = if chat["isOneOnOne"].as_bool() == Some(true) || id.ends_with(ONE_ON_ONE_SUFFIX) {
109 "oneOnOne"
110 } else if chat["chatType"].as_str() == Some("meeting") {
111 "meeting"
112 } else {
113 "group"
114 };
115 let preview = preview(id, &chat["lastMessage"]);
116 let read_ms = chat
117 .pointer("/consumptionHorizon/originalArrivalTime")
118 .and_then(Value::as_i64)
119 .unwrap_or(0);
120 serde_json::from_value(json!({
121 "id": id,
122 "topic": chat["title"].as_str().filter(|topic| !topic.trim().is_empty() && kind != "oneOnOne"),
123 "chatType": kind,
124 "createdDateTime": chat["createdAt"].as_str().and_then(rfc3339),
125 "lastUpdatedDateTime": preview.as_ref().and_then(|preview| preview["createdDateTime"].as_str().map(str::to_owned)),
126 "members": members,
127 "lastMessagePreview": preview,
128 "viewpoint": {"lastMessageReadDateTime": read_time(read_ms), "isHidden": null},
129 "onlineMeetingInfo": {"joinWebUrl": chat.pointer("/meetingInformation/meetingJoinUrl")},
130 }))
131 .ok()
132}
133
134pub fn aggregator_members(chat: &Value) -> Vec<NativeMember> {
135 chat["members"]
136 .as_array()
137 .into_iter()
138 .flatten()
139 .filter_map(|member| {
140 let user_id = member["mri"].as_str()?.strip_prefix(ORGID_PREFIX)?;
141 Some(NativeMember {
142 user_id: user_id.to_owned(),
143 owner: member["role"]
144 .as_str()
145 .is_some_and(|role| role.eq_ignore_ascii_case(OWNER_ROLE)),
146 name: member["friendlyName"]
147 .as_str()
148 .map(str::trim)
149 .filter(|name| !name.is_empty())
150 .map(str::to_owned),
151 })
152 })
153 .collect()
154}
155
156/// Graph previews every last message; one the record mapping skips still dates the chat.
157fn preview(conversation_id: &str, last_message: &Value) -> Option<Value> {
158 if last_message
159 .as_object()
160 .is_none_or(|object| object.is_empty())
161 {
162 return None;
163 }
164 graph_message_json(conversation_id, last_message).or_else(|| {
165 let id = chatsvc::id_text(last_message.get("id")?)?;
166 let time = [
167 "originalarrivaltime",
168 "originalArrivalTime",
169 "composetime",
170 "composeTime",
171 ]
172 .iter()
173 .find_map(|key| last_message[*key].as_str())
174 .and_then(rfc3339)?;
175 Some(json!({"id": id, "messageType": "systemEventMessage", "createdDateTime": time}))
176 })
177}
178
179fn read_time(millis: i64) -> Option<String> {
180 (millis > 0)
181 .then(|| DateTime::<Utc>::from_timestamp_millis(millis))
182 .flatten()
183 .map(|time| time.to_rfc3339())
184}
185
186fn millis_text(value: &Value) -> Option<String> {
187 let millis = value.as_i64().or_else(|| value.as_str()?.parse().ok())?;
188 read_time(millis)
189}
190
191fn rfc3339(text: &str) -> Option<String> {
192 DateTime::parse_from_rfc3339(text)
193 .ok()
194 .map(|time| time.with_timezone(&Utc).to_rfc3339())
195}
196
197#[cfg(test)]
198mod tests {
199 use serde_json::json;
200
201 use super::*;
202 use crate::mapping::chat_record;
203
204 fn conversation(id: &str, product: &str) -> Value {
205 json!({
206 "id": id,
207 "properties": {"consumptionhorizon": "1794474789021;1794474789021;1"},
208 "threadProperties": {"productThreadType": product, "topic": "Plan", "createdat": "1790000000000"},
209 "lastMessage": {
210 "id": "1794474789021",
211 "messagetype": "RichText/Html",
212 "content": "<p>hi</p>",
213 "from": "https://x/contacts/8:orgid:ann",
214 "imdisplayname": "Ann",
215 "originalarrivaltime": "2026-11-12T09:13:09.021Z",
216 },
217 })
218 }
219
220 #[test]
221 fn channels_and_streams_are_not_chats() {
222 assert_eq!(
223 chat_type(&conversation("19:a@thread.tacv2", "TeamsStandardChannel")),
224 None
225 );
226 assert_eq!(
227 chat_type(&conversation("48:notifications", "StreamOfNotifications")),
228 None
229 );
230 assert_eq!(
231 chat_type(&conversation("19:a@thread.v2", "Meeting")),
232 Some("meeting")
233 );
234 assert_eq!(
235 chat_type(&json!({"id": "19:ann_bob@unq.gbl.spaces"})),
236 Some("oneOnOne")
237 );
238 }
239
240 #[test]
241 fn a_read_group_chat_maps_to_a_record() {
242 let members = vec![
243 graph_member(
244 &NativeMember {
245 user_id: "me".into(),
246 owner: true,
247 name: Some("Me".into()),
248 },
249 None,
250 ),
251 graph_member(
252 &NativeMember {
253 user_id: "ann".into(),
254 owner: false,
255 name: Some("Ann Example".into()),
256 },
257 None,
258 ),
259 ];
260 let chat = graph_chat(&conversation("19:a@thread.v2", "Chat"), members).unwrap();
261 let record = chat_record(&chat, "me");
262 assert_eq!(record.title, "Plan");
263 assert_eq!(record.kind, "group");
264 assert_eq!(record.member_summary, "Ann Example");
265 assert_eq!(record.last_message_preview.as_deref(), Some("hi"));
266 assert!(!record.unread);
267 assert!(chat.members[0].is_owner());
268 }
269
270 #[test]
271 fn an_unmapped_last_message_still_dates_the_chat() {
272 let mut pinned = conversation("19:a@thread.v2", "Chat");
273 pinned["lastMessage"]["messagetype"] = json!("ThreadActivity/PinnedItemsUpdate");
274 let chat = graph_chat(&pinned, Vec::new()).unwrap();
275 assert!(chat.last_message_time().is_some());
276 }
277
278 #[test]
279 fn the_aggregator_chat_has_the_meeting_link() {
280 let chat = json!({
281 "id": "19:meeting_x@thread.v2",
282 "chatType": "meeting",
283 "title": "Daily",
284 "members": [{"mri": "8:orgid:ann", "role": "Admin", "friendlyName": "Ann"}],
285 "meetingInformation": {"meetingJoinUrl": "https://teams.microsoft.com/l/meetup-join/x"},
286 "lastMessage": {"id": "1", "messageType": "Text", "content": "hi", "from": "8:orgid:ann", "originalArrivalTime": "2026-11-12T09:13:09.021Z"},
287 });
288 let members: Vec<Value> = aggregator_members(&chat)
289 .iter()
290 .map(|member| graph_member(member, None))
291 .collect();
292 let graph = graph_chat_from_aggregator(&chat, members).unwrap();
293 assert_eq!(graph.chat_type, "meeting");
294 assert_eq!(graph.members[0].display_name.as_deref(), Some("Ann"));
295 assert_eq!(
296 graph.online_meeting_info.unwrap().join_web_url.as_deref(),
297 Some("https://teams.microsoft.com/l/meetup-join/x")
298 );
299 }
300
301 #[test]
302 fn one_on_one_ids_split_the_pair() {
303 assert_eq!(
304 one_on_one_ids("19:ann_bob@unq.gbl.spaces"),
305 Some(["ann".to_owned(), "bob".to_owned()])
306 );
307 assert_eq!(one_on_one_ids("19:a@thread.v2"), None);
308 }
309}