BlueGit

ict rusty-teams

Files

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

roster_event.rs

roster_event.rs 13.4 KiB Download Raw
1use chrono::{DateTime, Datelike, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use store::{MemberRecord, MessageRecord};
5
6const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
7const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
8const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
9const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail";
10const APP_INSTALLED_TYPE: &str = "#microsoft.graph.teamsAppInstalledEventMessageDetail";
11const UNRESOLVED_NAME_PREFIX: &str = "orgid:";
12const DAY_SECONDS: i64 = 86_400;
13const UNNAMED_APP: &str = "an app";
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16pub enum RosterChange {
17 Added,
18 Removed,
19 Left,
20 Renamed,
21 AppAdded,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
25pub enum SharedHistory {
26 #[default]
27 None,
28 Days(u32),
29 All,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct RosterEvent {
34 pub change: RosterChange,
35 pub initiator_id: Option<String>,
36 pub initiator_name: Option<String>,
37 pub member_ids: Vec<String>,
38 pub member_names: Vec<Option<String>>,
39 #[serde(default)]
40 pub history: SharedHistory,
41 #[serde(default)]
42 pub topic: Option<String>,
43 #[serde(default)]
44 pub app_name: Option<String>,
45}
46
47#[derive(Serialize, Deserialize)]
48struct StoredRoster {
49 roster: RosterEvent,
50}
51
52impl RosterEvent {
53 pub fn from_graph(detail: &Value, created_at: Option<DateTime<Utc>>) -> Option<RosterEvent> {
54 let kind = detail.get("@odata.type")?.as_str()?;
55 let members: Vec<(String, Option<String>)> = detail
56 .get("members")
57 .and_then(Value::as_array)
58 .into_iter()
59 .flatten()
60 .filter_map(|member| {
61 let user_id = member.get("id")?.as_str()?.to_owned();
62 Some((user_id, display_name(member)))
63 })
64 .collect();
65 let initiator = detail
66 .pointer("/initiator/user")
67 .or_else(|| detail.pointer("/initiator/application"));
68 let initiator_id = initiator
69 .and_then(|identity| identity.get("id"))
70 .and_then(Value::as_str)
71 .map(str::to_owned);
72 let only_initiator =
73 members.len() == 1 && initiator_id.as_deref() == Some(members[0].0.as_str());
74 let change = match kind {
75 MEMBERS_ADDED_TYPE => RosterChange::Added,
76 MEMBERS_LEFT_TYPE => RosterChange::Left,
77 MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,
78 MEMBERS_DELETED_TYPE => RosterChange::Removed,
79 CHAT_RENAMED_TYPE => RosterChange::Renamed,
80 APP_INSTALLED_TYPE => RosterChange::AppAdded,
81 _ => return None,
82 };
83 let history = match change {
84 RosterChange::Added => shared_history(
85 detail
86 .get("visibleHistoryStartDateTime")
87 .and_then(Value::as_str),
88 created_at,
89 ),
90 _ => SharedHistory::None,
91 };
92 let (member_ids, member_names) = members.into_iter().unzip();
93 Some(RosterEvent {
94 change,
95 initiator_name: initiator.and_then(display_name),
96 initiator_id,
97 member_ids,
98 member_names,
99 history,
100 topic: (change == RosterChange::Renamed)
101 .then(|| detail.get("chatDisplayName").and_then(Value::as_str))
102 .flatten()
103 .map(str::trim)
104 .filter(|topic| !topic.is_empty())
105 .map(str::to_owned),
106 app_name: (change == RosterChange::AppAdded)
107 .then(|| detail.get("teamsAppDisplayName").and_then(Value::as_str))
108 .flatten()
109 .map(str::trim)
110 .filter(|name| !name.is_empty())
111 .map(str::to_owned),
112 })
113 }
114
115 pub fn from_json(json: &str) -> Option<RosterEvent> {
116 serde_json::from_str::<StoredRoster>(json)
117 .ok()
118 .map(|stored| stored.roster)
119 }
120
121 pub fn to_json(&self) -> String {
122 serde_json::to_string(&StoredRoster {
123 roster: self.clone(),
124 })
125 .unwrap_or_default()
126 }
127
128 /// Teams wording; `name_of` gets each user id with the name the event carries.
129 pub fn text(&self, name_of: impl Fn(Option<&str>, Option<&str>) -> String) -> String {
130 let initiator = name_of(self.initiator_id.as_deref(), self.initiator_name.as_deref());
131 let targets: Vec<String> = self
132 .member_ids
133 .iter()
134 .zip(&self.member_names)
135 .map(|(user_id, name)| name_of(Some(user_id), name.as_deref()))
136 .collect();
137 let targets = join_targets(&targets);
138 match self.change {
139 RosterChange::Left => format!("{initiator} left the chat."),
140 RosterChange::Renamed => match &self.topic {
141 Some(topic) => format!("{initiator} changed the group name to {topic}."),
142 None => format!("{initiator} removed the group name for this conversation."),
143 },
144 RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),
145 RosterChange::AppAdded => {
146 let app = self.app_name.as_deref().unwrap_or(UNNAMED_APP);
147 format!("{initiator} added {app} to the chat.")
148 }
149 RosterChange::Added => match self.history {
150 SharedHistory::None => format!("{initiator} added {targets} to the chat."),
151 SharedHistory::All => {
152 format!("{initiator} added {targets} to the chat and shared all chat history.")
153 }
154 SharedHistory::Days(1) => format!(
155 "{initiator} added {targets} to the chat and shared chat history from the past day."
156 ),
157 SharedHistory::Days(days) => format!(
158 "{initiator} added {targets} to the chat and shared chat history from the past {days} days."
159 ),
160 },
161 }
162 }
163}
164
165pub fn roster_event(record: &MessageRecord) -> Option<RosterEvent> {
166 RosterEvent::from_json(record.call_event_json.as_deref()?)
167}
168
169pub fn merge_members(members: &mut Vec<MemberRecord>, added: &[MemberRecord]) {
170 for person in added {
171 let known = members
172 .iter()
173 .any(|member| member.user_id.is_some() && member.user_id == person.user_id);
174 if !known {
175 members.push(person.clone());
176 }
177 }
178}
179
180fn join_targets(targets: &[String]) -> String {
181 match targets {
182 [] => String::new(),
183 [only] => only.clone(),
184 [first, second] => format!("{first} and {second}"),
185 [first, rest @ ..] => format!("{first} and {} others", rest.len()),
186 }
187}
188
189fn display_name(identity: &Value) -> Option<String> {
190 identity
191 .get("displayName")
192 .and_then(Value::as_str)
193 .map(str::trim)
194 .filter(|name| !name.is_empty() && !name.starts_with(UNRESOLVED_NAME_PREFIX))
195 .map(str::to_owned)
196}
197
198fn shared_history(visible_from: Option<&str>, created_at: Option<DateTime<Utc>>) -> SharedHistory {
199 let Some(visible_from) = visible_from.and_then(|text| DateTime::parse_from_rfc3339(text).ok())
200 else {
201 return SharedHistory::None;
202 };
203 if visible_from.year() <= 1 {
204 return SharedHistory::All;
205 }
206 let Some(created_at) = created_at else {
207 return SharedHistory::None;
208 };
209 let seconds = (created_at - visible_from.with_timezone(&Utc)).num_seconds();
210 match (seconds + DAY_SECONDS / 2) / DAY_SECONDS {
211 days if days >= 1 => SharedHistory::Days(u32::try_from(days).unwrap_or(u32::MAX)),
212 _ => SharedHistory::None,
213 }
214}
215
216#[cfg(test)]
217mod tests {
218 use chrono::TimeZone;
219 use serde_json::json;
220
221 use super::*;
222
223 fn created() -> Option<DateTime<Utc>> {
224 Some(Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap())
225 }
226
227 fn added(members: Value, visible_from: Value) -> RosterEvent {
228 RosterEvent::from_graph(
229 &json!({
230 "@odata.type": MEMBERS_ADDED_TYPE,
231 "visibleHistoryStartDateTime": visible_from,
232 "members": members,
233 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
234 }),
235 created(),
236 )
237 .unwrap()
238 }
239
240 fn plain_names(user_id: Option<&str>, name: Option<&str>) -> String {
241 name.or(user_id).unwrap_or("Unknown").to_owned()
242 }
243
244 #[test]
245 fn a_rename_reads_like_teams() {
246 let renamed = |name: Value| {
247 RosterEvent::from_graph(
248 &json!({
249 "@odata.type": CHAT_RENAMED_TYPE,
250 "chatDisplayName": name,
251 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
252 }),
253 created(),
254 )
255 .unwrap()
256 };
257 let event = renamed(json!("Release crew"));
258 assert_eq!(event.change, RosterChange::Renamed);
259 assert_eq!(
260 event.text(plain_names),
261 "Daniel changed the group name to Release crew."
262 );
263 assert_eq!(RosterEvent::from_json(&event.to_json()).unwrap(), event);
264 assert_eq!(
265 renamed(json!(null)).text(plain_names),
266 "Daniel removed the group name for this conversation."
267 );
268 }
269
270 #[test]
271 fn added_without_history_reads_like_teams() {
272 let event = added(
273 json!([{"id": "ann", "displayName": "Ann"}]),
274 json!("2026-10-17T09:00:00Z"),
275 );
276 assert_eq!(event.history, SharedHistory::None);
277 assert_eq!(event.text(plain_names), "Daniel added Ann to the chat.");
278 }
279
280 #[test]
281 fn shared_history_is_all_or_rounded_days() {
282 let all = added(json!([{"id": "ann"}]), json!("0001-01-01T00:00:00Z"));
283 assert_eq!(all.history, SharedHistory::All);
284 assert_eq!(
285 all.text(plain_names),
286 "Daniel added ann to the chat and shared all chat history."
287 );
288 let one = added(json!([{"id": "ann"}]), json!("2026-10-16T08:59:58Z"));
289 assert_eq!(
290 one.text(plain_names),
291 "Daniel added ann to the chat and shared chat history from the past day."
292 );
293 let week = added(json!([{"id": "ann"}]), json!("2026-10-10T09:00:00Z"));
294 assert_eq!(week.history, SharedHistory::Days(7));
295 }
296
297 #[test]
298 fn targets_join_with_and_then_count_the_rest() {
299 let two = added(json!([{"id": "ann"}, {"id": "bob"}]), Value::Null);
300 assert_eq!(
301 two.text(plain_names),
302 "Daniel added ann and bob to the chat."
303 );
304 let four = added(
305 json!([{"id": "ann"}, {"id": "bob"}, {"id": "cid"}, {"id": "dan"}]),
306 Value::Null,
307 );
308 assert_eq!(
309 four.text(plain_names),
310 "Daniel added ann and 3 others to the chat."
311 );
312 }
313
314 #[test]
315 fn self_removal_is_leaving() {
316 let detail = json!({
317 "@odata.type": MEMBERS_DELETED_TYPE,
318 "members": [{"id": "me"}],
319 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
320 });
321 let event = RosterEvent::from_graph(&detail, created()).unwrap();
322 assert_eq!(event.change, RosterChange::Left);
323 assert_eq!(event.text(plain_names), "Daniel left the chat.");
324 let mut removed = detail.clone();
325 removed["members"] = json!([{"id": "ann", "displayName": "Ann"}]);
326 let event = RosterEvent::from_graph(&removed, created()).unwrap();
327 assert_eq!(event.text(plain_names), "Daniel removed Ann from the chat.");
328 }
329
330 #[test]
331 fn stored_json_round_trips_and_is_not_a_call_event() {
332 let event = added(json!([{"id": "ann"}]), Value::Null);
333 let json = event.to_json();
334 assert_eq!(RosterEvent::from_json(&json), Some(event));
335 assert!(crate::CallEvent::from_json(&json).is_none());
336 assert!(RosterEvent::from_json("{\"phase\":\"Ended\"}").is_none());
337 }
338
339 #[test]
340 fn other_events_are_not_roster_changes() {
341 let joined = json!({"@odata.type": "#microsoft.graph.membersJoinedEventMessageDetail"});
342 assert!(RosterEvent::from_graph(&joined, created()).is_none());
343 }
344
345 #[test]
346 fn merging_skips_known_members() {
347 let member = |user_id: &str| MemberRecord {
348 user_id: Some(user_id.to_owned()),
349 display_name: user_id.to_owned(),
350 };
351 let mut members = vec![member("me"), member("ann")];
352 merge_members(&mut members, &[member("ann"), member("bob")]);
353 let ids: Vec<_> = members
354 .iter()
355 .filter_map(|record| record.user_id.clone())
356 .collect();
357 assert_eq!(ids, ["me", "ann", "bob"]);
358 }
359
360 #[test]
361 fn an_installed_app_reads_like_teams() {
362 let detail = json!({
363 "@odata.type": APP_INSTALLED_TYPE,
364 "teamsAppId": "app-1",
365 "teamsAppDisplayName": "Jira",
366 "initiator": {"user": {"id": "ann", "displayName": "Ann Example"}},
367 });
368 let event = RosterEvent::from_graph(&detail, created()).unwrap();
369 assert_eq!(event.change, RosterChange::AppAdded);
370 assert!(event.member_ids.is_empty());
371 assert_eq!(event.text(plain_names), "Ann Example added Jira to the chat.");
372 }
373}