BlueGit

ict rusty-teams

Files

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

source.rs

source.rs 14.6 KiB Download Raw
1use std::collections::HashMap;
2use std::sync::{LazyLock, Mutex};
3
4use chatsvc::{ChatListing, UserProfile, UserProfiles};
5use chrono::{DateTime, Utc};
6use futures_util::{StreamExt, stream};
7use graph::{Chat, Member, Message};
8use serde_json::Value;
9use session::Session;
10
11use super::chat::{
12 NativeMember, ORGID_PREFIX, aggregator_members, chat_type, graph_chat,
13 graph_chat_from_aggregator, graph_member, is_team_thread, one_on_one_ids, thread_members,
14};
15use super::message::graph_message;
16use crate::error::{Error, Result};
17use crate::remote::{ChatsPage, RemotePage};
18
19const THREADS_IN_FLIGHT: usize = 6;
20const OLDER_PAGE_MARKER: &str = "chatsvc:older";
21
22/// Profiles looked up so far; `None` when the directory does not know the id, such as a bot.
23static PROFILES: LazyLock<Mutex<HashMap<String, Option<UserProfile>>>> =
24 LazyLock::new(|| Mutex::new(HashMap::new()));
25static EXTERNAL: LazyLock<Mutex<HashMap<String, Option<String>>>> =
26 LazyLock::new(|| Mutex::new(HashMap::new()));
27static TENANTS: LazyLock<Mutex<HashMap<String, String>>> =
28 LazyLock::new(|| Mutex::new(HashMap::new()));
29/// Thread members by chat, kept while the thread's roster version stays the same.
30static ROSTERS: LazyLock<Mutex<HashMap<String, (String, Vec<NativeMember>)>>> =
31 LazyLock::new(|| Mutex::new(HashMap::new()));
32
33/// Chats, members and messages read from the Teams chat service instead of Graph.
34pub struct NativeChats<'a> {
35 session: &'a Session,
36}
37
38impl<'a> NativeChats<'a> {
39 pub fn new(session: &'a Session) -> Self {
40 NativeChats { session }
41 }
42
43 pub async fn first_page(&self, page_size: usize) -> Result<ChatsPage> {
44 let url = ChatListing::new(self.session).first_page_url(page_size);
45 self.page(&url).await
46 }
47
48 pub async fn page(&self, url: &str) -> Result<ChatsPage> {
49 let listing = ChatListing::new(self.session);
50 let page = listing.page(url).await?;
51 let conversations: Vec<&Value> = page
52 .conversations
53 .iter()
54 .filter(|conversation| chat_type(conversation).is_some())
55 .collect();
56 let keys: Vec<(String, String)> = conversations
57 .iter()
58 .map(|conversation| {
59 (
60 conversation["id"].as_str().unwrap_or_default().to_owned(),
61 conversation["threadProperties"]["rosterVersion"].to_string(),
62 )
63 })
64 .collect();
65 let rosters: Vec<Vec<NativeMember>> = stream::iter(keys)
66 .map(|(chat_id, version)| self.roster(&listing, chat_id, version))
67 .buffered(THREADS_IN_FLIGHT)
68 .collect()
69 .await;
70 let user_ids: Vec<String> = rosters
71 .iter()
72 .flatten()
73 .map(|member| member.user_id.clone())
74 .collect();
75 self.learn_profiles(&user_ids).await;
76 let items = conversations
77 .into_iter()
78 .zip(rosters)
79 .filter_map(|(conversation, roster)| graph_chat(conversation, self.named(roster, true)))
80 .collect();
81 Ok(ChatsPage {
82 items,
83 next_link: page.next_url,
84 })
85 }
86
87 pub async fn chat(&self, chat_id: &str) -> Result<Chat> {
88 let chat = chatsvc::aggregator_chat(self.session, chat_id).await?;
89 if is_team_thread(&chat) {
90 return Err(Error::UnknownConversation(chat_id.to_owned()));
91 }
92 let mut members = aggregator_members(&chat);
93 let user_ids: Vec<String> = members
94 .iter()
95 .map(|member| member.user_id.clone())
96 .collect();
97 self.learn_profiles(&user_ids).await;
98 for member in &mut members {
99 if member.name.is_none() {
100 member.name = profile_name(&member.user_id);
101 }
102 }
103 let members = members
104 .iter()
105 .map(|member| graph_member(member, profile_email(&member.user_id).as_deref()))
106 .collect();
107 graph_chat_from_aggregator(&chat, members)
108 .ok_or_else(|| Error::Unsupported("a chat the chat service aggregator cannot describe"))
109 }
110
111 /// A chat just created here, before the chat service lists it.
112 pub async fn created_chat(
113 &self,
114 chat_id: &str,
115 kind: &str,
116 topic: Option<&str>,
117 user_ids: &[String],
118 ) -> Result<Chat> {
119 self.learn_profiles(user_ids).await;
120 let members: Vec<NativeMember> = user_ids
121 .iter()
122 .map(|user_id| NativeMember {
123 user_id: user_id.clone(),
124 owner: kind != "oneOnOne",
125 name: None,
126 })
127 .collect();
128 serde_json::from_value(serde_json::json!({
129 "id": chat_id,
130 "topic": topic,
131 "chatType": kind,
132 "createdDateTime": Utc::now().to_rfc3339(),
133 "members": self.named(members, false),
134 }))
135 .map_err(|_| Error::Unsupported("a new chat without a Graph shape"))
136 }
137
138 pub async fn members(&self, chat_id: &str) -> Result<Vec<Member>> {
139 let listing = ChatListing::new(self.session);
140 let thread = listing.thread(chat_id).await?;
141 let members = thread_members(&thread);
142 let user_ids: Vec<String> = members
143 .iter()
144 .map(|member| member.user_id.clone())
145 .collect();
146 self.learn_profiles(&user_ids).await;
147 let named = self.named(members, false);
148 Ok(named
149 .into_iter()
150 .filter_map(|member| serde_json::from_value(member).ok())
151 .collect())
152 }
153
154 pub async fn messages(
155 &self,
156 chat_id: &str,
157 before: Option<DateTime<Utc>>,
158 page_size: usize,
159 ) -> Result<RemotePage> {
160 let page = ChatListing::new(self.session)
161 .messages(
162 chat_id,
163 before.map(|time| time.timestamp_millis()),
164 page_size,
165 )
166 .await?;
167 Ok(RemotePage {
168 items: page
169 .messages
170 .iter()
171 .filter_map(|message| graph_message(chat_id, message))
172 .collect(),
173 next_link: page.has_older.then(|| OLDER_PAGE_MARKER.to_owned()),
174 oldest_at: page
175 .oldest_arrival_ms
176 .and_then(DateTime::from_timestamp_millis),
177 })
178 }
179
180 pub async fn message(&self, chat_id: &str, message_id: &str) -> Result<Message> {
181 let native = ChatListing::new(self.session)
182 .message(chat_id, message_id)
183 .await?;
184 graph_message(chat_id, &native).ok_or(Error::Unsupported(
185 "a chat service message without a Graph shape",
186 ))
187 }
188
189 async fn roster(
190 &self,
191 listing: &ChatListing,
192 chat_id: String,
193 version: String,
194 ) -> Vec<NativeMember> {
195 let chat_id = chat_id.as_str();
196 if chat_id.is_empty() {
197 return Vec::new();
198 }
199 if let Some(pair) = one_on_one_ids(chat_id) {
200 return pair
201 .into_iter()
202 .map(|user_id| NativeMember {
203 user_id,
204 owner: false,
205 name: None,
206 })
207 .collect();
208 }
209 if let Some((known, members)) = ROSTERS.lock().unwrap().get(chat_id)
210 && *known == version
211 {
212 return members.clone();
213 }
214 match listing.thread(chat_id).await {
215 Ok(thread) => {
216 remember_tenants(&thread);
217 let members = thread_members(&thread);
218 ROSTERS
219 .lock()
220 .unwrap()
221 .insert(chat_id.to_owned(), (version, members.clone()));
222 members
223 }
224 Err(_) => ROSTERS
225 .lock()
226 .unwrap()
227 .get(chat_id)
228 .map(|(_, members)| members.clone())
229 .unwrap_or_default(),
230 }
231 }
232
233 async fn learn_profiles(&self, user_ids: &[String]) {
234 let unknown: Vec<String> = {
235 let known = PROFILES.lock().unwrap();
236 let mut unknown: Vec<String> = user_ids
237 .iter()
238 .filter(|user_id| !known.contains_key(*user_id))
239 .cloned()
240 .collect();
241 unknown.sort();
242 unknown.dedup();
243 unknown
244 };
245 if unknown.is_empty() {
246 return;
247 }
248 let lookup = UserProfiles::new(self.session);
249 let Ok(mut profiles) = lookup.fetch(&unknown).await else {
250 return;
251 };
252 let missing: Vec<String> = unknown
253 .iter()
254 .filter(|user_id| !profiles.iter().any(|profile| &profile.user_id == *user_id))
255 .cloned()
256 .collect();
257 if !missing.is_empty()
258 && let Ok(federated) = lookup.fetch_federated(&missing).await
259 {
260 let mut external = EXTERNAL.lock().unwrap();
261 for profile in &federated {
262 external.insert(profile.user_id.clone(), profile.tenant_name.clone());
263 }
264 profiles.extend(federated);
265 }
266 let mut known = PROFILES.lock().unwrap();
267 for user_id in unknown {
268 known.insert(user_id, None);
269 }
270 for profile in profiles {
271 known.insert(profile.user_id.clone(), Some(profile));
272 }
273 }
274
275 /// `drop_unknown` leaves out ids the directory does not know, which in a 1:1 is a bot.
276 fn named(&self, members: Vec<NativeMember>, drop_unknown: bool) -> Vec<Value> {
277 let known = PROFILES.lock().unwrap();
278 members
279 .into_iter()
280 .filter(|member| !drop_unknown || !matches!(known.get(&member.user_id), Some(None)))
281 .map(|mut member| {
282 let profile = known.get(&member.user_id).cloned().flatten();
283 if member.name.is_none() {
284 member.name = profile
285 .as_ref()
286 .and_then(|profile| profile.display_name.clone());
287 }
288 graph_member(
289 &member,
290 profile
291 .as_ref()
292 .and_then(|profile| profile.email.as_deref()),
293 )
294 })
295 .collect()
296 }
297}
298
299/// Directory people for profiles found outside the own organization, remembered as external.
300pub fn remember_external(profiles: Vec<UserProfile>) -> Vec<graph::User> {
301 let mut external = EXTERNAL.lock().unwrap();
302 let mut known = PROFILES.lock().unwrap();
303 profiles
304 .into_iter()
305 .map(|profile| {
306 external.insert(profile.user_id.clone(), profile.tenant_name.clone());
307 let user = graph::User {
308 id: profile.user_id.clone(),
309 display_name: profile.display_name.clone(),
310 mail: profile.email.clone(),
311 user_principal_name: profile.user_principal_name.clone(),
312 job_title: profile.job_title.clone(),
313 department: profile.department.clone(),
314 };
315 known.insert(profile.user_id.clone(), Some(profile));
316 user
317 })
318 .collect()
319}
320
321pub fn user_has_address(
322 mail: Option<&str>,
323 user_principal_name: Option<&str>,
324 query: &str,
325) -> bool {
326 let query = query.trim();
327 [mail, user_principal_name]
328 .into_iter()
329 .flatten()
330 .any(|address| address.eq_ignore_ascii_case(query))
331}
332
333pub fn is_email_address(query: &str) -> bool {
334 let query = query.trim();
335 query.split_once('@').is_some_and(|(local, domain)| {
336 !local.is_empty() && domain.contains('.') && !query.contains(char::is_whitespace)
337 })
338}
339
340fn remember_tenants(thread: &Value) {
341 let mut tenants = TENANTS.lock().unwrap();
342 for member in thread["members"].as_array().into_iter().flatten() {
343 if let (Some(user_id), Some(tenant)) = (
344 member["id"]
345 .as_str()
346 .and_then(|id| id.strip_prefix(ORGID_PREFIX)),
347 member["tenantId"]
348 .as_str()
349 .filter(|tenant| !tenant.is_empty()),
350 ) {
351 tenants.insert(user_id.to_owned(), tenant.to_owned());
352 }
353 }
354}
355
356/// People of other organizations the lookups met, with their organization's name when known.
357/// A chat member whose tenant is not `home_tenant` counts too.
358pub fn external_people(home_tenant: Option<&str>) -> Vec<(String, Option<String>)> {
359 let mut people: HashMap<String, Option<String>> = EXTERNAL.lock().unwrap().clone();
360 if let Some(home_tenant) = home_tenant {
361 for (user_id, tenant) in TENANTS.lock().unwrap().iter() {
362 if tenant != home_tenant {
363 people.entry(user_id.clone()).or_default();
364 }
365 }
366 }
367 people.into_iter().collect()
368}
369
370/// What the directory lookups learned about a user, for callers outside the chat path.
371pub fn known_profile(user_id: &str) -> Option<UserProfile> {
372 PROFILES.lock().unwrap().get(user_id).cloned().flatten()
373}
374
375fn profile_name(user_id: &str) -> Option<String> {
376 known_profile(user_id).and_then(|profile| profile.display_name)
377}
378
379fn profile_email(user_id: &str) -> Option<String> {
380 known_profile(user_id).and_then(|profile| profile.email)
381}
382
383#[cfg(test)]
384mod tests {
385 #[test]
386 fn a_chat_member_of_another_tenant_is_external() {
387 super::remember_tenants(&serde_json::json!({"members": [
388 {"id": "8:orgid:tenant-test-home", "tenantId": "home"},
389 {"id": "8:orgid:tenant-test-guest", "tenantId": "other"},
390 ]}));
391 let people = super::external_people(Some("home"));
392 assert!(
393 people
394 .iter()
395 .any(|(user_id, _)| user_id == "tenant-test-guest")
396 );
397 assert!(
398 !people
399 .iter()
400 .any(|(user_id, _)| user_id == "tenant-test-home")
401 );
402 }
403
404 #[test]
405 fn only_a_full_email_address_asks_for_people_of_other_organizations() {
406 assert!(super::is_email_address(" ann@example.com "));
407 assert!(!super::is_email_address("ann@example"));
408 assert!(!super::is_email_address("ann example@x.com"));
409 assert!(!super::is_email_address("@example.com"));
410 }
411
412 #[test]
413 fn an_address_matches_mail_or_the_principal_name() {
414 assert!(super::user_has_address(
415 None,
416 Some("Ada@Other.Example"),
417 "ada@other.example"
418 ));
419 assert!(!super::user_has_address(
420 Some("other@example.com"),
421 Some("ada@other.example"),
422 "missing@example.com"
423 ));
424 }
425}