BlueGit

ict rusty-teams

Files

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

settings.rs

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