| 1 | use std::collections::HashSet; |
| 2 | use std::time::{Duration, Instant}; |
| 3 | |
| 4 | use graph::User; |
| 5 | |
| 6 | use crate::engine::{Conversation, META_USER_ID, SyncEngine}; |
| 7 | use crate::error::Result; |
| 8 | use crate::remote::Remote; |
| 9 | |
| 10 | const DIRECTORY_CACHE_TTL: Duration = Duration::from_secs(300); |
| 11 | const DIRECTORY_CACHE_MAX_QUERIES: usize = 64; |
| 12 | const DIRECTORY_MIN_QUERY_CHARS: usize = 2; |
| 13 | const RECENT_SENDERS_SCANNED: usize = 200; |
| 14 | |
| 15 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 16 | pub enum PersonSource { |
| 17 | Member, |
| 18 | Directory, |
| 19 | } |
| 20 | |
| 21 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 22 | pub struct PersonCandidate { |
| 23 | pub user_id: String, |
| 24 | pub display_name: String, |
| 25 | pub mail: Option<String>, |
| 26 | pub job_title: Option<String>, |
| 27 | pub source: PersonSource, |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub enum MentionCandidate { |
| 32 | Person(PersonCandidate), |
| 33 | Channel { channel_id: String, name: String }, |
| 34 | Team { team_id: String, name: String }, |
| 35 | } |
| 36 | |
| 37 | impl MentionCandidate { |
| 38 | pub fn display_name(&self) -> &str { |
| 39 | match self { |
| 40 | MentionCandidate::Person(person) => &person.display_name, |
| 41 | MentionCandidate::Channel { name, .. } | MentionCandidate::Team { name, .. } => name, |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | /// Ready to pass to the send, reply and edit calls. |
| 46 | pub fn to_mention(&self) -> crate::MentionInput { |
| 47 | match self { |
| 48 | MentionCandidate::Person(person) => { |
| 49 | crate::MentionInput::user(&person.user_id, &person.display_name) |
| 50 | } |
| 51 | MentionCandidate::Channel { channel_id, name } => { |
| 52 | crate::MentionInput::channel(channel_id, name) |
| 53 | } |
| 54 | MentionCandidate::Team { team_id, name } => crate::MentionInput::team(team_id, name), |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub(crate) struct DirectoryCache { |
| 60 | entries: std::collections::HashMap<String, (Instant, Vec<User>)>, |
| 61 | } |
| 62 | |
| 63 | impl DirectoryCache { |
| 64 | pub(crate) fn new() -> Self { |
| 65 | DirectoryCache { |
| 66 | entries: std::collections::HashMap::new(), |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | fn get(&self, query: &str) -> Option<Vec<User>> { |
| 71 | let (stored_at, users) = self.entries.get(query)?; |
| 72 | (stored_at.elapsed() < DIRECTORY_CACHE_TTL).then(|| users.clone()) |
| 73 | } |
| 74 | |
| 75 | fn put(&mut self, query: &str, users: Vec<User>) { |
| 76 | if self.entries.len() >= DIRECTORY_CACHE_MAX_QUERIES { |
| 77 | self.entries |
| 78 | .retain(|_, (stored_at, _)| stored_at.elapsed() < DIRECTORY_CACHE_TTL); |
| 79 | } |
| 80 | if self.entries.len() >= DIRECTORY_CACHE_MAX_QUERIES { |
| 81 | self.entries.clear(); |
| 82 | } |
| 83 | self.entries |
| 84 | .insert(query.to_owned(), (Instant::now(), users)); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | impl<R: Remote> SyncEngine<R> { |
| 89 | /// Directory search, answers are cached in memory for five minutes per query. |
| 90 | pub async fn search_people(&self, query: &str) -> Result<Vec<User>> { |
| 91 | let key = query.trim().to_lowercase(); |
| 92 | if let Some(cached) = self.directory_lock().get(&key) { |
| 93 | return Ok(cached); |
| 94 | } |
| 95 | let users = self.remote.search_people(query).await?; |
| 96 | self.directory_lock().put(&key, users.clone()); |
| 97 | Ok(users) |
| 98 | } |
| 99 | |
| 100 | /// Autocomplete for `@`: members of the conversation first, then (channels) the channel and its team, |
| 101 | /// then the directory. A failing directory search still returns the local part. |
| 102 | pub async fn mention_candidates( |
| 103 | &self, |
| 104 | conversation_id: &str, |
| 105 | query: &str, |
| 106 | limit: usize, |
| 107 | ) -> Result<Vec<MentionCandidate>> { |
| 108 | let conversation = self.resolve(conversation_id)?; |
| 109 | let query = query.trim().trim_start_matches('@').trim().to_lowercase(); |
| 110 | let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default(); |
| 111 | let mut seen: HashSet<String> = HashSet::from([my_user_id]); |
| 112 | |
| 113 | let mut candidates: Vec<MentionCandidate> = ranked( |
| 114 | self.local_people(conversation_id)? |
| 115 | .into_iter() |
| 116 | .filter(|person| seen.insert(person.user_id.clone())) |
| 117 | .map(MentionCandidate::Person), |
| 118 | &query, |
| 119 | ); |
| 120 | if let Conversation::Channel { team_id } = &conversation { |
| 121 | candidates.extend(ranked( |
| 122 | self.scope_entries(conversation_id, team_id)?, |
| 123 | &query, |
| 124 | )); |
| 125 | } |
| 126 | let local_people = candidates |
| 127 | .iter() |
| 128 | .filter(|candidate| matches!(candidate, MentionCandidate::Person(_))) |
| 129 | .count(); |
| 130 | if query.chars().count() >= DIRECTORY_MIN_QUERY_CHARS |
| 131 | && local_people < limit |
| 132 | && let Ok(users) = self.search_people(&query).await |
| 133 | { |
| 134 | let directory = users |
| 135 | .into_iter() |
| 136 | .filter(|user| seen.insert(user.id.clone())) |
| 137 | .map(directory_person) |
| 138 | .map(MentionCandidate::Person); |
| 139 | candidates.extend(ranked(directory, &query)); |
| 140 | } |
| 141 | candidates.truncate(limit); |
| 142 | Ok(candidates) |
| 143 | } |
| 144 | |
| 145 | fn local_people(&self, conversation_id: &str) -> Result<Vec<PersonCandidate>> { |
| 146 | let member = |user_id: &str, display_name: &str| PersonCandidate { |
| 147 | user_id: user_id.to_owned(), |
| 148 | display_name: display_name.to_owned(), |
| 149 | mail: None, |
| 150 | job_title: None, |
| 151 | source: PersonSource::Member, |
| 152 | }; |
| 153 | if let Some(chat) = self.store.chat(conversation_id)? { |
| 154 | return Ok(chat |
| 155 | .members |
| 156 | .iter() |
| 157 | .filter_map(|record| Some(member(record.user_id.as_deref()?, &record.display_name))) |
| 158 | .collect()); |
| 159 | } |
| 160 | let mut recent = self |
| 161 | .store |
| 162 | .messages(conversation_id, None, RECENT_SENDERS_SCANNED)?; |
| 163 | recent.reverse(); |
| 164 | Ok(recent |
| 165 | .iter() |
| 166 | .filter_map(|record| { |
| 167 | Some(member( |
| 168 | record.sender_id.as_deref()?, |
| 169 | record.sender_name.as_deref()?, |
| 170 | )) |
| 171 | }) |
| 172 | .collect()) |
| 173 | } |
| 174 | |
| 175 | fn scope_entries( |
| 176 | &self, |
| 177 | channel_id: &str, |
| 178 | team_id: &str, |
| 179 | ) -> Result<impl Iterator<Item = MentionCandidate> + use<R>> { |
| 180 | let channel = self |
| 181 | .store |
| 182 | .channel(channel_id)? |
| 183 | .map(|channel| MentionCandidate::Channel { |
| 184 | channel_id: channel.id, |
| 185 | name: channel.name, |
| 186 | }); |
| 187 | let team = self |
| 188 | .store |
| 189 | .team(team_id)? |
| 190 | .map(|team| MentionCandidate::Team { |
| 191 | team_id: team.id, |
| 192 | name: team.name, |
| 193 | }); |
| 194 | Ok(channel.into_iter().chain(team)) |
| 195 | } |
| 196 | |
| 197 | fn directory_lock(&self) -> std::sync::MutexGuard<'_, DirectoryCache> { |
| 198 | self.directory_cache |
| 199 | .lock() |
| 200 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | fn directory_person(user: User) -> PersonCandidate { |
| 205 | PersonCandidate { |
| 206 | display_name: user |
| 207 | .display_name |
| 208 | .or_else(|| user.mail.clone()) |
| 209 | .or(user.user_principal_name) |
| 210 | .unwrap_or_default(), |
| 211 | mail: user.mail, |
| 212 | job_title: user.job_title, |
| 213 | user_id: user.id, |
| 214 | source: PersonSource::Directory, |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | /// Keeps matches only. Best match first, the incoming order breaks ties. |
| 219 | fn ranked( |
| 220 | candidates: impl Iterator<Item = MentionCandidate>, |
| 221 | query: &str, |
| 222 | ) -> Vec<MentionCandidate> { |
| 223 | let mut scored: Vec<(u8, MentionCandidate)> = candidates |
| 224 | .filter_map(|candidate| Some((match_tier(&candidate, query)?, candidate))) |
| 225 | .collect(); |
| 226 | scored.sort_by_key(|(tier, _)| *tier); |
| 227 | scored.into_iter().map(|(_, candidate)| candidate).collect() |
| 228 | } |
| 229 | |
| 230 | fn match_tier(candidate: &MentionCandidate, query: &str) -> Option<u8> { |
| 231 | if query.is_empty() { |
| 232 | return Some(0); |
| 233 | } |
| 234 | let name = candidate.display_name().to_lowercase(); |
| 235 | if name.starts_with(query) { |
| 236 | return Some(0); |
| 237 | } |
| 238 | if name |
| 239 | .split(|character: char| !character.is_alphanumeric()) |
| 240 | .any(|word| word.starts_with(query)) |
| 241 | { |
| 242 | return Some(1); |
| 243 | } |
| 244 | if name.contains(query) { |
| 245 | return Some(2); |
| 246 | } |
| 247 | let MentionCandidate::Person(person) = candidate else { |
| 248 | return None; |
| 249 | }; |
| 250 | let mail = person.mail.as_deref()?.to_lowercase(); |
| 251 | if mail.starts_with(query) { |
| 252 | Some(3) |
| 253 | } else { |
| 254 | mail.contains(query).then_some(4) |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | #[cfg(test)] |
| 259 | mod tests { |
| 260 | use super::*; |
| 261 | |
| 262 | fn person(user_id: &str, name: &str, mail: Option<&str>) -> MentionCandidate { |
| 263 | MentionCandidate::Person(PersonCandidate { |
| 264 | user_id: user_id.to_owned(), |
| 265 | display_name: name.to_owned(), |
| 266 | mail: mail.map(str::to_owned), |
| 267 | job_title: None, |
| 268 | source: PersonSource::Directory, |
| 269 | }) |
| 270 | } |
| 271 | |
| 272 | fn names(candidates: Vec<MentionCandidate>) -> Vec<String> { |
| 273 | candidates |
| 274 | .iter() |
| 275 | .map(|candidate| candidate.display_name().to_owned()) |
| 276 | .collect() |
| 277 | } |
| 278 | |
| 279 | #[test] |
| 280 | fn prefix_beats_word_start_beats_contains() { |
| 281 | let ranked = ranked( |
| 282 | [ |
| 283 | person("1", "Maria Adams", None), |
| 284 | person("2", "Madame Curie", None), |
| 285 | person("3", "Ada Example", None), |
| 286 | person("4", "Nobody", None), |
| 287 | ] |
| 288 | .into_iter(), |
| 289 | "ada", |
| 290 | ); |
| 291 | assert_eq!( |
| 292 | names(ranked), |
| 293 | ["Ada Example", "Maria Adams", "Madame Curie"] |
| 294 | ); |
| 295 | } |
| 296 | |
| 297 | #[test] |
| 298 | fn mail_matches_rank_after_name_matches() { |
| 299 | let ranked = ranked( |
| 300 | [ |
| 301 | person("1", "Zed", Some("ada@example.com")), |
| 302 | person("2", "Ada", None), |
| 303 | ] |
| 304 | .into_iter(), |
| 305 | "ada", |
| 306 | ); |
| 307 | assert_eq!(names(ranked), ["Ada", "Zed"]); |
| 308 | } |
| 309 | |
| 310 | #[test] |
| 311 | fn empty_query_keeps_the_incoming_order() { |
| 312 | let ranked = ranked( |
| 313 | [person("1", "B", None), person("2", "A", None)].into_iter(), |
| 314 | "", |
| 315 | ); |
| 316 | assert_eq!(names(ranked), ["B", "A"]); |
| 317 | } |
| 318 | |
| 319 | #[test] |
| 320 | fn candidates_convert_to_the_matching_mention() { |
| 321 | let team = MentionCandidate::Team { |
| 322 | team_id: "t".to_owned(), |
| 323 | name: "Squad".to_owned(), |
| 324 | }; |
| 325 | assert_eq!(team.to_mention(), crate::MentionInput::team("t", "Squad")); |
| 326 | } |
| 327 | |
| 328 | #[test] |
| 329 | fn the_directory_cache_expires_and_is_bounded() { |
| 330 | let mut cache = DirectoryCache::new(); |
| 331 | cache.put("ada", Vec::new()); |
| 332 | assert!(cache.get("ada").is_some()); |
| 333 | assert!(cache.get("bo").is_none()); |
| 334 | for index in 0..DIRECTORY_CACHE_MAX_QUERIES + 1 { |
| 335 | cache.put(&format!("q{index}"), Vec::new()); |
| 336 | } |
| 337 | assert!(cache.entries.len() <= DIRECTORY_CACHE_MAX_QUERIES); |
| 338 | } |
| 339 | } |