BlueGit

ict rusty-teams

Files

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

settings.rs

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