| 1 | use serde_json::{Map, Value, json}; |
| 2 | use session::Session; |
| 3 | |
| 4 | use crate::error::Result; |
| 5 | use crate::messages::{MessageTransport, SessionMessageTransport}; |
| 6 | use crate::settings::UserSettings; |
| 7 | |
| 8 | const READ_RECEIPTS_KEY: &str = "readReceiptsEnabled"; |
| 9 | const MESSAGE_DENSITY_KEY: &str = "messageDensity"; |
| 10 | const COMPOSE_SETTINGS_KEY: &str = "composeUserSettings"; |
| 11 | const PERSONAL_SETTINGS_KEY: &str = "userPersonalSettings"; |
| 12 | const ENTER_KEY_FIELD: &str = "enterKeyBehavior"; |
| 13 | const MESSAGING_SETTINGS: &str = "messagingSettings"; |
| 14 | const UP_ARROW_FIELD: &str = "upArrowKeyBehavior"; |
| 15 | const TOAST_SETTINGS: &str = "toastSettings"; |
| 16 | const ACTIVITY_SETTINGS: &str = "activityGenerationSettings"; |
| 17 | const EMAIL_SETTINGS: &str = "emailSettings"; |
| 18 | const CHAT_SETTINGS: &str = "chatSettings"; |
| 19 | const SELECTED_PRESET_FIELD: &str = "selectedPreset"; |
| 20 | const MEETING_CHAT_FIELD: &str = "meetingChatNotification"; |
| 21 | const SHOW_PREVIEW_FIELD: &str = "ShowPreviewInToasts"; |
| 22 | const CHAT_MESSAGES_FIELD: &str = "Chat"; |
| 23 | const PERSONAL_MENTIONS_FIELD: &str = "MentionInChat_Person_v2"; |
| 24 | const EVERYONE_MENTIONS_FIELD: &str = "MentionInChat_Everyone"; |
| 25 | const LIKES_FIELD: &str = "LikeInChat_v2"; |
| 26 | const ACCOUNT_KEYS: [&str; 4] = [ |
| 27 | READ_RECEIPTS_KEY, |
| 28 | MESSAGE_DENSITY_KEY, |
| 29 | COMPOSE_SETTINGS_KEY, |
| 30 | PERSONAL_SETTINGS_KEY, |
| 31 | ]; |
| 32 | |
| 33 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 34 | pub enum MessageDensity { |
| 35 | #[default] |
| 36 | Comfy, |
| 37 | Compact, |
| 38 | } |
| 39 | |
| 40 | impl MessageDensity { |
| 41 | pub const ALL: [MessageDensity; 2] = [MessageDensity::Comfy, MessageDensity::Compact]; |
| 42 | |
| 43 | pub fn property_value(self) -> &'static str { |
| 44 | match self { |
| 45 | MessageDensity::Comfy => "COMFY", |
| 46 | MessageDensity::Compact => "COMPACT", |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | fn from_property(value: &str) -> Option<Self> { |
| 51 | MessageDensity::ALL |
| 52 | .into_iter() |
| 53 | .find(|density| density.property_value() == value) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 58 | pub enum EnterKeyBehavior { |
| 59 | #[default] |
| 60 | Send, |
| 61 | NewLine, |
| 62 | } |
| 63 | |
| 64 | impl EnterKeyBehavior { |
| 65 | pub const ALL: [EnterKeyBehavior; 2] = [EnterKeyBehavior::Send, EnterKeyBehavior::NewLine]; |
| 66 | |
| 67 | pub fn property_value(self) -> &'static str { |
| 68 | match self { |
| 69 | EnterKeyBehavior::Send => "Default", |
| 70 | EnterKeyBehavior::NewLine => "CreateNewLine", |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | fn from_property(value: &str) -> Option<Self> { |
| 75 | EnterKeyBehavior::ALL |
| 76 | .into_iter() |
| 77 | .find(|behavior| behavior.property_value() == value) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 82 | pub enum UpArrowBehavior { |
| 83 | NavigateToMessages, |
| 84 | #[default] |
| 85 | EditLastMessage, |
| 86 | StayInCompose, |
| 87 | } |
| 88 | |
| 89 | impl UpArrowBehavior { |
| 90 | pub const ALL: [UpArrowBehavior; 3] = [ |
| 91 | UpArrowBehavior::NavigateToMessages, |
| 92 | UpArrowBehavior::EditLastMessage, |
| 93 | UpArrowBehavior::StayInCompose, |
| 94 | ]; |
| 95 | |
| 96 | pub fn property_value(self) -> &'static str { |
| 97 | match self { |
| 98 | UpArrowBehavior::NavigateToMessages => "NAVIGATE_TO_MESSAGES", |
| 99 | UpArrowBehavior::EditLastMessage => "EDIT_LAST_MESSAGE", |
| 100 | UpArrowBehavior::StayInCompose => "STAY_IN_COMPOSE", |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | fn from_property(value: &str) -> Option<Self> { |
| 105 | UpArrowBehavior::ALL |
| 106 | .into_iter() |
| 107 | .find(|behavior| behavior.property_value() == value) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 112 | pub enum NotificationPreset { |
| 113 | AllActivity, |
| 114 | MentionsAndReplies, |
| 115 | #[default] |
| 116 | Customised, |
| 117 | } |
| 118 | |
| 119 | impl NotificationPreset { |
| 120 | pub const ALL: [NotificationPreset; 3] = [ |
| 121 | NotificationPreset::AllActivity, |
| 122 | NotificationPreset::MentionsAndReplies, |
| 123 | NotificationPreset::Customised, |
| 124 | ]; |
| 125 | |
| 126 | pub fn property_value(self) -> i64 { |
| 127 | match self { |
| 128 | NotificationPreset::AllActivity => 1, |
| 129 | NotificationPreset::MentionsAndReplies => 2, |
| 130 | NotificationPreset::Customised => 3, |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | fn from_property(value: &Value) -> Option<Self> { |
| 135 | let number = value |
| 136 | .as_i64() |
| 137 | .or_else(|| value.as_str().and_then(|text| text.parse().ok()))?; |
| 138 | NotificationPreset::ALL |
| 139 | .into_iter() |
| 140 | .find(|preset| preset.property_value() == number) |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /// Teams' "Show in Activity and banner" / "Show in Activity" / "Off" choice, stored as toast, email and activity flags. |
| 145 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 146 | pub enum ActivityAlert { |
| 147 | #[default] |
| 148 | BannerAndFeed, |
| 149 | OnlyFeed, |
| 150 | OnlyBanner, |
| 151 | Off, |
| 152 | } |
| 153 | |
| 154 | impl ActivityAlert { |
| 155 | fn flags(self) -> (bool, bool, bool) { |
| 156 | match self { |
| 157 | ActivityAlert::Off => (false, false, false), |
| 158 | ActivityAlert::OnlyFeed => (false, false, true), |
| 159 | ActivityAlert::OnlyBanner => (true, false, true), |
| 160 | ActivityAlert::BannerAndFeed => (true, true, true), |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | pub fn shows_banner(self) -> bool { |
| 165 | matches!( |
| 166 | self, |
| 167 | ActivityAlert::BannerAndFeed | ActivityAlert::OnlyBanner |
| 168 | ) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 173 | pub enum MeetingChatNotifications { |
| 174 | Mute, |
| 175 | Unmute, |
| 176 | #[default] |
| 177 | MuteUntilJoin, |
| 178 | } |
| 179 | |
| 180 | impl MeetingChatNotifications { |
| 181 | pub const ALL: [MeetingChatNotifications; 3] = [ |
| 182 | MeetingChatNotifications::Mute, |
| 183 | MeetingChatNotifications::Unmute, |
| 184 | MeetingChatNotifications::MuteUntilJoin, |
| 185 | ]; |
| 186 | |
| 187 | pub fn property_value(self) -> &'static str { |
| 188 | match self { |
| 189 | MeetingChatNotifications::Mute => "MeetingsManuallyUnmuted", |
| 190 | MeetingChatNotifications::Unmute => "MeetingsUserIsInvitedTo", |
| 191 | MeetingChatNotifications::MuteUntilJoin => "MeetingsUserParticipatesIn", |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | fn from_property(value: &str) -> Option<Self> { |
| 196 | MeetingChatNotifications::ALL |
| 197 | .into_iter() |
| 198 | .find(|choice| choice.property_value() == value) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 203 | pub struct NotificationAccountSettings { |
| 204 | pub preset: NotificationPreset, |
| 205 | pub chat_messages: ActivityAlert, |
| 206 | pub personal_mentions: ActivityAlert, |
| 207 | pub everyone_mentions: ActivityAlert, |
| 208 | pub likes: ActivityAlert, |
| 209 | pub show_preview: bool, |
| 210 | pub meeting_chats: MeetingChatNotifications, |
| 211 | } |
| 212 | |
| 213 | impl Default for NotificationAccountSettings { |
| 214 | fn default() -> Self { |
| 215 | NotificationAccountSettings { |
| 216 | preset: NotificationPreset::default(), |
| 217 | chat_messages: ActivityAlert::OnlyBanner, |
| 218 | personal_mentions: ActivityAlert::BannerAndFeed, |
| 219 | everyone_mentions: ActivityAlert::BannerAndFeed, |
| 220 | likes: ActivityAlert::BannerAndFeed, |
| 221 | show_preview: true, |
| 222 | meeting_chats: MeetingChatNotifications::default(), |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 228 | pub struct ChatAccountSettings { |
| 229 | pub read_receipts: bool, |
| 230 | pub message_density: MessageDensity, |
| 231 | pub enter_key: EnterKeyBehavior, |
| 232 | pub up_arrow: UpArrowBehavior, |
| 233 | pub notifications: NotificationAccountSettings, |
| 234 | } |
| 235 | |
| 236 | impl Default for ChatAccountSettings { |
| 237 | fn default() -> Self { |
| 238 | ChatAccountSettings { |
| 239 | read_receipts: true, |
| 240 | message_density: MessageDensity::default(), |
| 241 | enter_key: EnterKeyBehavior::default(), |
| 242 | up_arrow: UpArrowBehavior::default(), |
| 243 | notifications: NotificationAccountSettings::default(), |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 249 | pub enum ChatSettingChange { |
| 250 | ReadReceipts(bool), |
| 251 | MessageDensity(MessageDensity), |
| 252 | EnterKey(EnterKeyBehavior), |
| 253 | UpArrow(UpArrowBehavior), |
| 254 | Preset(NotificationPreset), |
| 255 | ChatMessages(ActivityAlert), |
| 256 | PersonalMentions(ActivityAlert), |
| 257 | EveryoneMentions(ActivityAlert), |
| 258 | Likes(ActivityAlert), |
| 259 | ShowPreview(bool), |
| 260 | MeetingChats(MeetingChatNotifications), |
| 261 | } |
| 262 | |
| 263 | /// The account properties Teams keeps these settings in, as last read from `users/ME/properties`. |
| 264 | #[derive(Debug, Clone, PartialEq, Default)] |
| 265 | pub struct ChatSettingsDocument { |
| 266 | properties: Map<String, Value>, |
| 267 | } |
| 268 | |
| 269 | impl ChatSettingsDocument { |
| 270 | pub fn from_properties(properties: &Value) -> Self { |
| 271 | let properties = ACCOUNT_KEYS |
| 272 | .iter() |
| 273 | .filter_map(|key| Some(((*key).to_owned(), properties.get(*key)?.clone()))) |
| 274 | .collect(); |
| 275 | ChatSettingsDocument { properties } |
| 276 | } |
| 277 | |
| 278 | pub fn from_text(text: &str) -> Self { |
| 279 | serde_json::from_str::<Value>(text) |
| 280 | .map(|value| ChatSettingsDocument::from_properties(&value)) |
| 281 | .unwrap_or_default() |
| 282 | } |
| 283 | |
| 284 | pub fn to_text(&self) -> String { |
| 285 | Value::Object(self.properties.clone()).to_string() |
| 286 | } |
| 287 | |
| 288 | pub fn settings(&self) -> ChatAccountSettings { |
| 289 | let defaults = ChatAccountSettings::default(); |
| 290 | let personal = self.json_property(PERSONAL_SETTINGS_KEY); |
| 291 | let compose = self.json_property(COMPOSE_SETTINGS_KEY); |
| 292 | ChatAccountSettings { |
| 293 | read_receipts: self |
| 294 | .properties |
| 295 | .get(READ_RECEIPTS_KEY) |
| 296 | .and_then(flag) |
| 297 | .unwrap_or(defaults.read_receipts), |
| 298 | message_density: self |
| 299 | .properties |
| 300 | .get(MESSAGE_DENSITY_KEY) |
| 301 | .and_then(Value::as_str) |
| 302 | .and_then(MessageDensity::from_property) |
| 303 | .unwrap_or(defaults.message_density), |
| 304 | enter_key: text_at(&compose, &[ENTER_KEY_FIELD]) |
| 305 | .and_then(EnterKeyBehavior::from_property) |
| 306 | .unwrap_or(defaults.enter_key), |
| 307 | up_arrow: text_at(&personal, &[MESSAGING_SETTINGS, UP_ARROW_FIELD]) |
| 308 | .and_then(UpArrowBehavior::from_property) |
| 309 | .unwrap_or(defaults.up_arrow), |
| 310 | notifications: notification_settings(&personal), |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | /// Applies the change and returns the property write Teams makes for it: name and value. |
| 315 | pub fn apply(&mut self, change: ChatSettingChange) -> (&'static str, Value) { |
| 316 | let (name, value) = match change { |
| 317 | ChatSettingChange::ReadReceipts(enabled) => { |
| 318 | (READ_RECEIPTS_KEY, Value::String(enabled.to_string())) |
| 319 | } |
| 320 | ChatSettingChange::MessageDensity(density) => ( |
| 321 | MESSAGE_DENSITY_KEY, |
| 322 | Value::String(density.property_value().to_owned()), |
| 323 | ), |
| 324 | ChatSettingChange::EnterKey(behavior) => { |
| 325 | let mut compose = self.json_property(COMPOSE_SETTINGS_KEY); |
| 326 | compose.insert(ENTER_KEY_FIELD.to_owned(), json!(behavior.property_value())); |
| 327 | ( |
| 328 | COMPOSE_SETTINGS_KEY, |
| 329 | Value::String(Value::Object(compose).to_string()), |
| 330 | ) |
| 331 | } |
| 332 | personal_change => { |
| 333 | let mut personal = self.json_property(PERSONAL_SETTINGS_KEY); |
| 334 | apply_personal(&mut personal, personal_change); |
| 335 | ( |
| 336 | PERSONAL_SETTINGS_KEY, |
| 337 | Value::String(Value::Object(personal).to_string()), |
| 338 | ) |
| 339 | } |
| 340 | }; |
| 341 | self.properties.insert(name.to_owned(), value.clone()); |
| 342 | (name, value) |
| 343 | } |
| 344 | |
| 345 | fn json_property(&self, key: &str) -> Map<String, Value> { |
| 346 | match self.properties.get(key) { |
| 347 | Some(Value::String(text)) => serde_json::from_str::<Value>(text) |
| 348 | .ok() |
| 349 | .and_then(|value| value.as_object().cloned()) |
| 350 | .unwrap_or_default(), |
| 351 | Some(Value::Object(object)) => object.clone(), |
| 352 | _ => Map::new(), |
| 353 | } |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | fn flag(value: &Value) -> Option<bool> { |
| 358 | match value { |
| 359 | Value::Bool(flag) => Some(*flag), |
| 360 | Value::String(text) => Some(!text.trim().eq_ignore_ascii_case("false")), |
| 361 | _ => None, |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | fn value_at<'a>(object: &'a Map<String, Value>, path: &[&str]) -> Option<&'a Value> { |
| 366 | let (first, rest) = path.split_first()?; |
| 367 | rest.iter() |
| 368 | .try_fold(object.get(*first)?, |value, field| value.get(*field)) |
| 369 | } |
| 370 | |
| 371 | fn text_at<'a>(object: &'a Map<String, Value>, path: &[&str]) -> Option<&'a str> { |
| 372 | value_at(object, path)?.as_str() |
| 373 | } |
| 374 | |
| 375 | fn flag_at(object: &Map<String, Value>, group: &str, field: &str) -> Option<bool> { |
| 376 | value_at(object, &[group, field]).and_then(flag) |
| 377 | } |
| 378 | |
| 379 | fn activity_alert( |
| 380 | personal: &Map<String, Value>, |
| 381 | field: &str, |
| 382 | fallback: ActivityAlert, |
| 383 | ) -> ActivityAlert { |
| 384 | let (fallback_toast, _, fallback_activity) = fallback.flags(); |
| 385 | let toast = flag_at(personal, TOAST_SETTINGS, field).unwrap_or(fallback_toast); |
| 386 | let activity = flag_at(personal, ACTIVITY_SETTINGS, field).unwrap_or(fallback_activity); |
| 387 | match (activity, toast) { |
| 388 | (true, true) => ActivityAlert::BannerAndFeed, |
| 389 | (true, false) => ActivityAlert::OnlyFeed, |
| 390 | (false, true) => ActivityAlert::OnlyBanner, |
| 391 | (false, false) => ActivityAlert::Off, |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | fn chat_messages_alert(personal: &Map<String, Value>) -> ActivityAlert { |
| 396 | match flag_at(personal, TOAST_SETTINGS, CHAT_MESSAGES_FIELD) { |
| 397 | Some(false) => ActivityAlert::Off, |
| 398 | _ => ActivityAlert::OnlyBanner, |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | fn notification_settings(personal: &Map<String, Value>) -> NotificationAccountSettings { |
| 403 | let defaults = NotificationAccountSettings::default(); |
| 404 | NotificationAccountSettings { |
| 405 | preset: personal |
| 406 | .get(SELECTED_PRESET_FIELD) |
| 407 | .and_then(NotificationPreset::from_property) |
| 408 | .unwrap_or(defaults.preset), |
| 409 | chat_messages: chat_messages_alert(personal), |
| 410 | personal_mentions: activity_alert( |
| 411 | personal, |
| 412 | PERSONAL_MENTIONS_FIELD, |
| 413 | defaults.personal_mentions, |
| 414 | ), |
| 415 | everyone_mentions: activity_alert( |
| 416 | personal, |
| 417 | EVERYONE_MENTIONS_FIELD, |
| 418 | defaults.everyone_mentions, |
| 419 | ), |
| 420 | likes: activity_alert(personal, LIKES_FIELD, defaults.likes), |
| 421 | show_preview: text_at(personal, &[TOAST_SETTINGS, SHOW_PREVIEW_FIELD]) |
| 422 | .map_or(defaults.show_preview, |value| value != "Off"), |
| 423 | meeting_chats: text_at(personal, &[CHAT_SETTINGS, MEETING_CHAT_FIELD]) |
| 424 | .and_then(MeetingChatNotifications::from_property) |
| 425 | .unwrap_or(defaults.meeting_chats), |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | fn group_mut<'a>(personal: &'a mut Map<String, Value>, group: &str) -> &'a mut Map<String, Value> { |
| 430 | let entry = personal |
| 431 | .entry(group.to_owned()) |
| 432 | .or_insert_with(|| Value::Object(Map::new())); |
| 433 | if !entry.is_object() { |
| 434 | *entry = Value::Object(Map::new()); |
| 435 | } |
| 436 | entry.as_object_mut().expect("group is an object") |
| 437 | } |
| 438 | |
| 439 | fn set_field(personal: &mut Map<String, Value>, group: &str, field: &str, value: Value) { |
| 440 | group_mut(personal, group).insert(field.to_owned(), value); |
| 441 | } |
| 442 | |
| 443 | fn set_alert(personal: &mut Map<String, Value>, field: &str, alert: ActivityAlert) { |
| 444 | let (toast, email, activity) = alert.flags(); |
| 445 | set_field(personal, TOAST_SETTINGS, field, Value::Bool(toast)); |
| 446 | set_field(personal, EMAIL_SETTINGS, field, Value::Bool(email)); |
| 447 | set_field(personal, ACTIVITY_SETTINGS, field, Value::Bool(activity)); |
| 448 | } |
| 449 | |
| 450 | fn apply_personal(personal: &mut Map<String, Value>, change: ChatSettingChange) { |
| 451 | match change { |
| 452 | ChatSettingChange::UpArrow(behavior) => set_field( |
| 453 | personal, |
| 454 | MESSAGING_SETTINGS, |
| 455 | UP_ARROW_FIELD, |
| 456 | json!(behavior.property_value()), |
| 457 | ), |
| 458 | ChatSettingChange::Preset(preset) => { |
| 459 | personal.insert( |
| 460 | SELECTED_PRESET_FIELD.to_owned(), |
| 461 | json!(preset.property_value()), |
| 462 | ); |
| 463 | } |
| 464 | ChatSettingChange::ChatMessages(alert) => set_alert(personal, CHAT_MESSAGES_FIELD, alert), |
| 465 | ChatSettingChange::PersonalMentions(alert) => { |
| 466 | set_alert(personal, PERSONAL_MENTIONS_FIELD, alert) |
| 467 | } |
| 468 | ChatSettingChange::EveryoneMentions(alert) => { |
| 469 | set_alert(personal, EVERYONE_MENTIONS_FIELD, alert) |
| 470 | } |
| 471 | ChatSettingChange::Likes(alert) => set_alert(personal, LIKES_FIELD, alert), |
| 472 | ChatSettingChange::ShowPreview(shown) => set_field( |
| 473 | personal, |
| 474 | TOAST_SETTINGS, |
| 475 | SHOW_PREVIEW_FIELD, |
| 476 | json!(if shown { "On" } else { "Off" }), |
| 477 | ), |
| 478 | ChatSettingChange::MeetingChats(choice) => set_field( |
| 479 | personal, |
| 480 | CHAT_SETTINGS, |
| 481 | MEETING_CHAT_FIELD, |
| 482 | json!(choice.property_value()), |
| 483 | ), |
| 484 | ChatSettingChange::ReadReceipts(_) |
| 485 | | ChatSettingChange::MessageDensity(_) |
| 486 | | ChatSettingChange::EnterKey(_) => {} |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | pub struct ChatSettingsClient<T: MessageTransport = SessionMessageTransport> { |
| 491 | settings: UserSettings<T>, |
| 492 | } |
| 493 | |
| 494 | impl ChatSettingsClient<SessionMessageTransport> { |
| 495 | pub fn new(session: &Session) -> Self { |
| 496 | ChatSettingsClient::with_settings(UserSettings::new(session)) |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | impl<T: MessageTransport> ChatSettingsClient<T> { |
| 501 | pub fn with_settings(settings: UserSettings<T>) -> Self { |
| 502 | ChatSettingsClient { settings } |
| 503 | } |
| 504 | |
| 505 | pub async fn read(&self) -> Result<ChatSettingsDocument> { |
| 506 | Ok(ChatSettingsDocument::from_properties( |
| 507 | &self.settings.properties().await?, |
| 508 | )) |
| 509 | } |
| 510 | |
| 511 | /// Reads the current properties first so fields this client does not know survive the write. |
| 512 | pub async fn write(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> { |
| 513 | let mut document = self.read().await?; |
| 514 | let (name, value) = document.apply(change); |
| 515 | self.settings.set_property(name, value).await?; |
| 516 | Ok(document) |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | #[cfg(test)] |
| 521 | mod tests { |
| 522 | use std::collections::VecDeque; |
| 523 | use std::sync::Mutex; |
| 524 | |
| 525 | use session::{ApiResponse, Method, Request}; |
| 526 | |
| 527 | use super::*; |
| 528 | |
| 529 | struct Canned { |
| 530 | answers: Mutex<VecDeque<(u16, Value)>>, |
| 531 | requests: Mutex<Vec<Request>>, |
| 532 | } |
| 533 | |
| 534 | impl MessageTransport for &Canned { |
| 535 | async fn send(&self, request: Request) -> Result<ApiResponse> { |
| 536 | self.requests.lock().unwrap().push(request); |
| 537 | let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted"); |
| 538 | Ok(ApiResponse { |
| 539 | status, |
| 540 | body, |
| 541 | retry_after: None, |
| 542 | }) |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | fn parsed(text: &str) -> Value { |
| 547 | serde_json::from_str(text).unwrap() |
| 548 | } |
| 549 | |
| 550 | #[test] |
| 551 | fn missing_properties_give_the_teams_defaults() { |
| 552 | let settings = ChatSettingsDocument::from_properties(&json!({})).settings(); |
| 553 | assert_eq!(settings, ChatAccountSettings::default()); |
| 554 | assert!(settings.read_receipts); |
| 555 | assert_eq!(settings.message_density, MessageDensity::Comfy); |
| 556 | assert_eq!(settings.enter_key, EnterKeyBehavior::Send); |
| 557 | assert_eq!(settings.up_arrow, UpArrowBehavior::EditLastMessage); |
| 558 | assert_eq!( |
| 559 | settings.notifications.preset, |
| 560 | NotificationPreset::Customised |
| 561 | ); |
| 562 | assert_eq!( |
| 563 | settings.notifications.meeting_chats, |
| 564 | MeetingChatNotifications::MuteUntilJoin |
| 565 | ); |
| 566 | } |
| 567 | |
| 568 | #[test] |
| 569 | fn reads_every_setting_from_the_teams_properties() { |
| 570 | let personal = json!({ |
| 571 | "messagingSettings": {"upArrowKeyBehavior": "STAY_IN_COMPOSE"}, |
| 572 | "selectedPreset": 2, |
| 573 | "toastSettings": {"Chat": false, "MentionInChat_Person_v2": false, "LikeInChat_v2": true, "ShowPreviewInToasts": "Off"}, |
| 574 | "activityGenerationSettings": {"MentionInChat_Person_v2": true, "LikeInChat_v2": false, "MentionInChat_Everyone": false}, |
| 575 | "chatSettings": {"meetingChatNotification": "MeetingsUserIsInvitedTo"}, |
| 576 | }); |
| 577 | let document = ChatSettingsDocument::from_properties(&json!({ |
| 578 | "readReceiptsEnabled": "false", |
| 579 | "messageDensity": "COMPACT", |
| 580 | "composeUserSettings": "{\"enterKeyBehavior\":\"CreateNewLine\"}", |
| 581 | "userPersonalSettings": personal.to_string(), |
| 582 | "unrelated": "dropped", |
| 583 | })); |
| 584 | let settings = document.settings(); |
| 585 | assert!(!settings.read_receipts); |
| 586 | assert_eq!(settings.message_density, MessageDensity::Compact); |
| 587 | assert_eq!(settings.enter_key, EnterKeyBehavior::NewLine); |
| 588 | assert_eq!(settings.up_arrow, UpArrowBehavior::StayInCompose); |
| 589 | let notifications = settings.notifications; |
| 590 | assert_eq!(notifications.preset, NotificationPreset::MentionsAndReplies); |
| 591 | assert_eq!(notifications.chat_messages, ActivityAlert::Off); |
| 592 | assert_eq!(notifications.personal_mentions, ActivityAlert::OnlyFeed); |
| 593 | assert_eq!(notifications.likes, ActivityAlert::OnlyBanner); |
| 594 | assert_eq!(notifications.everyone_mentions, ActivityAlert::OnlyBanner); |
| 595 | assert!(!notifications.show_preview); |
| 596 | assert_eq!( |
| 597 | notifications.meeting_chats, |
| 598 | MeetingChatNotifications::Unmute |
| 599 | ); |
| 600 | assert!(!document.to_text().contains("unrelated")); |
| 601 | } |
| 602 | |
| 603 | #[test] |
| 604 | fn read_receipts_follow_teams_parsing() { |
| 605 | let read = |value: Value| { |
| 606 | ChatSettingsDocument::from_properties(&json!({"readReceiptsEnabled": value})) |
| 607 | .settings() |
| 608 | .read_receipts |
| 609 | }; |
| 610 | assert!(read(json!("true"))); |
| 611 | assert!(!read(json!(" False "))); |
| 612 | assert!(!read(json!(false))); |
| 613 | assert!(read(json!("anything"))); |
| 614 | } |
| 615 | |
| 616 | #[test] |
| 617 | fn plain_properties_are_written_as_teams_strings() { |
| 618 | let mut document = ChatSettingsDocument::default(); |
| 619 | assert_eq!( |
| 620 | document.apply(ChatSettingChange::ReadReceipts(false)), |
| 621 | ("readReceiptsEnabled", json!("false")) |
| 622 | ); |
| 623 | assert_eq!( |
| 624 | document.apply(ChatSettingChange::MessageDensity(MessageDensity::Compact)), |
| 625 | ("messageDensity", json!("COMPACT")) |
| 626 | ); |
| 627 | let settings = document.settings(); |
| 628 | assert!(!settings.read_receipts); |
| 629 | assert_eq!(settings.message_density, MessageDensity::Compact); |
| 630 | } |
| 631 | |
| 632 | #[test] |
| 633 | fn enter_key_keeps_other_compose_fields() { |
| 634 | let mut document = ChatSettingsDocument::from_properties(&json!({ |
| 635 | "composeUserSettings": "{\"enterKeyBehavior\":\"Default\",\"future\":1}" |
| 636 | })); |
| 637 | let (name, value) = document.apply(ChatSettingChange::EnterKey(EnterKeyBehavior::NewLine)); |
| 638 | assert_eq!(name, "composeUserSettings"); |
| 639 | assert_eq!( |
| 640 | parsed(value.as_str().unwrap()), |
| 641 | json!({"enterKeyBehavior": "CreateNewLine", "future": 1}) |
| 642 | ); |
| 643 | } |
| 644 | |
| 645 | #[test] |
| 646 | fn personal_settings_changes_keep_unknown_fields() { |
| 647 | let mut document = ChatSettingsDocument::from_properties(&json!({ |
| 648 | "userPersonalSettings": "{\"soundsSettings\":{\"alertSound\":\"All\"},\"messagingSettings\":{\"shouldShowDiscoverApp\":true}}" |
| 649 | })); |
| 650 | document.apply(ChatSettingChange::UpArrow( |
| 651 | UpArrowBehavior::NavigateToMessages, |
| 652 | )); |
| 653 | let (name, value) = |
| 654 | document.apply(ChatSettingChange::Preset(NotificationPreset::AllActivity)); |
| 655 | assert_eq!(name, "userPersonalSettings"); |
| 656 | assert_eq!( |
| 657 | parsed(value.as_str().unwrap()), |
| 658 | json!({ |
| 659 | "soundsSettings": {"alertSound": "All"}, |
| 660 | "messagingSettings": {"shouldShowDiscoverApp": true, "upArrowKeyBehavior": "NAVIGATE_TO_MESSAGES"}, |
| 661 | "selectedPreset": 1, |
| 662 | }) |
| 663 | ); |
| 664 | } |
| 665 | |
| 666 | #[test] |
| 667 | fn alerts_write_toast_email_and_activity_like_teams() { |
| 668 | let mut document = ChatSettingsDocument::default(); |
| 669 | document.apply(ChatSettingChange::ChatMessages(ActivityAlert::Off)); |
| 670 | document.apply(ChatSettingChange::PersonalMentions(ActivityAlert::OnlyFeed)); |
| 671 | let (_, value) = document.apply(ChatSettingChange::Likes(ActivityAlert::BannerAndFeed)); |
| 672 | let personal = parsed(value.as_str().unwrap()); |
| 673 | assert_eq!( |
| 674 | personal["toastSettings"], |
| 675 | json!({"Chat": false, "MentionInChat_Person_v2": false, "LikeInChat_v2": true}) |
| 676 | ); |
| 677 | assert_eq!( |
| 678 | personal["emailSettings"], |
| 679 | json!({"Chat": false, "MentionInChat_Person_v2": false, "LikeInChat_v2": true}) |
| 680 | ); |
| 681 | assert_eq!( |
| 682 | personal["activityGenerationSettings"], |
| 683 | json!({"Chat": false, "MentionInChat_Person_v2": true, "LikeInChat_v2": true}) |
| 684 | ); |
| 685 | let notifications = document.settings().notifications; |
| 686 | assert_eq!(notifications.chat_messages, ActivityAlert::Off); |
| 687 | assert_eq!(notifications.personal_mentions, ActivityAlert::OnlyFeed); |
| 688 | assert_eq!(notifications.likes, ActivityAlert::BannerAndFeed); |
| 689 | } |
| 690 | |
| 691 | #[test] |
| 692 | fn preview_and_meeting_chats_round_trip() { |
| 693 | let mut document = ChatSettingsDocument::default(); |
| 694 | document.apply(ChatSettingChange::ShowPreview(false)); |
| 695 | document.apply(ChatSettingChange::MeetingChats( |
| 696 | MeetingChatNotifications::Mute, |
| 697 | )); |
| 698 | let restored = ChatSettingsDocument::from_text(&document.to_text()); |
| 699 | let notifications = restored.settings().notifications; |
| 700 | assert!(!notifications.show_preview); |
| 701 | assert_eq!(notifications.meeting_chats, MeetingChatNotifications::Mute); |
| 702 | assert_eq!(restored, document); |
| 703 | } |
| 704 | |
| 705 | #[tokio::test] |
| 706 | async fn write_reads_then_puts_the_named_property() { |
| 707 | let transport = Canned { |
| 708 | answers: Mutex::new( |
| 709 | vec![ |
| 710 | (200, json!({"messageDensity": "COMFY", "other": 1})), |
| 711 | (200, Value::Null), |
| 712 | ] |
| 713 | .into(), |
| 714 | ), |
| 715 | requests: Mutex::new(Vec::new()), |
| 716 | }; |
| 717 | let client = |
| 718 | ChatSettingsClient::with_settings(UserSettings::with_transport(&transport, "emea")); |
| 719 | let document = client |
| 720 | .write(ChatSettingChange::MessageDensity(MessageDensity::Compact)) |
| 721 | .await |
| 722 | .unwrap(); |
| 723 | assert_eq!(document.settings().message_density, MessageDensity::Compact); |
| 724 | let requests = transport.requests.lock().unwrap(); |
| 725 | assert_eq!(requests[0].method, Method::Get); |
| 726 | assert_eq!(requests[1].method, Method::Put); |
| 727 | assert_eq!( |
| 728 | requests[1].url, |
| 729 | "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=messageDensity" |
| 730 | ); |
| 731 | assert_eq!(requests[1].body, Some(json!({"messageDensity": "COMPACT"}))); |
| 732 | } |
| 733 | } |