BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / language_settings.rs

language_settings.rs

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