| 1 | use serde_json::{Value, json}; |
| 2 | use session::{Method, Request, SPACES, Scope, Session}; |
| 3 | |
| 4 | use crate::error::Result; |
| 5 | use crate::language_settings::with_headers; |
| 6 | use crate::messages::ensure_success; |
| 7 | use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport}; |
| 8 | |
| 9 | const SKYPE_SCOPE: &str = "user_impersonation"; |
| 10 | const BOT_MRI_PREFIX: &str = "28:"; |
| 11 | const BOT_TYPE: &str = "BOT"; |
| 12 | const PLACEHOLDER_IMAGE_HOST: &str = "www.contoso.com"; |
| 13 | const SECURE_SCHEME: &str = "https://"; |
| 14 | const PROFILE_QUERY: &str = "isMailAddress=false&enableGuest=true&includeIBBarredUsers=true&skypeTeamsInfo=true&includeBots=true"; |
| 15 | |
| 16 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 17 | pub struct BotProfile { |
| 18 | pub bot_id: String, |
| 19 | pub display_name: String, |
| 20 | pub image_url: Option<String>, |
| 21 | } |
| 22 | |
| 23 | pub struct BotProfiles<T: CsaTransport = SessionTransport> { |
| 24 | transport: T, |
| 25 | url: String, |
| 26 | } |
| 27 | |
| 28 | impl BotProfiles<SessionTransport> { |
| 29 | pub fn new(session: &Session) -> Self { |
| 30 | let transport = SessionTransport::with_scope(session, Scope::new(SPACES, SKYPE_SCOPE)); |
| 31 | BotProfiles::with_transport(transport, DEFAULT_REGION) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | impl<T: CsaTransport> BotProfiles<T> { |
| 36 | pub fn with_transport(transport: T, region: &str) -> Self { |
| 37 | BotProfiles { |
| 38 | transport, |
| 39 | url: format!( |
| 40 | "https://teams.cloud.microsoft/api/mt/{region}/beta/users/fetchShortProfile?{PROFILE_QUERY}" |
| 41 | ), |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | pub async fn fetch(&self, bot_ids: &[String]) -> Result<Vec<BotProfile>> { |
| 46 | if bot_ids.is_empty() { |
| 47 | return Ok(Vec::new()); |
| 48 | } |
| 49 | let mris: Vec<Value> = bot_ids |
| 50 | .iter() |
| 51 | .map(|bot_id| json!(format!("{BOT_MRI_PREFIX}{bot_id}"))) |
| 52 | .collect(); |
| 53 | let answer = self |
| 54 | .transport |
| 55 | .send(with_headers(Request::with_body( |
| 56 | Method::Post, |
| 57 | self.url.clone(), |
| 58 | Value::Array(mris), |
| 59 | ))) |
| 60 | .await?; |
| 61 | ensure_success(&answer)?; |
| 62 | Ok(parse_bot_profiles(&answer.body)) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | pub fn parse_bot_profiles(body: &Value) -> Vec<BotProfile> { |
| 67 | body.get("value") |
| 68 | .and_then(Value::as_array) |
| 69 | .map(Vec::as_slice) |
| 70 | .unwrap_or_default() |
| 71 | .iter() |
| 72 | .filter(|profile| profile.get("type").and_then(Value::as_str) == Some(BOT_TYPE)) |
| 73 | .filter_map(|profile| { |
| 74 | let bot_id = profile |
| 75 | .get("mri") |
| 76 | .and_then(Value::as_str)? |
| 77 | .strip_prefix(BOT_MRI_PREFIX)? |
| 78 | .to_owned(); |
| 79 | let display_name = profile |
| 80 | .get("displayName") |
| 81 | .and_then(Value::as_str) |
| 82 | .filter(|name| !name.trim().is_empty())? |
| 83 | .to_owned(); |
| 84 | let image_url = profile |
| 85 | .get("imageUri") |
| 86 | .and_then(Value::as_str) |
| 87 | .filter(|url| is_real_image(url)) |
| 88 | .map(str::to_owned); |
| 89 | Some(BotProfile { |
| 90 | bot_id, |
| 91 | display_name, |
| 92 | image_url, |
| 93 | }) |
| 94 | }) |
| 95 | .collect() |
| 96 | } |
| 97 | |
| 98 | fn is_real_image(url: &str) -> bool { |
| 99 | url.strip_prefix(SECURE_SCHEME) |
| 100 | .and_then(|rest| rest.split('/').next()) |
| 101 | .is_some_and(|host| !host.is_empty() && host != PLACEHOLDER_IMAGE_HOST) |
| 102 | } |
| 103 | |
| 104 | #[cfg(test)] |
| 105 | mod tests { |
| 106 | use std::sync::Mutex; |
| 107 | |
| 108 | use session::ApiResponse; |
| 109 | |
| 110 | use super::*; |
| 111 | |
| 112 | struct Canned { |
| 113 | body: Value, |
| 114 | requests: Mutex<Vec<Request>>, |
| 115 | } |
| 116 | |
| 117 | impl CsaTransport for &Canned { |
| 118 | async fn send(&self, request: Request) -> Result<ApiResponse> { |
| 119 | self.requests.lock().unwrap().push(request); |
| 120 | Ok(ApiResponse { |
| 121 | status: 200, |
| 122 | body: self.body.clone(), |
| 123 | retry_after: None, |
| 124 | }) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | fn answer() -> Value { |
| 129 | json!({"value": [ |
| 130 | {"mri": "28:cf28171e", "displayName": "Echo", "type": "BOT", "imageUri": "http://www.contoso.com/"}, |
| 131 | {"mri": "28:358f0194", "displayName": "Workflows", "type": "BOT", |
| 132 | "imageUri": "https://res.cdn.office.net/teamsappdata/workflows_largeimage.png"}, |
| 133 | {"mri": "8:orgid:user-ada", "displayName": "Ada Example", "type": "ADUser"} |
| 134 | ]}) |
| 135 | } |
| 136 | |
| 137 | #[test] |
| 138 | fn bots_keep_their_name_and_only_a_real_icon() { |
| 139 | let profiles = parse_bot_profiles(&answer()); |
| 140 | assert_eq!( |
| 141 | profiles, |
| 142 | [ |
| 143 | BotProfile { |
| 144 | bot_id: "cf28171e".into(), |
| 145 | display_name: "Echo".into(), |
| 146 | image_url: None, |
| 147 | }, |
| 148 | BotProfile { |
| 149 | bot_id: "358f0194".into(), |
| 150 | display_name: "Workflows".into(), |
| 151 | image_url: Some( |
| 152 | "https://res.cdn.office.net/teamsappdata/workflows_largeimage.png".into() |
| 153 | ), |
| 154 | }, |
| 155 | ] |
| 156 | ); |
| 157 | } |
| 158 | |
| 159 | #[tokio::test] |
| 160 | async fn the_lookup_posts_bot_mris_to_the_middle_tier() { |
| 161 | let canned = Canned { |
| 162 | body: answer(), |
| 163 | requests: Mutex::new(Vec::new()), |
| 164 | }; |
| 165 | let client = BotProfiles::with_transport(&canned, "emea"); |
| 166 | let profiles = client.fetch(&["cf28171e".to_owned()]).await.unwrap(); |
| 167 | assert_eq!(profiles.len(), 2); |
| 168 | let requests = canned.requests.lock().unwrap(); |
| 169 | assert!(requests[0].url.starts_with( |
| 170 | "https://teams.cloud.microsoft/api/mt/emea/beta/users/fetchShortProfile?" |
| 171 | )); |
| 172 | assert_eq!(requests[0].body, Some(json!(["28:cf28171e"]))); |
| 173 | } |
| 174 | } |