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