| 1 | use std::collections::HashMap; |
| 2 | |
| 3 | use chatsvc::BotProfile; |
| 4 | use chrono::Utc; |
| 5 | use graph::Chat; |
| 6 | use store::{AvatarRecord, BOT_MRI_PREFIX, ChatRecord, MemberRecord}; |
| 7 | |
| 8 | use crate::engine::SyncEngine; |
| 9 | use crate::error::{Error, Result}; |
| 10 | use crate::mapping::chat_record; |
| 11 | use crate::remote::Remote; |
| 12 | |
| 13 | /// Bots Graph leaves out of 1:1 chat members, such as the Echo test call bot, by the id in the chat id. |
| 14 | #[derive(Default)] |
| 15 | pub(crate) struct BotPartners { |
| 16 | known: HashMap<String, Option<BotProfile>>, |
| 17 | } |
| 18 | |
| 19 | impl BotPartners { |
| 20 | pub(crate) fn unknown_ids(&self, chats: &[Chat], my_user_id: &str) -> Vec<String> { |
| 21 | let mut unknown: Vec<String> = chats |
| 22 | .iter() |
| 23 | .filter_map(|chat| chat.memberless_partner_id(my_user_id)) |
| 24 | .filter(|partner_id| !self.known.contains_key(*partner_id)) |
| 25 | .map(str::to_owned) |
| 26 | .collect(); |
| 27 | unknown.sort(); |
| 28 | unknown.dedup(); |
| 29 | unknown |
| 30 | } |
| 31 | |
| 32 | pub(crate) fn remember(&mut self, asked: &[String], profiles: Vec<BotProfile>) { |
| 33 | for bot_id in asked { |
| 34 | self.known.entry(bot_id.clone()).or_insert(None); |
| 35 | } |
| 36 | for profile in profiles { |
| 37 | self.known.insert(profile.bot_id.clone(), Some(profile)); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | pub(crate) fn profile(&self, bot_id: &str) -> Option<&BotProfile> { |
| 42 | self.known.get(bot_id)?.as_ref() |
| 43 | } |
| 44 | |
| 45 | pub(crate) fn chat_record(&self, chat: &Chat, my_user_id: &str) -> ChatRecord { |
| 46 | let mut record = chat_record(chat, my_user_id); |
| 47 | let partner = chat |
| 48 | .memberless_partner_id(my_user_id) |
| 49 | .and_then(|partner_id| self.profile(partner_id)); |
| 50 | if let Some(profile) = partner { |
| 51 | record.title = profile.display_name.clone(); |
| 52 | record.member_summary = profile.display_name.clone(); |
| 53 | record.members.push(MemberRecord { |
| 54 | user_id: Some(format!("{BOT_MRI_PREFIX}{}", profile.bot_id)), |
| 55 | display_name: profile.display_name.clone(), |
| 56 | }); |
| 57 | } |
| 58 | record |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | impl<R: Remote> SyncEngine<R> { |
| 63 | pub(crate) async fn resolve_bot_partners(&self, chats: &[Chat], my_user_id: &str) { |
| 64 | let unknown = self.bot_partners().unknown_ids(chats, my_user_id); |
| 65 | self.fetch_bot_profiles(&unknown).await; |
| 66 | } |
| 67 | |
| 68 | async fn fetch_bot_profiles(&self, bot_ids: &[String]) { |
| 69 | if bot_ids.is_empty() { |
| 70 | return; |
| 71 | } |
| 72 | match self.remote.bot_profiles(bot_ids).await { |
| 73 | Ok(profiles) => self.bot_partners().remember(bot_ids, profiles), |
| 74 | Err(Error::Unsupported(_)) => self.bot_partners().remember(bot_ids, Vec::new()), |
| 75 | Err(error) => self.report(format!("cannot look up bot chats: {error}")), |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | pub(crate) fn bot_partners(&self) -> std::sync::MutexGuard<'_, BotPartners> { |
| 80 | self.bot_partners |
| 81 | .lock() |
| 82 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 83 | } |
| 84 | |
| 85 | pub(crate) fn partner_chat_record(&self, chat: &Chat, my_user_id: &str) -> ChatRecord { |
| 86 | self.bot_partners().chat_record(chat, my_user_id) |
| 87 | } |
| 88 | |
| 89 | pub(crate) async fn fetch_bot_icons(&self, bot_mris: &[String]) -> Result<Vec<String>> { |
| 90 | let bot_ids: Vec<String> = bot_mris |
| 91 | .iter() |
| 92 | .filter_map(|mri| mri.strip_prefix(BOT_MRI_PREFIX)) |
| 93 | .map(str::to_owned) |
| 94 | .collect(); |
| 95 | let missing: Vec<String> = { |
| 96 | let partners = self.bot_partners(); |
| 97 | bot_ids |
| 98 | .iter() |
| 99 | .filter(|bot_id| !partners.known.contains_key(*bot_id)) |
| 100 | .cloned() |
| 101 | .collect() |
| 102 | }; |
| 103 | self.fetch_bot_profiles(&missing).await; |
| 104 | let mut changed = Vec::new(); |
| 105 | for bot_id in bot_ids { |
| 106 | let image_url = self |
| 107 | .bot_partners() |
| 108 | .profile(&bot_id) |
| 109 | .and_then(|profile| profile.image_url.clone()); |
| 110 | let photo = match image_url { |
| 111 | Some(url) => match self.remote.external_image(&url).await { |
| 112 | Ok(photo) => Some(photo), |
| 113 | Err(error) => { |
| 114 | self.report(format!("cannot load a bot icon: {error}")); |
| 115 | continue; |
| 116 | } |
| 117 | }, |
| 118 | None => None, |
| 119 | }; |
| 120 | let user_id = format!("{BOT_MRI_PREFIX}{bot_id}"); |
| 121 | if photo.is_some() { |
| 122 | changed.push(user_id.clone()); |
| 123 | } |
| 124 | self.store.upsert_avatar(&AvatarRecord { |
| 125 | user_id, |
| 126 | content_type: photo |
| 127 | .as_ref() |
| 128 | .map(|photo| photo.content_type.clone()) |
| 129 | .unwrap_or_default(), |
| 130 | bytes: photo.map(|photo| photo.bytes), |
| 131 | fetched_at: Utc::now(), |
| 132 | })?; |
| 133 | } |
| 134 | Ok(changed) |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | #[cfg(test)] |
| 139 | mod tests { |
| 140 | use super::*; |
| 141 | |
| 142 | fn echo_chat() -> Chat { |
| 143 | serde_json::from_value(serde_json::json!({ |
| 144 | "id": "19:user-me_bot-echo@unq.gbl.spaces", |
| 145 | "chatType": "oneOnOne", |
| 146 | "members": [{"userId": "user-me", "displayName": "Test Me"}], |
| 147 | })) |
| 148 | .unwrap() |
| 149 | } |
| 150 | |
| 151 | fn echo_profile() -> BotProfile { |
| 152 | BotProfile { |
| 153 | bot_id: "bot-echo".into(), |
| 154 | display_name: "Echo".into(), |
| 155 | image_url: None, |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | #[test] |
| 160 | fn a_resolved_bot_names_the_chat_and_joins_its_members() { |
| 161 | let mut partners = BotPartners::default(); |
| 162 | let chats = [echo_chat()]; |
| 163 | assert_eq!(partners.unknown_ids(&chats, "user-me"), ["bot-echo"]); |
| 164 | partners.remember(&["bot-echo".to_owned()], vec![echo_profile()]); |
| 165 | assert!(partners.unknown_ids(&chats, "user-me").is_empty()); |
| 166 | let record = partners.chat_record(&chats[0], "user-me"); |
| 167 | assert_eq!(record.title, "Echo"); |
| 168 | assert_eq!(record.member_summary, "Echo"); |
| 169 | let bot = record.members.last().unwrap(); |
| 170 | assert_eq!(bot.user_id.as_deref(), Some("28:bot-echo")); |
| 171 | assert!(bot.is_bot()); |
| 172 | } |
| 173 | |
| 174 | #[test] |
| 175 | fn a_partner_that_is_no_bot_is_asked_once_and_keeps_the_graph_title() { |
| 176 | let mut partners = BotPartners::default(); |
| 177 | let chats = [echo_chat()]; |
| 178 | partners.remember(&["bot-echo".to_owned()], Vec::new()); |
| 179 | assert!(partners.unknown_ids(&chats, "user-me").is_empty()); |
| 180 | let record = partners.chat_record(&chats[0], "user-me"); |
| 181 | assert_eq!(record.title, "(only you)"); |
| 182 | assert_eq!(record.members.len(), 1); |
| 183 | } |
| 184 | } |