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