BlueGit

ict rusty-teams

Files

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

settings.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
settings.rs 18.4 KiB Download Raw
1use serde_json::{Map, Value};
2use session::{Method, Request, Session};
3
4use crate::error::{Error, Result};
5use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};
6use crate::pins::DEFAULT_REGION;
7
8const SETTINGS_KEY: &str = "simpleCollabUserSettings";
9const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
10const TEAMS_ORDER_KEY: &str = "teamsOrder";
11const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12const DEFAULT_REACTIONS_KEY: &str = "defaultMessageReactions";
13const APP_HORIZON_KEY: &str = "appConsumptionHorizon";
14const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];
15const MAX_SKIN_TONE: u8 = 5;
16const MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
17const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
18const ADAPTIVE_RAIL_FIELD: &str = "hasUserEnabledAdaptiveRailForDesktop";
19const MUTED_DEFAULT: bool = false;
20const MEETING_DEFAULT: bool = false;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum ChatSection {
24 Muted,
25 Meeting,
26}
27
28impl ChatSection {
29 fn field(self) -> &'static str {
30 match self {
31 ChatSection::Muted => MUTED_FIELD,
32 ChatSection::Meeting => MEETING_FIELD,
33 }
34 }
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub struct ChatSectionSettings {
39 pub muted: Option<bool>,
40 pub meeting: Option<bool>,
41 pub adaptive_rail: Option<bool>,
42}
43
44impl ChatSectionSettings {
45 pub fn enabled(&self, section: ChatSection) -> bool {
46 match section {
47 ChatSection::Muted => self.muted.unwrap_or(MUTED_DEFAULT),
48 ChatSection::Meeting => self.meeting.unwrap_or(MEETING_DEFAULT),
49 }
50 }
51
52 pub fn adaptive_rail(&self) -> bool {
53 self.adaptive_rail.unwrap_or(false)
54 }
55
56 pub fn set(&mut self, section: ChatSection, enabled: bool) {
57 match section {
58 ChatSection::Muted => self.muted = Some(enabled),
59 ChatSection::Meeting => self.meeting = Some(enabled),
60 }
61 }
62}
63
64pub struct UserSettings<T: MessageTransport = SessionMessageTransport> {
65 transport: T,
66 base_url: String,
67}
68
69impl UserSettings<SessionMessageTransport> {
70 pub fn new(session: &Session) -> Self {
71 Self::with_region(session, DEFAULT_REGION)
72 }
73
74 pub fn with_region(session: &Session, region: &str) -> Self {
75 UserSettings::with_transport(SessionMessageTransport::new(session), region)
76 }
77}
78
79impl<T: MessageTransport> UserSettings<T> {
80 pub fn with_transport(transport: T, region: &str) -> Self {
81 UserSettings {
82 transport,
83 base_url: format!(
84 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/properties"
85 ),
86 }
87 }
88
89 pub async fn chat_sections(&self) -> Result<ChatSectionSettings> {
90 Ok(parse_chat_sections(&self.properties().await?))
91 }
92
93 pub async fn set_chat_section(&self, section: ChatSection, enabled: bool) -> Result<()> {
94 let properties = self.properties().await?;
95 let merged = merge_chat_section(&properties, section, enabled);
96 self.set_property(SETTINGS_KEY, Value::String(merged)).await
97 }
98
99 pub async fn set_skin_tone(&self, tone: u8) -> Result<()> {
100 self.set_property(SKIN_TONE_KEY, Value::String(tone.to_string()))
101 .await
102 }
103
104 pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {
105 self.set_property(DEFAULT_REACTIONS_KEY, default_reactions_value(reaction_ids))
106 .await
107 }
108
109 /// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.
110 pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
111 let properties = self.properties().await?;
112 let horizon = AppConsumptionHorizon {
113 channel_ms: now_ms,
114 ..parse_app_consumption_horizon(&properties)
115 };
116 self.set_property(APP_HORIZON_KEY, Value::String(horizon.property_value()))
117 .await?;
118 Ok(horizon)
119 }
120
121 pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {
122 let url = format!("{}?name={name}", self.base_url);
123 let mut body = Map::new();
124 body.insert(name.to_owned(), value);
125 let answer = self
126 .transport
127 .send(Request::with_body(Method::Put, url, Value::Object(body)))
128 .await?;
129 ensure_success(&answer)
130 }
131
132 pub async fn properties(&self) -> Result<Value> {
133 let answer = self.transport.send(Request::get(&self.base_url)).await?;
134 ensure_success(&answer)?;
135 if answer.body.is_object() {
136 Ok(answer.body)
137 } else {
138 Err(Error::UnexpectedAnswer("no user properties".into()))
139 }
140 }
141}
142
143fn stored_settings(properties: &Value) -> Map<String, Value> {
144 properties
145 .get(SETTINGS_KEY)
146 .and_then(Value::as_str)
147 .and_then(|text| serde_json::from_str::<Value>(text).ok())
148 .and_then(|value| value.as_object().cloned())
149 .unwrap_or_default()
150}
151
152pub fn parse_chat_sections(properties: &Value) -> ChatSectionSettings {
153 let settings = stored_settings(properties);
154 ChatSectionSettings {
155 muted: settings.get(MUTED_FIELD).and_then(Value::as_bool),
156 meeting: settings.get(MEETING_FIELD).and_then(Value::as_bool),
157 adaptive_rail: settings.get(ADAPTIVE_RAIL_FIELD).and_then(Value::as_bool),
158 }
159}
160
161pub fn parse_skin_tone(properties: &Value) -> Option<u8> {
162 let value = properties.get(SKIN_TONE_KEY)?;
163 let tone = match value {
164 Value::String(text) => text.parse().ok()?,
165 other => u8::try_from(other.as_u64()?).ok()?,
166 };
167 (tone <= MAX_SKIN_TONE).then_some(tone)
168}
169
170pub fn parse_default_reactions(properties: &Value) -> Option<Vec<String>> {
171 let entries = match properties.get(DEFAULT_REACTIONS_KEY)? {
172 Value::String(text) => serde_json::from_str::<Value>(text).ok()?,
173 other => other.clone(),
174 };
175 entries.as_array().map(|entries| {
176 entries
177 .iter()
178 .filter_map(Value::as_str)
179 .filter(|reaction_id| !reaction_id.is_empty())
180 .map(str::to_owned)
181 .collect()
182 })
183}
184
185pub fn default_reactions_value(reaction_ids: &[String]) -> Value {
186 Value::String(Value::from(reaction_ids.to_vec()).to_string())
187}
188
189pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
190 let entries = match properties.get(TEAMS_ORDER_KEY) {
191 Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
192 Some(other) => Some(other.clone()),
193 None => None,
194 };
195 let mut order: Vec<(String, i64)> = entries
196 .as_ref()
197 .and_then(Value::as_array)
198 .map(|entries| {
199 entries
200 .iter()
201 .filter_map(|entry| {
202 let team_id = entry.get("teamId")?.as_str()?.to_owned();
203 let position = entry.get("order")?;
204 let position = position
205 .as_i64()
206 .or_else(|| position.as_f64().map(|float| float as i64))
207 .or_else(|| position.as_str()?.parse().ok())?;
208 Some((team_id, position))
209 })
210 .collect()
211 })
212 .unwrap_or_default();
213 order.sort_by_key(|(_, position)| *position);
214 order
215}
216
217/// Per app "read everything before" times in ms; Teams treats a conversation of that app as read up to it.
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
219pub struct AppConsumptionHorizon {
220 pub chat_ms: i64,
221 pub channel_ms: i64,
222 pub engage_community_ms: i64,
223}
224
225impl AppConsumptionHorizon {
226 pub fn property_value(&self) -> String {
227 let values = [self.chat_ms, self.channel_ms, self.engage_community_ms];
228 let mut fields = Map::new();
229 for (app, value) in APP_HORIZON_APPS.iter().zip(values) {
230 fields.insert((*app).to_owned(), Value::from(value));
231 }
232 Value::Object(fields).to_string()
233 }
234}
235
236pub fn parse_app_consumption_horizon(properties: &Value) -> AppConsumptionHorizon {
237 let parsed = match properties.get(APP_HORIZON_KEY) {
238 Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
239 Some(other) => Some(other.clone()),
240 None => None,
241 };
242 let Some(fields) = parsed.as_ref().and_then(Value::as_object) else {
243 return AppConsumptionHorizon::default();
244 };
245 let valid = (fields.contains_key("chat") || fields.contains_key("channel"))
246 && fields
247 .values()
248 .all(|value| value.as_f64().is_some_and(|number| number >= 0.0));
249 if !valid {
250 return AppConsumptionHorizon::default();
251 }
252 let read = |app: &str| {
253 fields
254 .get(app)
255 .and_then(Value::as_f64)
256 .map_or(0, |number| number as i64)
257 };
258 AppConsumptionHorizon {
259 chat_ms: read("chat"),
260 channel_ms: read("channel"),
261 engage_community_ms: read("engage_community"),
262 }
263}
264
265pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {
266 let mut settings = stored_settings(properties);
267 settings
268 .entry("id")
269 .or_insert_with(|| Value::String(SETTINGS_ID.to_owned()));
270 settings.insert(section.field().to_owned(), Value::Bool(enabled));
271 Value::Object(settings).to_string()
272}
273
274#[cfg(test)]
275mod tests {
276 use std::collections::VecDeque;
277 use std::sync::Mutex;
278
279 use serde_json::json;
280 use session::ApiResponse;
281
282 use super::*;
283
284 struct Canned {
285 answers: Mutex<VecDeque<(u16, Value)>>,
286 requests: Mutex<Vec<Request>>,
287 }
288
289 impl MessageTransport for &Canned {
290 async fn send(&self, request: Request) -> Result<ApiResponse> {
291 self.requests.lock().unwrap().push(request);
292 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
293 Ok(ApiResponse {
294 status,
295 body,
296 retry_after: None,
297 })
298 }
299 }
300
301 fn properties(settings: &str) -> Value {
302 json!({"other": "kept", SETTINGS_KEY: settings})
303 }
304
305 #[test]
306 fn skin_tone_is_read_from_the_string_property() {
307 assert_eq!(
308 parse_skin_tone(&json!({"preferredSkinToneIndex": "2"})),
309 Some(2)
310 );
311 assert_eq!(
312 parse_skin_tone(&json!({"preferredSkinToneIndex": "9"})),
313 None
314 );
315 assert_eq!(parse_skin_tone(&json!({})), None);
316 }
317
318 #[test]
319 fn default_reactions_are_read_from_the_json_string_or_an_array() {
320 assert_eq!(
321 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: r#"["like","heart","fire"]"#})),
322 Some(vec![
323 "like".to_owned(),
324 "heart".to_owned(),
325 "fire".to_owned()
326 ])
327 );
328 assert_eq!(
329 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: ["yes", "", 3]})),
330 Some(vec!["yes".to_owned()])
331 );
332 assert_eq!(
333 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "[]"})),
334 Some(Vec::new())
335 );
336 assert_eq!(parse_default_reactions(&json!({})), None);
337 assert_eq!(
338 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "not json"})),
339 None
340 );
341 }
342
343 #[tokio::test]
344 async fn default_reactions_are_put_as_a_json_string() {
345 let transport = Canned {
346 answers: Mutex::new(vec![(200, Value::Null)].into()),
347 requests: Mutex::new(Vec::new()),
348 };
349 UserSettings::with_transport(&transport, "emea")
350 .set_default_reactions(&["like".to_owned(), "fire".to_owned()])
351 .await
352 .unwrap();
353 let requests = transport.requests.lock().unwrap();
354 assert_eq!(requests[0].method, Method::Put);
355 assert_eq!(
356 requests[0].url,
357 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=defaultMessageReactions"
358 );
359 assert_eq!(
360 requests[0].body,
361 Some(json!({"defaultMessageReactions": r#"["like","fire"]"#}))
362 );
363 }
364
365 #[test]
366 fn unset_fields_use_the_teams_defaults() {
367 let parsed = parse_chat_sections(&json!({}));
368 assert_eq!(parsed, ChatSectionSettings::default());
369 assert!(!parsed.enabled(ChatSection::Muted));
370 assert!(!parsed.enabled(ChatSection::Meeting));
371 assert!(!parsed.adaptive_rail());
372 }
373
374 #[test]
375 fn reads_every_flag_from_the_json_string() {
376 let parsed = parse_chat_sections(&properties(
377 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true,"hasUserEnabledAdaptiveRailForDesktop":true}"#,
378 ));
379 assert!(!parsed.enabled(ChatSection::Muted));
380 assert!(parsed.enabled(ChatSection::Meeting));
381 assert!(parsed.adaptive_rail());
382 }
383
384 #[test]
385 fn teams_order_is_read_from_the_json_string_sorted_by_order() {
386 let parsed = parse_teams_order(&json!({
387 TEAMS_ORDER_KEY: r#"[{"teamId":"19:b","order":1},{"teamId":"19:a","order":"0"},{"teamId":"19:c"},{"order":2},{"teamId":"19:d","order":2.0}]"#,
388 }));
389 assert_eq!(
390 parsed,
391 vec![
392 ("19:a".to_owned(), 0),
393 ("19:b".to_owned(), 1),
394 ("19:d".to_owned(), 2)
395 ]
396 );
397 }
398
399 #[test]
400 fn teams_order_is_empty_when_missing_or_malformed() {
401 assert!(parse_teams_order(&json!({})).is_empty());
402 assert!(parse_teams_order(&json!({TEAMS_ORDER_KEY: "not json"})).is_empty());
403 assert!(parse_teams_order(&json!({TEAMS_ORDER_KEY: "{}"})).is_empty());
404 }
405
406 #[test]
407 fn merge_keeps_every_unknown_field_and_the_other_flag() {
408 let existing = properties(
409 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMeetingChatSection":true,"futureSetting":{"nested":[1,2]},"count":3}"#,
410 );
411 let merged = merge_chat_section(&existing, ChatSection::Muted, false);
412 let value: Value = serde_json::from_str(&merged).unwrap();
413 assert_eq!(
414 value,
415 json!({
416 "id": "simpleCollabUserSettingsId",
417 "hasUserEnabledMeetingChatSection": true,
418 "hasUserEnabledMutedChatSection": false,
419 "futureSetting": {"nested": [1, 2]},
420 "count": 3,
421 })
422 );
423 assert_eq!(
424 parse_chat_sections(&json!({SETTINGS_KEY: merged})),
425 ChatSectionSettings {
426 muted: Some(false),
427 meeting: Some(true),
428 adaptive_rail: None,
429 }
430 );
431 }
432
433 #[test]
434 fn merge_without_stored_settings_creates_the_object_with_its_id() {
435 let merged = merge_chat_section(&json!({}), ChatSection::Meeting, true);
436 let value: Value = serde_json::from_str(&merged).unwrap();
437 assert_eq!(
438 value,
439 json!({"id": SETTINGS_ID, "hasUserEnabledMeetingChatSection": true})
440 );
441 }
442
443 #[tokio::test]
444 async fn setting_a_section_reads_then_puts_the_merged_object_as_text() {
445 let transport = Canned {
446 answers: Mutex::new(
447 vec![(200, properties(r#"{"keep":1}"#)), (200, Value::Null)].into(),
448 ),
449 requests: Mutex::new(Vec::new()),
450 };
451 UserSettings::with_transport(&transport, "emea")
452 .set_chat_section(ChatSection::Muted, false)
453 .await
454 .unwrap();
455 let requests = transport.requests.lock().unwrap();
456 let base = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties";
457 assert_eq!(requests[0].method, Method::Get);
458 assert_eq!(requests[0].url, base);
459 assert_eq!(requests[1].method, Method::Put);
460 assert_eq!(
461 requests[1].url,
462 format!("{base}?name=simpleCollabUserSettings")
463 );
464 let sent = requests[1].body.as_ref().unwrap()["simpleCollabUserSettings"]
465 .as_str()
466 .unwrap();
467 let value: Value = serde_json::from_str(sent).unwrap();
468 assert_eq!(value["keep"], json!(1));
469 assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));
470 }
471
472 #[test]
473 fn app_horizon_reads_the_string_and_ignores_invalid_values() {
474 let parsed = parse_app_consumption_horizon(&json!({
475 "appConsumptionHorizon": "{\"chat\":1791368000000,\"channel\":1791369000000,\"engage_community\":0}"
476 }));
477 assert_eq!(
478 parsed,
479 AppConsumptionHorizon {
480 chat_ms: 1791368000000,
481 channel_ms: 1791369000000,
482 engage_community_ms: 0,
483 }
484 );
485 let object =
486 parse_app_consumption_horizon(&json!({"appConsumptionHorizon": {"channel": 5}}));
487 assert_eq!(object.channel_ms, 5);
488 for broken in [
489 json!({}),
490 json!({"appConsumptionHorizon": "not json"}),
491 json!({"appConsumptionHorizon": "{\"engage_community\":5}"}),
492 json!({"appConsumptionHorizon": "{\"channel\":-1}"}),
493 json!({"appConsumptionHorizon": "{\"channel\":\"5\"}"}),
494 ] {
495 assert_eq!(
496 parse_app_consumption_horizon(&broken),
497 AppConsumptionHorizon::default()
498 );
499 }
500 }
501
502 #[tokio::test]
503 async fn mark_all_channels_read_moves_only_the_channel_entry() {
504 let stored = json!({
505 "appConsumptionHorizon": "{\"chat\":100,\"channel\":200,\"engage_community\":300}"
506 });
507 let transport = Canned {
508 answers: Mutex::new(vec![(200, stored), (200, Value::Null)].into()),
509 requests: Mutex::new(Vec::new()),
510 };
511 let horizon = UserSettings::with_transport(&transport, "emea")
512 .mark_all_channels_read(1791368000000)
513 .await
514 .unwrap();
515 assert_eq!(horizon.channel_ms, 1791368000000);
516 let requests = transport.requests.lock().unwrap();
517 assert_eq!(requests[1].method, Method::Put);
518 assert_eq!(
519 requests[1].url,
520 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=appConsumptionHorizon"
521 );
522 let sent = requests[1].body.as_ref().unwrap()["appConsumptionHorizon"]
523 .as_str()
524 .unwrap();
525 let value: Value = serde_json::from_str(sent).unwrap();
526 assert_eq!(
527 value,
528 json!({"chat": 100, "channel": 1791368000000_i64, "engage_community": 300})
529 );
530 }
531}