feat(settings): account chat and notification settings in chatsvc
- read and merge-write readReceiptsEnabled, messageDensity, composeUserSettings and userPersonalSettings like Teams - per chat conversationNotificationSettings plus alerts - engine cache in store meta, refresh and save through the remote Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -0,0 +1,130 @@
1
use serde_json::{Map, Value};
2
3
pub(crate) const PROPERTY_NAME: &str = "conversationNotificationSettings";
4
const ALL_NEW_POSTS: &str = "allNewPosts";
5
const DESKTOP: &str = "dskNotif";
6
const EVERYONE: &str = "everyone";
7
const ON: &str = "On";
8
const OFF: &str = "Off";
9
10
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11
pub enum ChatNotificationMode {
12
#[default]
13
AllNewMessages,
14
Mute,
15
}
16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18
pub enum DesktopNotifications {
19
#[default]
20
MatchAllChats,
21
On,
22
Off,
23
}
24
25
#[derive(Debug, Clone, PartialEq, Eq)]
26
pub struct ChatNotificationWrite {
27
pub alerts: bool,
28
pub settings: String,
29
}
30
31
fn stored(raw: Option<&str>) -> Map<String, Value> {
32
raw.and_then(|text| serde_json::from_str::<Value>(text).ok())
33
.and_then(|value| value.as_object().cloned())
34
.unwrap_or_default()
35
}
36
37
pub fn parse_desktop(raw: Option<&str>) -> DesktopNotifications {
38
match stored(raw).get(DESKTOP).and_then(Value::as_str) {
39
Some(ON) => DesktopNotifications::On,
40
Some(OFF) => DesktopNotifications::Off,
41
_ => DesktopNotifications::MatchAllChats,
42
}
43
}
44
45
/// Teams' granular chat setting: `alerts` plus the merged `conversationNotificationSettings` text.
46
pub fn chat_notification_write(
47
raw: Option<&str>,
48
mode: ChatNotificationMode,
49
desktop: DesktopNotifications,
50
) -> ChatNotificationWrite {
51
let mut settings = stored(raw);
52
let desktop_value = match desktop {
53
DesktopNotifications::MatchAllChats => Value::Null,
54
DesktopNotifications::On => Value::String(ON.to_owned()),
55
DesktopNotifications::Off => Value::String(OFF.to_owned()),
56
};
57
settings.insert(DESKTOP.to_owned(), desktop_value);
58
let alerts = mode == ChatNotificationMode::AllNewMessages;
59
settings.insert(
60
ALL_NEW_POSTS.to_owned(),
61
Value::String(if alerts { ON } else { OFF }.to_owned()),
62
);
63
if !alerts {
64
settings.insert(EVERYONE.to_owned(), Value::String(OFF.to_owned()));
65
}
66
ChatNotificationWrite {
67
alerts,
68
settings: Value::Object(settings).to_string(),
69
}
70
}
71
72
#[cfg(test)]
73
mod tests {
74
use serde_json::json;
75
76
use super::*;
77
78
fn written(write: &ChatNotificationWrite) -> Value {
79
serde_json::from_str(&write.settings).unwrap()
80
}
81
82
#[test]
83
fn desktop_preference_is_read_from_dsk_notif() {
84
assert_eq!(parse_desktop(None), DesktopNotifications::MatchAllChats);
85
assert_eq!(
86
parse_desktop(Some(r#"{"dskNotif":"Off"}"#)),
87
DesktopNotifications::Off
88
);
89
assert_eq!(
90
parse_desktop(Some(r#"{"dskNotif":"On","allNewPosts":"On"}"#)),
91
DesktopNotifications::On
92
);
93
assert_eq!(
94
parse_desktop(Some(r#"{"dskNotif":null}"#)),
95
DesktopNotifications::MatchAllChats
96
);
97
assert_eq!(
98
parse_desktop(Some("garbage")),
99
DesktopNotifications::MatchAllChats
100
);
101
}
102
103
#[test]
104
fn all_new_messages_turns_alerts_on_and_keeps_other_fields() {
105
let write = chat_notification_write(
106
Some(r#"{"everyone":"On","future":1}"#),
107
ChatNotificationMode::AllNewMessages,
108
DesktopNotifications::MatchAllChats,
109
);
110
assert!(write.alerts);
111
assert_eq!(
112
written(&write),
113
json!({"everyone": "On", "future": 1, "dskNotif": null, "allNewPosts": "On"})
114
);
115
}
116
117
#[test]
118
fn mute_turns_alerts_and_everyone_mentions_off() {
119
let write = chat_notification_write(
120
Some(r#"{"everyone":"On"}"#),
121
ChatNotificationMode::Mute,
122
DesktopNotifications::Off,
123
);
124
assert!(!write.alerts);
125
assert_eq!(
126
written(&write),
127
json!({"everyone": "Off", "dskNotif": "Off", "allNewPosts": "Off"})
128
);
129
}
130
}
@@ -0,0 +1,130 @@1
use serde_json::{Map, Value};2
3
pub(crate) const PROPERTY_NAME: &str = "conversationNotificationSettings";4
const ALL_NEW_POSTS: &str = "allNewPosts";5
const DESKTOP: &str = "dskNotif";6
const EVERYONE: &str = "everyone";7
const ON: &str = "On";8
const OFF: &str = "Off";9
10
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]11
pub enum ChatNotificationMode {12
#[default]13
AllNewMessages,14
Mute,15
}16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]18
pub enum DesktopNotifications {19
#[default]20
MatchAllChats,21
On,22
Off,23
}24
25
#[derive(Debug, Clone, PartialEq, Eq)]26
pub struct ChatNotificationWrite {27
pub alerts: bool,28
pub settings: String,29
}30
31
fn stored(raw: Option<&str>) -> Map<String, Value> {32
raw.and_then(|text| serde_json::from_str::<Value>(text).ok())33
.and_then(|value| value.as_object().cloned())34
.unwrap_or_default()35
}36
37
pub fn parse_desktop(raw: Option<&str>) -> DesktopNotifications {38
match stored(raw).get(DESKTOP).and_then(Value::as_str) {39
Some(ON) => DesktopNotifications::On,40
Some(OFF) => DesktopNotifications::Off,41
_ => DesktopNotifications::MatchAllChats,42
}43
}44
45
/// Teams' granular chat setting: `alerts` plus the merged `conversationNotificationSettings` text.46
pub fn chat_notification_write(47
raw: Option<&str>,48
mode: ChatNotificationMode,49
desktop: DesktopNotifications,50
) -> ChatNotificationWrite {51
let mut settings = stored(raw);52
let desktop_value = match desktop {53
DesktopNotifications::MatchAllChats => Value::Null,54
DesktopNotifications::On => Value::String(ON.to_owned()),55
DesktopNotifications::Off => Value::String(OFF.to_owned()),56
};57
settings.insert(DESKTOP.to_owned(), desktop_value);58
let alerts = mode == ChatNotificationMode::AllNewMessages;59
settings.insert(60
ALL_NEW_POSTS.to_owned(),61
Value::String(if alerts { ON } else { OFF }.to_owned()),62
);63
if !alerts {64
settings.insert(EVERYONE.to_owned(), Value::String(OFF.to_owned()));65
}66
ChatNotificationWrite {67
alerts,68
settings: Value::Object(settings).to_string(),69
}70
}71
72
#[cfg(test)]73
mod tests {74
use serde_json::json;75
76
use super::*;77
78
fn written(write: &ChatNotificationWrite) -> Value {79
serde_json::from_str(&write.settings).unwrap()80
}81
82
#[test]83
fn desktop_preference_is_read_from_dsk_notif() {84
assert_eq!(parse_desktop(None), DesktopNotifications::MatchAllChats);85
assert_eq!(86
parse_desktop(Some(r#"{"dskNotif":"Off"}"#)),87
DesktopNotifications::Off88
);89
assert_eq!(90
parse_desktop(Some(r#"{"dskNotif":"On","allNewPosts":"On"}"#)),91
DesktopNotifications::On92
);93
assert_eq!(94
parse_desktop(Some(r#"{"dskNotif":null}"#)),95
DesktopNotifications::MatchAllChats96
);97
assert_eq!(98
parse_desktop(Some("garbage")),99
DesktopNotifications::MatchAllChats100
);101
}102
103
#[test]104
fn all_new_messages_turns_alerts_on_and_keeps_other_fields() {105
let write = chat_notification_write(106
Some(r#"{"everyone":"On","future":1}"#),107
ChatNotificationMode::AllNewMessages,108
DesktopNotifications::MatchAllChats,109
);110
assert!(write.alerts);111
assert_eq!(112
written(&write),113
json!({"everyone": "On", "future": 1, "dskNotif": null, "allNewPosts": "On"})114
);115
}116
117
#[test]118
fn mute_turns_alerts_and_everyone_mentions_off() {119
let write = chat_notification_write(120
Some(r#"{"everyone":"On"}"#),121
ChatNotificationMode::Mute,122
DesktopNotifications::Off,123
);124
assert!(!write.alerts);125
assert_eq!(126
written(&write),127
json!({"everyone": "Off", "dskNotif": "Off", "allNewPosts": "Off"})128
);129
}130
}@@ -0,0 +1,733 @@
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
}
@@ -0,0 +1,733 @@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::ALL52
.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::ALL76
.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::ALL106
.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 = value136
.as_i64()137
.or_else(|| value.as_str().and_then(|text| text.parse().ok()))?;138
NotificationPreset::ALL139
.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::OnlyBanner168
)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::ALL197
.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_KEYS272
.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: self294
.properties295
.get(READ_RECEIPTS_KEY)296
.and_then(flag)297
.unwrap_or(defaults.read_receipts),298
message_density: self299
.properties300
.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: personal406
.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 = personal431
.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::Customised561
);562
assert_eq!(563
settings.notifications.meeting_chats,564
MeetingChatNotifications::MuteUntilJoin565
);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::Unmute599
);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_receipts609
};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 = client720
.write(ChatSettingChange::MessageDensity(MessageDensity::Compact))721
.await722
.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
}@@ -2,6 +2,9 @@ use serde_json::{Value, json};
2
2
use session::{Method, Request, Session};
3
3
4
4
use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};
5
use crate::chat_notifications::{
6
self, ChatNotificationMode, ChatNotificationWrite, DesktopNotifications,
7
};
5
8
use crate::error::{Error, Result};
6
9
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
7
10
use crate::pins::DEFAULT_REGION;
@@ -11,12 +14,19 @@ const PAGE_SIZE: usize = 200;
11
14
const MAX_PAGES: usize = 100;
12
15
const ALERTS_OFF: &str = "false";
13
16
14
#[derive(Debug, Clone, PartialEq, Eq)]
17
#[derive(Debug, Clone, PartialEq, Eq, Default)]
15
18
pub struct ConversationState {
16
19
pub id: String,
17
20
pub muted: bool,
18
21
pub hidden: Option<bool>,
19
22
pub read: ReadHorizon,
23
pub notification_settings: Option<String>,
24
}
25
26
impl ConversationState {
27
pub fn desktop_notifications(&self) -> DesktopNotifications {
28
chat_notifications::parse_desktop(self.notification_settings.as_deref())
29
}
20
30
}
21
31
22
32
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
@@ -84,6 +94,31 @@ impl<T: MessageTransport> Conversations<T> {
84
94
ensure_success(&answer)
85
95
}
86
96
97
/// Teams writes the merged notification settings first, then `alerts`.
98
pub async fn set_chat_notifications(
99
&self,
100
conversation_id: &str,
101
current_settings: Option<&str>,
102
mode: ChatNotificationMode,
103
desktop: DesktopNotifications,
104
) -> Result<ChatNotificationWrite> {
105
let write = chat_notifications::chat_notification_write(current_settings, mode, desktop);
106
let url = format!(
107
"{}/{}/properties?name={}",
108
self.base_url,
109
encode(conversation_id),
110
chat_notifications::PROPERTY_NAME
111
);
112
let body = json!({ chat_notifications::PROPERTY_NAME: write.settings });
113
let answer = self
114
.transport
115
.send(Request::with_body(Method::Put, url, body))
116
.await?;
117
ensure_success(&answer)?;
118
self.set_alerts(conversation_id, write.alerts).await?;
119
Ok(write)
120
}
121
87
122
pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
88
123
let url = format!(
89
124
"{}/{}/properties?name={}",
@@ -167,6 +202,10 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
167
202
muted,
168
203
hidden: hidden_flag(conversation),
169
204
read: ReadHorizon::from_conversation(conversation),
205
notification_settings: conversation["properties"]
206
[chat_notifications::PROPERTY_NAME]
207
.as_str()
208
.map(str::to_owned),
170
209
})
171
210
})
172
211
.collect())
@@ -209,8 +248,7 @@ mod tests {
209
248
ConversationState {
210
249
id: id.to_owned(),
211
250
muted,
212
hidden: None,
213
read: ReadHorizon::default(),
251
..Default::default()
214
252
}
215
253
}
216
254
@@ -401,4 +439,49 @@ mod tests {
401
439
Some(json!({"consumptionhorizon": "9;10;0"}))
402
440
);
403
441
}
442
443
#[tokio::test]
444
async fn chat_notifications_put_the_settings_then_alerts() {
445
let transport = canned(vec![(200, Value::Null), (200, Value::Null)]);
446
let write = Conversations::with_transport(&transport, "emea")
447
.set_chat_notifications(
448
"19:a@thread.v2",
449
Some(r#"{"everyone":"On"}"#),
450
ChatNotificationMode::Mute,
451
DesktopNotifications::MatchAllChats,
452
)
453
.await
454
.unwrap();
455
assert!(!write.alerts);
456
let requests = transport.requests.lock().unwrap();
457
assert_eq!(
458
requests[0].url,
459
format!("{BASE}/19%3Aa%40thread.v2/properties?name=conversationNotificationSettings")
460
);
461
let sent = requests[0].body.as_ref().unwrap()["conversationNotificationSettings"]
462
.as_str()
463
.unwrap();
464
assert_eq!(
465
serde_json::from_str::<Value>(sent).unwrap(),
466
json!({"everyone": "Off", "dskNotif": null, "allNewPosts": "Off"})
467
);
468
assert_eq!(
469
requests[1].url,
470
format!("{BASE}/19%3Aa%40thread.v2/properties?name=alerts")
471
);
472
assert_eq!(requests[1].body, Some(json!({"alerts": "false"})));
473
}
474
475
#[tokio::test]
476
async fn states_carry_the_chat_notification_settings() {
477
let transport = canned(vec![(
478
200,
479
json!({"conversations": [{"id": "19:a", "properties": {"conversationNotificationSettings": "{\"dskNotif\":\"Off\"}"}}]}),
480
)]);
481
let states = Conversations::with_transport(&transport, "emea")
482
.conversation_states()
483
.await
484
.unwrap();
485
assert_eq!(states[0].desktop_notifications(), DesktopNotifications::Off);
486
}
404
487
}
@@ -2,6 +2,9 @@ use serde_json::{Value, json};2
use session::{Method, Request, Session};2
use session::{Method, Request, Session};3
3
4
use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};4
use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};5
use crate::chat_notifications::{6
self, ChatNotificationMode, ChatNotificationWrite, DesktopNotifications,7
};5
use crate::error::{Error, Result};8
use crate::error::{Error, Result};6
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};9
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};7
use crate::pins::DEFAULT_REGION;10
use crate::pins::DEFAULT_REGION;@@ -11,12 +14,19 @@ const PAGE_SIZE: usize = 200;11
const MAX_PAGES: usize = 100;14
const MAX_PAGES: usize = 100;12
const ALERTS_OFF: &str = "false";15
const ALERTS_OFF: &str = "false";13
16
14
#[derive(Debug, Clone, PartialEq, Eq)]17
#[derive(Debug, Clone, PartialEq, Eq, Default)]15
pub struct ConversationState {18
pub struct ConversationState {16
pub id: String,19
pub id: String,17
pub muted: bool,20
pub muted: bool,18
pub hidden: Option<bool>,21
pub hidden: Option<bool>,19
pub read: ReadHorizon,22
pub read: ReadHorizon,23
pub notification_settings: Option<String>,24
}25
26
impl ConversationState {27
pub fn desktop_notifications(&self) -> DesktopNotifications {28
chat_notifications::parse_desktop(self.notification_settings.as_deref())29
}20
}30
}21
31
22
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {32
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {@@ -84,6 +94,31 @@ impl<T: MessageTransport> Conversations<T> {84
ensure_success(&answer)94
ensure_success(&answer)85
}95
}86
96
97
/// Teams writes the merged notification settings first, then `alerts`.98
pub async fn set_chat_notifications(99
&self,100
conversation_id: &str,101
current_settings: Option<&str>,102
mode: ChatNotificationMode,103
desktop: DesktopNotifications,104
) -> Result<ChatNotificationWrite> {105
let write = chat_notifications::chat_notification_write(current_settings, mode, desktop);106
let url = format!(107
"{}/{}/properties?name={}",108
self.base_url,109
encode(conversation_id),110
chat_notifications::PROPERTY_NAME111
);112
let body = json!({ chat_notifications::PROPERTY_NAME: write.settings });113
let answer = self114
.transport115
.send(Request::with_body(Method::Put, url, body))116
.await?;117
ensure_success(&answer)?;118
self.set_alerts(conversation_id, write.alerts).await?;119
Ok(write)120
}121
87
pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {122
pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {88
let url = format!(123
let url = format!(89
"{}/{}/properties?name={}",124
"{}/{}/properties?name={}",@@ -167,6 +202,10 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {167
muted,202
muted,168
hidden: hidden_flag(conversation),203
hidden: hidden_flag(conversation),169
read: ReadHorizon::from_conversation(conversation),204
read: ReadHorizon::from_conversation(conversation),205
notification_settings: conversation["properties"]206
[chat_notifications::PROPERTY_NAME]207
.as_str()208
.map(str::to_owned),170
})209
})171
})210
})172
.collect())211
.collect())@@ -209,8 +248,7 @@ mod tests {209
ConversationState {248
ConversationState {210
id: id.to_owned(),249
id: id.to_owned(),211
muted,250
muted,212
hidden: None,251
..Default::default()213
read: ReadHorizon::default(),214
}252
}215
}253
}216
254
@@ -401,4 +439,49 @@ mod tests {401
Some(json!({"consumptionhorizon": "9;10;0"}))439
Some(json!({"consumptionhorizon": "9;10;0"}))402
);440
);403
}441
}442
443
#[tokio::test]444
async fn chat_notifications_put_the_settings_then_alerts() {445
let transport = canned(vec![(200, Value::Null), (200, Value::Null)]);446
let write = Conversations::with_transport(&transport, "emea")447
.set_chat_notifications(448
"19:a@thread.v2",449
Some(r#"{"everyone":"On"}"#),450
ChatNotificationMode::Mute,451
DesktopNotifications::MatchAllChats,452
)453
.await454
.unwrap();455
assert!(!write.alerts);456
let requests = transport.requests.lock().unwrap();457
assert_eq!(458
requests[0].url,459
format!("{BASE}/19%3Aa%40thread.v2/properties?name=conversationNotificationSettings")460
);461
let sent = requests[0].body.as_ref().unwrap()["conversationNotificationSettings"]462
.as_str()463
.unwrap();464
assert_eq!(465
serde_json::from_str::<Value>(sent).unwrap(),466
json!({"everyone": "Off", "dskNotif": null, "allNewPosts": "Off"})467
);468
assert_eq!(469
requests[1].url,470
format!("{BASE}/19%3Aa%40thread.v2/properties?name=alerts")471
);472
assert_eq!(requests[1].body, Some(json!({"alerts": "false"})));473
}474
475
#[tokio::test]476
async fn states_carry_the_chat_notification_settings() {477
let transport = canned(vec![(478
200,479
json!({"conversations": [{"id": "19:a", "properties": {"conversationNotificationSettings": "{\"dskNotif\":\"Off\"}"}}]}),480
)]);481
let states = Conversations::with_transport(&transport, "emea")482
.conversation_states()483
.await484
.unwrap();485
assert_eq!(states[0].desktop_notifications(), DesktopNotifications::Off);486
}404
}487
}@@ -4,6 +4,8 @@ pub mod calendar;
4
4
pub mod calllog;
5
5
pub mod cards;
6
6
pub mod channel_notifications;
7
pub mod chat_notifications;
8
pub mod chat_settings;
7
9
pub mod conversations;
8
10
pub mod drafts;
9
11
pub mod emotions;
@@ -45,6 +47,12 @@ pub use cards::{
45
47
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
46
48
};
47
49
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
50
pub use chat_notifications::{ChatNotificationMode, ChatNotificationWrite, DesktopNotifications};
51
pub use chat_settings::{
52
ActivityAlert, ChatAccountSettings, ChatSettingChange, ChatSettingsClient,
53
ChatSettingsDocument, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,
54
NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
55
};
48
56
pub use conversations::{ConversationState, Conversations};
49
57
pub use drafts::{ScheduledDraft, ScheduledDrafts};
50
58
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
@@ -4,6 +4,8 @@ pub mod calendar;4
pub mod calllog;4
pub mod calllog;5
pub mod cards;5
pub mod cards;6
pub mod channel_notifications;6
pub mod channel_notifications;7
pub mod chat_notifications;8
pub mod chat_settings;7
pub mod conversations;9
pub mod conversations;8
pub mod drafts;10
pub mod drafts;9
pub mod emotions;11
pub mod emotions;@@ -45,6 +47,12 @@ pub use cards::{45
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,47
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,46
};48
};47
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};49
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};50
pub use chat_notifications::{ChatNotificationMode, ChatNotificationWrite, DesktopNotifications};51
pub use chat_settings::{52
ActivityAlert, ChatAccountSettings, ChatSettingChange, ChatSettingsClient,53
ChatSettingsDocument, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,54
NotificationAccountSettings, NotificationPreset, UpArrowBehavior,55
};48
pub use conversations::{ConversationState, Conversations};56
pub use conversations::{ConversationState, Conversations};49
pub use drafts::{ScheduledDraft, ScheduledDrafts};57
pub use drafts::{ScheduledDraft, ScheduledDrafts};50
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};58
pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};@@ -62,6 +62,7 @@ mod tests {
62
62
last_message_from: Some("8:orgid:someone".to_owned()),
63
63
..ReadHorizon::default()
64
64
},
65
notification_settings: None,
65
66
}
66
67
}
67
68
@@ -62,6 +62,7 @@ mod tests {62
last_message_from: Some("8:orgid:someone".to_owned()),62
last_message_from: Some("8:orgid:someone".to_owned()),63
..ReadHorizon::default()63
..ReadHorizon::default()64
},64
},65
notification_settings: None,65
}66
}66
}67
}67
68
@@ -0,0 +1,92 @@
1
use chatsvc::{
2
ChatNotificationMode, ChatSettingChange, ChatSettingsDocument, DesktopNotifications,
3
};
4
use store::Store;
5
6
use crate::engine::SyncEngine;
7
use crate::error::Result;
8
use crate::events::CoreEvent;
9
use crate::remote::Remote;
10
11
const META_CHAT_SETTINGS: &str = "account.chat_settings";
12
13
pub fn stored_chat_settings(store: &Store) -> ChatSettingsDocument {
14
store
15
.meta(META_CHAT_SETTINGS)
16
.ok()
17
.flatten()
18
.map(|text| ChatSettingsDocument::from_text(&text))
19
.unwrap_or_default()
20
}
21
22
pub fn store_chat_settings(store: &Store, document: &ChatSettingsDocument) -> Result<()> {
23
Ok(store.set_meta(META_CHAT_SETTINGS, &document.to_text())?)
24
}
25
26
impl<R: Remote> SyncEngine<R> {
27
pub async fn refresh_chat_settings(&self) -> Result<ChatSettingsDocument> {
28
let document = self.remote.chat_settings().await?;
29
store_chat_settings(&self.store, &document)?;
30
Ok(document)
31
}
32
33
pub async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {
34
let document = self.remote.save_chat_setting(change).await?;
35
store_chat_settings(&self.store, &document)?;
36
Ok(document)
37
}
38
39
pub fn chat_desktop_notifications(&self, chat_id: &str) -> DesktopNotifications {
40
self.chat_states
41
.lock()
42
.unwrap()
43
.get(chat_id)
44
.map(|state| state.desktop_notifications())
45
.unwrap_or_default()
46
}
47
48
pub async fn set_chat_notifications(
49
&self,
50
chat_id: &str,
51
mode: ChatNotificationMode,
52
desktop: DesktopNotifications,
53
) -> Result<()> {
54
let current = self
55
.chat_states
56
.lock()
57
.unwrap()
58
.get(chat_id)
59
.and_then(|state| state.notification_settings.clone());
60
let write = self
61
.remote
62
.set_chat_notifications(chat_id, current.as_deref(), mode, desktop)
63
.await?;
64
{
65
let mut states = self.chat_states.lock().unwrap();
66
let state = states.entry(chat_id.to_owned()).or_default();
67
state.id = chat_id.to_owned();
68
state.muted = !write.alerts;
69
state.notification_settings = Some(write.settings);
70
}
71
self.store.set_chat_muted(chat_id, !write.alerts)?;
72
let _ = self.events.send(CoreEvent::SidebarChanged);
73
Ok(())
74
}
75
}
76
77
#[cfg(test)]
78
mod tests {
79
use chatsvc::MessageDensity;
80
81
use super::*;
82
83
#[test]
84
fn the_document_survives_a_restart_in_the_store() {
85
let store = Store::open_in_memory().unwrap();
86
assert_eq!(stored_chat_settings(&store), ChatSettingsDocument::default());
87
let mut document = ChatSettingsDocument::default();
88
document.apply(ChatSettingChange::MessageDensity(MessageDensity::Compact));
89
store_chat_settings(&store, &document).unwrap();
90
assert_eq!(stored_chat_settings(&store), document);
91
}
92
}
@@ -0,0 +1,92 @@1
use chatsvc::{2
ChatNotificationMode, ChatSettingChange, ChatSettingsDocument, DesktopNotifications,3
};4
use store::Store;5
6
use crate::engine::SyncEngine;7
use crate::error::Result;8
use crate::events::CoreEvent;9
use crate::remote::Remote;10
11
const META_CHAT_SETTINGS: &str = "account.chat_settings";12
13
pub fn stored_chat_settings(store: &Store) -> ChatSettingsDocument {14
store15
.meta(META_CHAT_SETTINGS)16
.ok()17
.flatten()18
.map(|text| ChatSettingsDocument::from_text(&text))19
.unwrap_or_default()20
}21
22
pub fn store_chat_settings(store: &Store, document: &ChatSettingsDocument) -> Result<()> {23
Ok(store.set_meta(META_CHAT_SETTINGS, &document.to_text())?)24
}25
26
impl<R: Remote> SyncEngine<R> {27
pub async fn refresh_chat_settings(&self) -> Result<ChatSettingsDocument> {28
let document = self.remote.chat_settings().await?;29
store_chat_settings(&self.store, &document)?;30
Ok(document)31
}32
33
pub async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {34
let document = self.remote.save_chat_setting(change).await?;35
store_chat_settings(&self.store, &document)?;36
Ok(document)37
}38
39
pub fn chat_desktop_notifications(&self, chat_id: &str) -> DesktopNotifications {40
self.chat_states41
.lock()42
.unwrap()43
.get(chat_id)44
.map(|state| state.desktop_notifications())45
.unwrap_or_default()46
}47
48
pub async fn set_chat_notifications(49
&self,50
chat_id: &str,51
mode: ChatNotificationMode,52
desktop: DesktopNotifications,53
) -> Result<()> {54
let current = self55
.chat_states56
.lock()57
.unwrap()58
.get(chat_id)59
.and_then(|state| state.notification_settings.clone());60
let write = self61
.remote62
.set_chat_notifications(chat_id, current.as_deref(), mode, desktop)63
.await?;64
{65
let mut states = self.chat_states.lock().unwrap();66
let state = states.entry(chat_id.to_owned()).or_default();67
state.id = chat_id.to_owned();68
state.muted = !write.alerts;69
state.notification_settings = Some(write.settings);70
}71
self.store.set_chat_muted(chat_id, !write.alerts)?;72
let _ = self.events.send(CoreEvent::SidebarChanged);73
Ok(())74
}75
}76
77
#[cfg(test)]78
mod tests {79
use chatsvc::MessageDensity;80
81
use super::*;82
83
#[test]84
fn the_document_survives_a_restart_in_the_store() {85
let store = Store::open_in_memory().unwrap();86
assert_eq!(stored_chat_settings(&store), ChatSettingsDocument::default());87
let mut document = ChatSettingsDocument::default();88
document.apply(ChatSettingChange::MessageDensity(MessageDensity::Compact));89
store_chat_settings(&store, &document).unwrap();90
assert_eq!(stored_chat_settings(&store), document);91
}92
}@@ -13,6 +13,7 @@ mod card_widgets;
13
13
mod card_width;
14
14
mod channel_mentions;
15
15
mod channel_sync;
16
mod chat_settings_sync;
16
17
mod chat_paging;
17
18
mod download;
18
19
mod draft;
@@ -101,6 +102,12 @@ pub use chatsvc::{
101
102
ForwardResult, Gif, PinnedMessage, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
102
103
WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,
103
104
};
105
pub use chat_settings_sync::{store_chat_settings, stored_chat_settings};
106
pub use chatsvc::{
107
ActivityAlert, ChatAccountSettings, ChatNotificationMode, ChatSettingChange,
108
ChatSettingsDocument, DesktopNotifications, EnterKeyBehavior, MeetingChatNotifications,
109
MessageDensity, NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
110
};
104
111
pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};
105
112
pub use chatsvc::{
106
113
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,
@@ -13,6 +13,7 @@ mod card_widgets;13
mod card_width;13
mod card_width;14
mod channel_mentions;14
mod channel_mentions;15
mod channel_sync;15
mod channel_sync;16
mod chat_settings_sync;16
mod chat_paging;17
mod chat_paging;17
mod download;18
mod download;18
mod draft;19
mod draft;@@ -101,6 +102,12 @@ pub use chatsvc::{101
ForwardResult, Gif, PinnedMessage, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,102
ForwardResult, Gif, PinnedMessage, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,102
WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,103
WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,103
};104
};105
pub use chat_settings_sync::{store_chat_settings, stored_chat_settings};106
pub use chatsvc::{107
ActivityAlert, ChatAccountSettings, ChatNotificationMode, ChatSettingChange,108
ChatSettingsDocument, DesktopNotifications, EnterKeyBehavior, MeetingChatNotifications,109
MessageDensity, NotificationAccountSettings, NotificationPreset, UpArrowBehavior,110
};104
pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};111
pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};105
pub use chatsvc::{112
pub use chatsvc::{106
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,113
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,@@ -116,6 +116,7 @@ mod tests {
116
116
last_message_from: Some(format!("8:orgid:{from}")),
117
117
..ReadHorizon::default()
118
118
},
119
notification_settings: None,
119
120
}
120
121
}
121
122
@@ -116,6 +116,7 @@ mod tests {116
last_message_from: Some(format!("8:orgid:{from}")),116
last_message_from: Some(format!("8:orgid:{from}")),117
..ReadHorizon::default()117
..ReadHorizon::default()118
},118
},119
notification_settings: None,119
}120
}120
}121
}121
122
@@ -3,8 +3,9 @@ use chatsvc::substrate_search::{
3
3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
4
4
};
5
5
use chatsvc::{
6
ActivityFeed, AppConsumptionHorizon, MentionActivity, UserSettings,
7
parse_app_consumption_horizon,
6
ActivityFeed, AppConsumptionHorizon, ChatNotificationMode, ChatNotificationWrite,
7
ChatSettingChange, ChatSettingsClient, ChatSettingsDocument, DesktopNotifications,
8
MentionActivity, UserSettings, parse_app_consumption_horizon,
8
9
};
9
10
use chatsvc::{
10
11
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
@@ -470,6 +471,24 @@ pub trait Remote {
470
471
Err(Error::Unsupported("sound settings"))
471
472
}
472
473
474
async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
475
Err(Error::Unsupported("chat settings"))
476
}
477
478
async fn save_chat_setting(&self, _change: ChatSettingChange) -> Result<ChatSettingsDocument> {
479
Err(Error::Unsupported("chat settings"))
480
}
481
482
async fn set_chat_notifications(
483
&self,
484
_chat_id: &str,
485
_current_settings: Option<&str>,
486
_mode: ChatNotificationMode,
487
_desktop: DesktopNotifications,
488
) -> Result<ChatNotificationWrite> {
489
Err(Error::Unsupported("chat notifications"))
490
}
491
473
492
async fn save_sound_settings(
474
493
&self,
475
494
_user_mri: &str,
@@ -1223,6 +1242,26 @@ impl Remote for Graph {
1223
1242
Ok(SoundSettingsClient::new(self.session()).read().await?)
1224
1243
}
1225
1244
1245
async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
1246
Ok(ChatSettingsClient::new(self.session()).read().await?)
1247
}
1248
1249
async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {
1250
Ok(ChatSettingsClient::new(self.session()).write(change).await?)
1251
}
1252
1253
async fn set_chat_notifications(
1254
&self,
1255
chat_id: &str,
1256
current_settings: Option<&str>,
1257
mode: ChatNotificationMode,
1258
desktop: DesktopNotifications,
1259
) -> Result<ChatNotificationWrite> {
1260
Ok(Conversations::new(self.session())
1261
.set_chat_notifications(chat_id, current_settings, mode, desktop)
1262
.await?)
1263
}
1264
1226
1265
async fn save_sound_settings(
1227
1266
&self,
1228
1267
user_mri: &str,
@@ -3,8 +3,9 @@ use chatsvc::substrate_search::{3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,4
};4
};5
use chatsvc::{5
use chatsvc::{6
ActivityFeed, AppConsumptionHorizon, MentionActivity, UserSettings,6
ActivityFeed, AppConsumptionHorizon, ChatNotificationMode, ChatNotificationWrite,7
parse_app_consumption_horizon,7
ChatSettingChange, ChatSettingsClient, ChatSettingsDocument, DesktopNotifications,8
MentionActivity, UserSettings, parse_app_consumption_horizon,8
};9
};9
use chatsvc::{10
use chatsvc::{10
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,11
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,@@ -470,6 +471,24 @@ pub trait Remote {470
Err(Error::Unsupported("sound settings"))471
Err(Error::Unsupported("sound settings"))471
}472
}472
473
474
async fn chat_settings(&self) -> Result<ChatSettingsDocument> {475
Err(Error::Unsupported("chat settings"))476
}477
478
async fn save_chat_setting(&self, _change: ChatSettingChange) -> Result<ChatSettingsDocument> {479
Err(Error::Unsupported("chat settings"))480
}481
482
async fn set_chat_notifications(483
&self,484
_chat_id: &str,485
_current_settings: Option<&str>,486
_mode: ChatNotificationMode,487
_desktop: DesktopNotifications,488
) -> Result<ChatNotificationWrite> {489
Err(Error::Unsupported("chat notifications"))490
}491
473
async fn save_sound_settings(492
async fn save_sound_settings(474
&self,493
&self,475
_user_mri: &str,494
_user_mri: &str,@@ -1223,6 +1242,26 @@ impl Remote for Graph {1223
Ok(SoundSettingsClient::new(self.session()).read().await?)1242
Ok(SoundSettingsClient::new(self.session()).read().await?)1224
}1243
}1225
1244
1245
async fn chat_settings(&self) -> Result<ChatSettingsDocument> {1246
Ok(ChatSettingsClient::new(self.session()).read().await?)1247
}1248
1249
async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {1250
Ok(ChatSettingsClient::new(self.session()).write(change).await?)1251
}1252
1253
async fn set_chat_notifications(1254
&self,1255
chat_id: &str,1256
current_settings: Option<&str>,1257
mode: ChatNotificationMode,1258
desktop: DesktopNotifications,1259
) -> Result<ChatNotificationWrite> {1260
Ok(Conversations::new(self.session())1261
.set_chat_notifications(chat_id, current_settings, mode, desktop)1262
.await?)1263
}1264
1226
async fn save_sound_settings(1265
async fn save_sound_settings(1227
&self,1266
&self,1228
user_mri: &str,1267
user_mri: &str,@@ -584,6 +584,7 @@ impl Remote for Handle {
584
584
muted,
585
585
hidden: None,
586
586
read: chatsvc::ReadHorizon::default(),
587
notification_settings: None,
587
588
})
588
589
.collect();
589
590
states.extend(
@@ -594,6 +595,7 @@ impl Remote for Handle {
594
595
muted: false,
595
596
hidden: Some(hidden),
596
597
read: chatsvc::ReadHorizon::default(),
598
notification_settings: None,
597
599
}),
598
600
);
599
601
let read = self.read_states.lock().unwrap().clone();
@@ -604,6 +606,7 @@ impl Remote for Handle {
604
606
muted: false,
605
607
hidden: None,
606
608
read,
609
notification_settings: None,
607
610
}),
608
611
);
609
612
Ok(states)
@@ -584,6 +584,7 @@ impl Remote for Handle {584
muted,584
muted,585
hidden: None,585
hidden: None,586
read: chatsvc::ReadHorizon::default(),586
read: chatsvc::ReadHorizon::default(),587
notification_settings: None,587
})588
})588
.collect();589
.collect();589
states.extend(590
states.extend(@@ -594,6 +595,7 @@ impl Remote for Handle {594
muted: false,595
muted: false,595
hidden: Some(hidden),596
hidden: Some(hidden),596
read: chatsvc::ReadHorizon::default(),597
read: chatsvc::ReadHorizon::default(),598
notification_settings: None,597
}),599
}),598
);600
);599
let read = self.read_states.lock().unwrap().clone();601
let read = self.read_states.lock().unwrap().clone();@@ -604,6 +606,7 @@ impl Remote for Handle {604
muted: false,606
muted: false,605
hidden: None,607
hidden: None,606
read,608
read,609
notification_settings: None,607
}),610
}),608
);611
);609
Ok(states)612
Ok(states)