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