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