BlueGit

ict rusty-teams

Files

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

settings.rs

fix(sidebar): review findings
metis Daniel Däschle · pushed by metis · 7 weeks ago
6d166892 History
settings.rs 9.8 KiB Download Raw
1use serde_json::{Map, Value, json};
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 MUTED_FIELD: &str = "hasUserEnabledMutedChatSection";
12const MEETING_FIELD: &str = "hasUserEnabledMeetingChatSection";
13const MUTED_DEFAULT: bool = true;
14const MEETING_DEFAULT: bool = false;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum ChatSection {
18 Muted,
19 Meeting,
20}
21
22impl ChatSection {
23 fn field(self) -> &'static str {
24 match self {
25 ChatSection::Muted => MUTED_FIELD,
26 ChatSection::Meeting => MEETING_FIELD,
27 }
28 }
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub struct ChatSectionSettings {
33 pub muted: Option<bool>,
34 pub meeting: Option<bool>,
35}
36
37impl ChatSectionSettings {
38 pub fn enabled(&self, section: ChatSection) -> bool {
39 match section {
40 ChatSection::Muted => self.muted.unwrap_or(MUTED_DEFAULT),
41 ChatSection::Meeting => self.meeting.unwrap_or(MEETING_DEFAULT),
42 }
43 }
44
45 pub fn set(&mut self, section: ChatSection, enabled: bool) {
46 match section {
47 ChatSection::Muted => self.muted = Some(enabled),
48 ChatSection::Meeting => self.meeting = Some(enabled),
49 }
50 }
51}
52
53pub struct UserSettings<T: MessageTransport = SessionMessageTransport> {
54 transport: T,
55 base_url: String,
56}
57
58impl UserSettings<SessionMessageTransport> {
59 pub fn new(session: &Session) -> Self {
60 Self::with_region(session, DEFAULT_REGION)
61 }
62
63 pub fn with_region(session: &Session, region: &str) -> Self {
64 UserSettings::with_transport(SessionMessageTransport::new(session), region)
65 }
66}
67
68impl<T: MessageTransport> UserSettings<T> {
69 pub fn with_transport(transport: T, region: &str) -> Self {
70 UserSettings {
71 transport,
72 base_url: format!(
73 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/properties"
74 ),
75 }
76 }
77
78 pub async fn chat_sections(&self) -> Result<ChatSectionSettings> {
79 Ok(parse_chat_sections(&self.properties().await?))
80 }
81
82 pub async fn set_chat_section(&self, section: ChatSection, enabled: bool) -> Result<()> {
83 let properties = self.properties().await?;
84 let merged = merge_chat_section(&properties, section, enabled);
85 let url = format!("{}?name={SETTINGS_KEY}", self.base_url);
86 let body = json!({ SETTINGS_KEY: merged });
87 let answer = self
88 .transport
89 .send(Request::with_body(Method::Put, url, body))
90 .await?;
91 ensure_success(&answer)
92 }
93
94 pub async fn properties(&self) -> Result<Value> {
95 let answer = self.transport.send(Request::get(&self.base_url)).await?;
96 ensure_success(&answer)?;
97 if answer.body.is_object() {
98 Ok(answer.body)
99 } else {
100 Err(Error::UnexpectedAnswer("no user properties".into()))
101 }
102 }
103}
104
105fn stored_settings(properties: &Value) -> Map<String, Value> {
106 properties
107 .get(SETTINGS_KEY)
108 .and_then(Value::as_str)
109 .and_then(|text| serde_json::from_str::<Value>(text).ok())
110 .and_then(|value| value.as_object().cloned())
111 .unwrap_or_default()
112}
113
114pub fn parse_chat_sections(properties: &Value) -> ChatSectionSettings {
115 let settings = stored_settings(properties);
116 ChatSectionSettings {
117 muted: settings.get(MUTED_FIELD).and_then(Value::as_bool),
118 meeting: settings.get(MEETING_FIELD).and_then(Value::as_bool),
119 }
120}
121
122pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
123 let entries = match properties.get(TEAMS_ORDER_KEY) {
124 Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
125 Some(other) => Some(other.clone()),
126 None => None,
127 };
128 let mut order: Vec<(String, i64)> = entries
129 .as_ref()
130 .and_then(Value::as_array)
131 .map(|entries| {
132 entries
133 .iter()
134 .filter_map(|entry| {
135 let team_id = entry.get("teamId")?.as_str()?.to_owned();
136 let position = entry.get("order")?;
137 let position = position
138 .as_i64()
139 .or_else(|| position.as_f64().map(|float| float as i64))
140 .or_else(|| position.as_str()?.parse().ok())?;
141 Some((team_id, position))
142 })
143 .collect()
144 })
145 .unwrap_or_default();
146 order.sort_by_key(|(_, position)| *position);
147 order
148}
149
150pub fn merge_chat_section(properties: &Value, section: ChatSection, enabled: bool) -> String {
151 let mut settings = stored_settings(properties);
152 settings
153 .entry("id")
154 .or_insert_with(|| Value::String(SETTINGS_ID.to_owned()));
155 settings.insert(section.field().to_owned(), Value::Bool(enabled));
156 Value::Object(settings).to_string()
157}
158
159#[cfg(test)]
160mod tests {
161 use std::collections::VecDeque;
162 use std::sync::Mutex;
163
164 use session::ApiResponse;
165
166 use super::*;
167
168 struct Canned {
169 answers: Mutex<VecDeque<(u16, Value)>>,
170 requests: Mutex<Vec<Request>>,
171 }
172
173 impl MessageTransport for &Canned {
174 async fn send(&self, request: Request) -> Result<ApiResponse> {
175 self.requests.lock().unwrap().push(request);
176 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
177 Ok(ApiResponse {
178 status,
179 body,
180 retry_after: None,
181 })
182 }
183 }
184
185 fn properties(settings: &str) -> Value {
186 json!({"other": "kept", SETTINGS_KEY: settings})
187 }
188
189 #[test]
190 fn unset_fields_use_the_teams_defaults() {
191 let parsed = parse_chat_sections(&json!({}));
192 assert_eq!(parsed, ChatSectionSettings::default());
193 assert!(parsed.enabled(ChatSection::Muted));
194 assert!(!parsed.enabled(ChatSection::Meeting));
195 }
196
197 #[test]
198 fn reads_both_flags_from_the_json_string() {
199 let parsed = parse_chat_sections(&properties(
200 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMutedChatSection":false,"hasUserEnabledMeetingChatSection":true}"#,
201 ));
202 assert!(!parsed.enabled(ChatSection::Muted));
203 assert!(parsed.enabled(ChatSection::Meeting));
204 }
205
206 #[test]
207 fn teams_order_is_read_from_the_json_string_sorted_by_order() {
208 let parsed = parse_teams_order(&json!({
209 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}]"#,
210 }));
211 assert_eq!(
212 parsed,
213 vec![
214 ("19:a".to_owned(), 0),
215 ("19:b".to_owned(), 1),
216 ("19:d".to_owned(), 2)
217 ]
218 );
219 }
220
221 #[test]
222 fn teams_order_is_empty_when_missing_or_malformed() {
223 assert!(parse_teams_order(&json!({})).is_empty());
224 assert!(parse_teams_order(&json!({TEAMS_ORDER_KEY: "not json"})).is_empty());
225 assert!(parse_teams_order(&json!({TEAMS_ORDER_KEY: "{}"})).is_empty());
226 }
227
228 #[test]
229 fn merge_keeps_every_unknown_field_and_the_other_flag() {
230 let existing = properties(
231 r#"{"id":"simpleCollabUserSettingsId","hasUserEnabledMeetingChatSection":true,"futureSetting":{"nested":[1,2]},"count":3}"#,
232 );
233 let merged = merge_chat_section(&existing, ChatSection::Muted, false);
234 let value: Value = serde_json::from_str(&merged).unwrap();
235 assert_eq!(
236 value,
237 json!({
238 "id": "simpleCollabUserSettingsId",
239 "hasUserEnabledMeetingChatSection": true,
240 "hasUserEnabledMutedChatSection": false,
241 "futureSetting": {"nested": [1, 2]},
242 "count": 3,
243 })
244 );
245 assert_eq!(
246 parse_chat_sections(&json!({SETTINGS_KEY: merged})),
247 ChatSectionSettings {
248 muted: Some(false),
249 meeting: Some(true)
250 }
251 );
252 }
253
254 #[test]
255 fn merge_without_stored_settings_creates_the_object_with_its_id() {
256 let merged = merge_chat_section(&json!({}), ChatSection::Meeting, true);
257 let value: Value = serde_json::from_str(&merged).unwrap();
258 assert_eq!(
259 value,
260 json!({"id": SETTINGS_ID, "hasUserEnabledMeetingChatSection": true})
261 );
262 }
263
264 #[tokio::test]
265 async fn setting_a_section_reads_then_puts_the_merged_object_as_text() {
266 let transport = Canned {
267 answers: Mutex::new(
268 vec![(200, properties(r#"{"keep":1}"#)), (200, Value::Null)].into(),
269 ),
270 requests: Mutex::new(Vec::new()),
271 };
272 UserSettings::with_transport(&transport, "emea")
273 .set_chat_section(ChatSection::Muted, false)
274 .await
275 .unwrap();
276 let requests = transport.requests.lock().unwrap();
277 let base = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties";
278 assert_eq!(requests[0].method, Method::Get);
279 assert_eq!(requests[0].url, base);
280 assert_eq!(requests[1].method, Method::Put);
281 assert_eq!(
282 requests[1].url,
283 format!("{base}?name=simpleCollabUserSettings")
284 );
285 let sent = requests[1].body.as_ref().unwrap()["simpleCollabUserSettings"]
286 .as_str()
287 .unwrap();
288 let value: Value = serde_json::from_str(sent).unwrap();
289 assert_eq!(value["keep"], json!(1));
290 assert_eq!(value["hasUserEnabledMutedChatSection"], json!(false));
291 }
292}