| 1 | use serde_json::{Map, Value, json}; |
| 2 | use session::{Method, Request, SPACES, Scope, Session}; |
| 3 | |
| 4 | use crate::error::{Error, Result}; |
| 5 | use crate::messages::ensure_success; |
| 6 | use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport}; |
| 7 | use crate::translate::language_code; |
| 8 | |
| 9 | const SKYPE_SCOPE: &str = "user_impersonation"; |
| 10 | const CLIENT_VERSION: &str = "1415/26091712213"; |
| 11 | const CLIENT_TYPE: &str = "TeamsV2Web"; |
| 12 | |
| 13 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 14 | pub enum TranslationBehavior { |
| 15 | #[default] |
| 16 | Ask, |
| 17 | Auto, |
| 18 | Never, |
| 19 | } |
| 20 | |
| 21 | impl TranslationBehavior { |
| 22 | pub fn code(self) -> &'static str { |
| 23 | match self { |
| 24 | TranslationBehavior::Ask => "Ask", |
| 25 | TranslationBehavior::Auto => "Yes", |
| 26 | TranslationBehavior::Never => "No", |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | pub fn from_code(code: &str) -> Self { |
| 31 | match code { |
| 32 | "Yes" => TranslationBehavior::Auto, |
| 33 | "No" => TranslationBehavior::Never, |
| 34 | _ => TranslationBehavior::Ask, |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | #[derive(Debug, Clone, PartialEq, Default)] |
| 40 | pub struct LanguageSettings { |
| 41 | pub display_locale: Option<String>, |
| 42 | pub target_locale: Option<String>, |
| 43 | pub behavior: TranslationBehavior, |
| 44 | pub authoring_locales: Vec<String>, |
| 45 | pub preferences: Map<String, Value>, |
| 46 | } |
| 47 | |
| 48 | impl LanguageSettings { |
| 49 | pub fn never_translate_codes(&self) -> Vec<String> { |
| 50 | let mut codes: Vec<String> = Vec::new(); |
| 51 | for locale in &self.authoring_locales { |
| 52 | let code = language_code(locale); |
| 53 | if !code.is_empty() && !codes.contains(&code) { |
| 54 | codes.push(code); |
| 55 | } |
| 56 | } |
| 57 | codes |
| 58 | } |
| 59 | |
| 60 | pub fn with_never_translate(&self, code: &str) -> Vec<String> { |
| 61 | let mut locales = self.authoring_locales.clone(); |
| 62 | if !self |
| 63 | .never_translate_codes() |
| 64 | .iter() |
| 65 | .any(|known| known == code) |
| 66 | { |
| 67 | locales.push(code.to_owned()); |
| 68 | } |
| 69 | locales |
| 70 | } |
| 71 | |
| 72 | pub fn without_never_translate(&self, code: &str) -> Vec<String> { |
| 73 | self.authoring_locales |
| 74 | .iter() |
| 75 | .filter(|locale| language_code(locale) != code) |
| 76 | .cloned() |
| 77 | .collect() |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | impl LanguageSettings { |
| 82 | /// The shape of the account answer, so a stored copy parses back with `parse_language_settings`. |
| 83 | pub fn to_account_value(&self) -> Value { |
| 84 | let locale = |
| 85 | |locale: &Option<String>| locale.as_ref().map(|locale| json!({"locale": locale})); |
| 86 | json!({"userLanguageAccountSettings": {"value": { |
| 87 | "defaultDisplayLanguage": locale(&self.display_locale), |
| 88 | "defaultTranslationLanguage": locale(&self.target_locale), |
| 89 | "authoringLanguages": authoring_patch(&self.authoring_locales)["authoringLanguages"], |
| 90 | "translationPreferences": self.preferences, |
| 91 | }}}) |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | pub fn parse_language_settings(body: &Value) -> Result<LanguageSettings> { |
| 96 | let value = body |
| 97 | .pointer("/userLanguageAccountSettings/value") |
| 98 | .and_then(Value::as_object) |
| 99 | .ok_or_else(|| Error::UnexpectedAnswer("no language settings".into()))?; |
| 100 | let locale = |pointer: &str| { |
| 101 | value |
| 102 | .get(pointer) |
| 103 | .and_then(|entry| entry.get("locale")) |
| 104 | .and_then(Value::as_str) |
| 105 | .filter(|locale| !locale.is_empty()) |
| 106 | .map(str::to_owned) |
| 107 | }; |
| 108 | let preferences = value |
| 109 | .get("translationPreferences") |
| 110 | .and_then(Value::as_object) |
| 111 | .cloned() |
| 112 | .unwrap_or_default(); |
| 113 | Ok(LanguageSettings { |
| 114 | display_locale: locale("defaultDisplayLanguage"), |
| 115 | target_locale: locale("defaultTranslationLanguage"), |
| 116 | behavior: preferences |
| 117 | .get("translationBehavior") |
| 118 | .and_then(Value::as_str) |
| 119 | .map_or_else(TranslationBehavior::default, TranslationBehavior::from_code), |
| 120 | authoring_locales: value |
| 121 | .get("authoringLanguages") |
| 122 | .and_then(Value::as_array) |
| 123 | .into_iter() |
| 124 | .flatten() |
| 125 | .filter_map(|entry| entry.get("locale")?.as_str().map(str::to_owned)) |
| 126 | .collect(), |
| 127 | preferences, |
| 128 | }) |
| 129 | } |
| 130 | |
| 131 | pub fn read_body() -> Value { |
| 132 | json!({"userLanguageAccountSettings": true}) |
| 133 | } |
| 134 | |
| 135 | pub fn behavior_patch(settings: &LanguageSettings, behavior: TranslationBehavior) -> Value { |
| 136 | let mut preferences = settings.preferences.clone(); |
| 137 | preferences.insert("translationBehavior".into(), json!(behavior.code())); |
| 138 | json!({"translationPreferences": preferences}) |
| 139 | } |
| 140 | |
| 141 | pub fn target_patch(locale: &str) -> Value { |
| 142 | json!({"defaultTranslationLanguage": {"locale": locale}}) |
| 143 | } |
| 144 | |
| 145 | pub fn authoring_patch(locales: &[String]) -> Value { |
| 146 | json!({ |
| 147 | "authoringLanguages": locales |
| 148 | .iter() |
| 149 | .map(|locale| json!({"locale": locale})) |
| 150 | .collect::<Vec<Value>>() |
| 151 | }) |
| 152 | } |
| 153 | |
| 154 | pub struct LanguageSettingsClient<T: CsaTransport = SessionTransport> { |
| 155 | transport: T, |
| 156 | base_url: String, |
| 157 | } |
| 158 | |
| 159 | impl LanguageSettingsClient<SessionTransport> { |
| 160 | pub fn new(session: &Session) -> Self { |
| 161 | Self::with_region(session, DEFAULT_REGION) |
| 162 | } |
| 163 | |
| 164 | pub fn with_region(session: &Session, region: &str) -> Self { |
| 165 | let transport = SessionTransport::with_scope(session, Scope::new(SPACES, SKYPE_SCOPE)); |
| 166 | LanguageSettingsClient::with_transport(transport, region) |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | impl<T: CsaTransport> LanguageSettingsClient<T> { |
| 171 | pub fn with_transport(transport: T, region: &str) -> Self { |
| 172 | LanguageSettingsClient { |
| 173 | transport, |
| 174 | base_url: format!("https://teams.cloud.microsoft/api/mt/{region}/beta/users"), |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | pub async fn read(&self) -> Result<LanguageSettings> { |
| 179 | let url = format!("{}/useraggregatesettings", self.base_url); |
| 180 | let answer = self |
| 181 | .transport |
| 182 | .send(with_headers(Request::with_body( |
| 183 | Method::Post, |
| 184 | url, |
| 185 | read_body(), |
| 186 | ))) |
| 187 | .await?; |
| 188 | ensure_success(&answer)?; |
| 189 | parse_language_settings(&answer.body) |
| 190 | } |
| 191 | |
| 192 | pub async fn patch(&self, patch: Value) -> Result<()> { |
| 193 | let url = format!("{}/languageAccountSettings", self.base_url); |
| 194 | let answer = self |
| 195 | .transport |
| 196 | .send(with_headers(Request::with_body(Method::Patch, url, patch))) |
| 197 | .await?; |
| 198 | ensure_success(&answer) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | fn with_headers(mut request: Request) -> Request { |
| 203 | request.headers = vec![ |
| 204 | ("x-ms-client-type".to_owned(), CLIENT_TYPE.to_owned()), |
| 205 | ("x-ms-client-version".to_owned(), CLIENT_VERSION.to_owned()), |
| 206 | ("Accept".to_owned(), "application/json".to_owned()), |
| 207 | ]; |
| 208 | request |
| 209 | } |
| 210 | |
| 211 | #[cfg(test)] |
| 212 | mod tests { |
| 213 | use std::collections::VecDeque; |
| 214 | use std::sync::Mutex; |
| 215 | |
| 216 | use session::ApiResponse; |
| 217 | |
| 218 | use super::*; |
| 219 | |
| 220 | struct Canned { |
| 221 | answers: Mutex<VecDeque<(u16, Value)>>, |
| 222 | requests: Mutex<Vec<Request>>, |
| 223 | } |
| 224 | |
| 225 | impl CsaTransport for &Canned { |
| 226 | async fn send(&self, request: Request) -> Result<ApiResponse> { |
| 227 | self.requests.lock().unwrap().push(request); |
| 228 | let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted"); |
| 229 | Ok(ApiResponse { |
| 230 | status, |
| 231 | body, |
| 232 | retry_after: None, |
| 233 | }) |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | fn account() -> Value { |
| 238 | json!({"userLanguageAccountSettings": {"value": { |
| 239 | "defaultDisplayLanguage": {"locale": "en-US"}, |
| 240 | "defaultTranslationLanguage": {"locale": "en"}, |
| 241 | "authoringLanguages": [{"locale": "de-DE"}, {"locale": "en-DE"}, {"locale": "en-US"}], |
| 242 | "translationPreferences": { |
| 243 | "translationBehavior": "Ask", |
| 244 | "untranslatedLanguages": ["de", "en"], |
| 245 | "languageOverrides": [] |
| 246 | } |
| 247 | }}}) |
| 248 | } |
| 249 | |
| 250 | #[test] |
| 251 | fn parses_the_account_settings() { |
| 252 | let settings = parse_language_settings(&account()).unwrap(); |
| 253 | assert_eq!(settings.display_locale.as_deref(), Some("en-US")); |
| 254 | assert_eq!(settings.target_locale.as_deref(), Some("en")); |
| 255 | assert_eq!(settings.behavior, TranslationBehavior::Ask); |
| 256 | assert_eq!(settings.never_translate_codes(), vec!["de", "en"]); |
| 257 | assert_eq!( |
| 258 | settings.preferences["untranslatedLanguages"], |
| 259 | json!(["de", "en"]) |
| 260 | ); |
| 261 | } |
| 262 | |
| 263 | #[test] |
| 264 | fn a_stored_copy_parses_back_to_the_same_settings() { |
| 265 | let settings = parse_language_settings(&account()).unwrap(); |
| 266 | assert_eq!( |
| 267 | parse_language_settings(&settings.to_account_value()).unwrap(), |
| 268 | settings |
| 269 | ); |
| 270 | let empty = LanguageSettings::default(); |
| 271 | assert_eq!( |
| 272 | parse_language_settings(&empty.to_account_value()).unwrap(), |
| 273 | empty |
| 274 | ); |
| 275 | } |
| 276 | |
| 277 | #[test] |
| 278 | fn missing_fields_fall_back_to_ask_and_empty_lists() { |
| 279 | let settings = |
| 280 | parse_language_settings(&json!({"userLanguageAccountSettings": {"value": {}}})) |
| 281 | .unwrap(); |
| 282 | assert_eq!(settings, LanguageSettings::default()); |
| 283 | assert!(parse_language_settings(&json!({})).is_err()); |
| 284 | } |
| 285 | |
| 286 | #[test] |
| 287 | fn behavior_codes_follow_the_account_values() { |
| 288 | assert_eq!( |
| 289 | TranslationBehavior::from_code("Yes"), |
| 290 | TranslationBehavior::Auto |
| 291 | ); |
| 292 | assert_eq!( |
| 293 | TranslationBehavior::from_code("No"), |
| 294 | TranslationBehavior::Never |
| 295 | ); |
| 296 | assert_eq!( |
| 297 | TranslationBehavior::from_code("Ask"), |
| 298 | TranslationBehavior::Ask |
| 299 | ); |
| 300 | assert_eq!( |
| 301 | TranslationBehavior::from_code("?"), |
| 302 | TranslationBehavior::Ask |
| 303 | ); |
| 304 | assert_eq!(TranslationBehavior::Auto.code(), "Yes"); |
| 305 | } |
| 306 | |
| 307 | #[test] |
| 308 | fn behavior_patch_keeps_the_other_preferences() { |
| 309 | let settings = parse_language_settings(&account()).unwrap(); |
| 310 | assert_eq!( |
| 311 | behavior_patch(&settings, TranslationBehavior::Auto), |
| 312 | json!({"translationPreferences": { |
| 313 | "translationBehavior": "Yes", |
| 314 | "untranslatedLanguages": ["de", "en"], |
| 315 | "languageOverrides": [] |
| 316 | }}) |
| 317 | ); |
| 318 | } |
| 319 | |
| 320 | #[test] |
| 321 | fn target_and_authoring_patches_carry_only_their_part() { |
| 322 | assert_eq!( |
| 323 | target_patch("fr"), |
| 324 | json!({"defaultTranslationLanguage": {"locale": "fr"}}) |
| 325 | ); |
| 326 | assert_eq!( |
| 327 | authoring_patch(&["de-DE".into(), "fr".into()]), |
| 328 | json!({"authoringLanguages": [{"locale": "de-DE"}, {"locale": "fr"}]}) |
| 329 | ); |
| 330 | } |
| 331 | |
| 332 | #[test] |
| 333 | fn adding_and_removing_a_never_language_works_on_codes() { |
| 334 | let settings = parse_language_settings(&account()).unwrap(); |
| 335 | assert_eq!( |
| 336 | settings.with_never_translate("fr"), |
| 337 | vec!["de-DE", "en-DE", "en-US", "fr"] |
| 338 | ); |
| 339 | assert_eq!( |
| 340 | settings.with_never_translate("de"), |
| 341 | vec!["de-DE", "en-DE", "en-US"] |
| 342 | ); |
| 343 | assert_eq!(settings.without_never_translate("en"), vec!["de-DE"]); |
| 344 | } |
| 345 | |
| 346 | #[tokio::test] |
| 347 | async fn read_and_patch_use_the_mt_routes_with_the_client_headers() { |
| 348 | let transport = Canned { |
| 349 | answers: Mutex::new(vec![(200, account()), (200, Value::Null)].into()), |
| 350 | requests: Mutex::new(Vec::new()), |
| 351 | }; |
| 352 | let client = LanguageSettingsClient::with_transport(&transport, "emea"); |
| 353 | let settings = client.read().await.unwrap(); |
| 354 | client |
| 355 | .patch(behavior_patch(&settings, TranslationBehavior::Never)) |
| 356 | .await |
| 357 | .unwrap(); |
| 358 | let requests = transport.requests.lock().unwrap(); |
| 359 | let base = "https://teams.cloud.microsoft/api/mt/emea/beta/users"; |
| 360 | assert_eq!(requests[0].method, Method::Post); |
| 361 | assert_eq!(requests[0].url, format!("{base}/useraggregatesettings")); |
| 362 | assert_eq!( |
| 363 | requests[0].body, |
| 364 | Some(json!({"userLanguageAccountSettings": true})) |
| 365 | ); |
| 366 | assert_eq!(requests[1].method, Method::Patch); |
| 367 | assert_eq!(requests[1].url, format!("{base}/languageAccountSettings")); |
| 368 | let names: Vec<&str> = requests[1] |
| 369 | .headers |
| 370 | .iter() |
| 371 | .map(|(name, _)| name.as_str()) |
| 372 | .collect(); |
| 373 | assert_eq!(names, ["x-ms-client-type", "x-ms-client-version", "Accept"]); |
| 374 | assert_eq!( |
| 375 | requests[1].body.as_ref().unwrap()["translationPreferences"]["translationBehavior"], |
| 376 | json!("No") |
| 377 | ); |
| 378 | } |
| 379 | |
| 380 | #[tokio::test] |
| 381 | async fn an_empty_answer_is_not_settings() { |
| 382 | let transport = Canned { |
| 383 | answers: Mutex::new(vec![(204, Value::Null)].into()), |
| 384 | requests: Mutex::new(Vec::new()), |
| 385 | }; |
| 386 | let outcome = LanguageSettingsClient::with_transport(&transport, "emea") |
| 387 | .read() |
| 388 | .await; |
| 389 | assert!(outcome.is_err()); |
| 390 | } |
| 391 | } |