BlueGit

ict rusty-teams

Files

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

channel_notifications.rs

channel_notifications.rs 10.6 KiB Download Raw
1use std::collections::HashMap;
2
3use serde_json::{Value, json};
4use session::{Method, Request, Scope, Session};
5
6use crate::error::{Error, Result};
7use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
9pub const NSS_RESOURCE: &str = "https://uis.teams.microsoft.com";
10const NSS_SCOPE: &str = "user_impersonation";
11pub(crate) const PROPERTY_NAME: &str = "channelNotificationSettings";
12const NSS_BATCH_LIMIT: usize = 100;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum ChannelNotificationLevel {
16 BannerAndFeed,
17 #[default]
18 Feed,
19 Off,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub struct ChannelNotifications {
24 pub level: ChannelNotificationLevel,
25 pub include_replies: bool,
26}
27
28impl ChannelNotifications {
29 pub fn from_followed(followed: bool) -> Self {
30 if followed {
31 ChannelNotifications {
32 level: ChannelNotificationLevel::BannerAndFeed,
33 include_replies: true,
34 }
35 } else {
36 ChannelNotifications::default()
37 }
38 }
39
40 pub fn property_value(self) -> String {
41 let mut settings = match self.level {
42 ChannelNotificationLevel::BannerAndFeed => {
43 json!({"allNewPosts": "On", "dskNotif": "On"})
44 }
45 ChannelNotificationLevel::Feed => json!({"allNewPosts": "On"}),
46 ChannelNotificationLevel::Off => json!({"allNewPosts": "Off"}),
47 };
48 settings["includeReplies"] =
49 json!(self.include_replies && self.level != ChannelNotificationLevel::Off);
50 settings.to_string()
51 }
52}
53
54pub fn parse_property(raw: &str) -> Option<ChannelNotifications> {
55 let settings: Value = serde_json::from_str(raw).ok()?;
56 let level = match (
57 settings.get("allNewPosts").and_then(Value::as_str)?,
58 settings.get("dskNotif").and_then(Value::as_str),
59 ) {
60 ("On", Some("On")) => ChannelNotificationLevel::BannerAndFeed,
61 ("On", _) => ChannelNotificationLevel::Feed,
62 _ => ChannelNotificationLevel::Off,
63 };
64 Some(ChannelNotifications {
65 level,
66 include_replies: settings
67 .get("includeReplies")
68 .and_then(Value::as_bool)
69 .unwrap_or(false),
70 })
71}
72
73pub fn parse_nss_batch(body: &Value) -> HashMap<String, ChannelNotifications> {
74 body.get("results")
75 .and_then(Value::as_array)
76 .into_iter()
77 .flatten()
78 .filter_map(|result| {
79 let settings = result
80 .get("settings")
81 .filter(|settings| settings.is_object())?;
82 let level = match settings.get("allNewPosts").and_then(Value::as_str)? {
83 "BannerAndFeed" => ChannelNotificationLevel::BannerAndFeed,
84 "Feed" => ChannelNotificationLevel::Feed,
85 _ => ChannelNotificationLevel::Off,
86 };
87 Some((
88 result.get("channelId")?.as_str()?.to_owned(),
89 ChannelNotifications {
90 level,
91 include_replies: settings
92 .get("includeReplies")
93 .and_then(Value::as_bool)
94 .unwrap_or(false),
95 },
96 ))
97 })
98 .collect()
99}
100
101pub struct ChannelSettings<T: CsaTransport = SessionTransport> {
102 transport: T,
103 url: String,
104}
105
106impl ChannelSettings<SessionTransport> {
107 pub fn new(session: &Session) -> Self {
108 ChannelSettings::with_transport(
109 SessionTransport::with_scope(session, Scope::new(NSS_RESOURCE, NSS_SCOPE)),
110 DEFAULT_REGION,
111 )
112 }
113}
114
115impl<T: CsaTransport> ChannelSettings<T> {
116 pub fn with_transport(transport: T, region: &str) -> Self {
117 ChannelSettings {
118 transport,
119 url: format!(
120 "https://teams.cloud.microsoft/api/nss/{region}/v1/me/notificationSettings/channels/batch"
121 ),
122 }
123 }
124
125 pub async fn fetch(
126 &self,
127 channel_ids: &[String],
128 ) -> Result<HashMap<String, ChannelNotifications>> {
129 let mut settings = HashMap::new();
130 for batch in channel_ids.chunks(NSS_BATCH_LIMIT) {
131 let answer = self
132 .transport
133 .send(Request::with_body(
134 Method::Post,
135 &self.url,
136 json!({"channelIds": batch}),
137 ))
138 .await?;
139 if !answer.is_success() {
140 return Err(Error::UnexpectedAnswer(format!(
141 "channel settings answered {}",
142 answer.status
143 )));
144 }
145 settings.extend(parse_nss_batch(&answer.body));
146 }
147 Ok(settings)
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use std::collections::VecDeque;
154 use std::sync::Mutex;
155
156 use session::ApiResponse;
157
158 use super::*;
159 use crate::conversations::Conversations;
160 use crate::messages::MessageTransport;
161
162 struct Canned {
163 answers: Mutex<VecDeque<(u16, Value)>>,
164 requests: Mutex<Vec<Request>>,
165 }
166
167 impl CsaTransport for &Canned {
168 async fn send(&self, request: Request) -> Result<ApiResponse> {
169 self.requests.lock().unwrap().push(request);
170 let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
171 Ok(ApiResponse {
172 status,
173 body,
174 retry_after: None,
175 })
176 }
177 }
178
179 impl MessageTransport for &Canned {
180 async fn send(&self, request: Request) -> Result<ApiResponse> {
181 CsaTransport::send(self, request).await
182 }
183 }
184
185 fn canned(answers: Vec<(u16, Value)>) -> Canned {
186 Canned {
187 answers: Mutex::new(answers.into()),
188 requests: Mutex::new(Vec::new()),
189 }
190 }
191
192 #[test]
193 fn property_maps_the_three_levels() {
194 let banner =
195 parse_property(r#"{"allNewPosts":"On","dskNotif":"On","includeReplies":true}"#);
196 assert_eq!(
197 banner,
198 Some(ChannelNotifications {
199 level: ChannelNotificationLevel::BannerAndFeed,
200 include_replies: true
201 })
202 );
203 let feed = parse_property(r#"{"allNewPosts":"On","latestCnsVersion":1}"#).unwrap();
204 assert_eq!(feed.level, ChannelNotificationLevel::Feed);
205 assert!(!feed.include_replies);
206 let off = parse_property(r#"{"allNewPosts":"Off","includeReplies":false}"#).unwrap();
207 assert_eq!(off.level, ChannelNotificationLevel::Off);
208 }
209
210 #[test]
211 fn unreadable_property_is_missing() {
212 assert_eq!(parse_property("not json"), None);
213 assert_eq!(parse_property(r#"{"includeReplies":true}"#), None);
214 }
215
216 #[test]
217 fn followed_without_a_value_means_banner_with_replies() {
218 assert_eq!(
219 ChannelNotifications::from_followed(true),
220 ChannelNotifications {
221 level: ChannelNotificationLevel::BannerAndFeed,
222 include_replies: true
223 }
224 );
225 assert_eq!(
226 ChannelNotifications::from_followed(false).level,
227 ChannelNotificationLevel::Feed
228 );
229 }
230
231 #[test]
232 fn nss_batch_skips_channels_without_settings() {
233 let body = json!({"results": [
234 {"channelId": "19:a", "success": true, "settings": {"allNewPosts": "BannerAndFeed", "includeReplies": true}},
235 {"channelId": "19:b", "success": true, "settings": {"allNewPosts": "Feed"}},
236 {"channelId": "19:c", "success": true, "settings": {"allNewPosts": "Off"}},
237 {"channelId": "19:d", "success": true, "settings": null},
238 {"channelId": "19:e", "success": false, "settings": null, "errorMessage": "x"},
239 ]});
240 let parsed = parse_nss_batch(&body);
241 assert_eq!(parsed.len(), 3);
242 assert_eq!(
243 parsed["19:a"].level,
244 ChannelNotificationLevel::BannerAndFeed
245 );
246 assert!(parsed["19:a"].include_replies);
247 assert_eq!(parsed["19:b"].level, ChannelNotificationLevel::Feed);
248 assert_eq!(parsed["19:c"].level, ChannelNotificationLevel::Off);
249 }
250
251 #[tokio::test]
252 async fn fetch_splits_into_batches_of_one_hundred() {
253 let transport = canned(vec![
254 (200, json!({"results": []})),
255 (200, json!({"results": []})),
256 ]);
257 let ids: Vec<String> = (0..101).map(|index| format!("19:{index}")).collect();
258 ChannelSettings::with_transport(&transport, "emea")
259 .fetch(&ids)
260 .await
261 .unwrap();
262 let requests = transport.requests.lock().unwrap();
263 let sizes: Vec<usize> = requests
264 .iter()
265 .map(|request| {
266 request.body.as_ref().unwrap()["channelIds"]
267 .as_array()
268 .unwrap()
269 .len()
270 })
271 .collect();
272 assert_eq!(sizes, [100, 1]);
273 }
274
275 #[tokio::test]
276 async fn write_puts_the_settings_as_a_json_string() {
277 let transport = canned(vec![
278 (200, Value::Null),
279 (200, Value::Null),
280 (200, Value::Null),
281 ]);
282 let conversations = Conversations::with_transport(&transport, "emea");
283 for (level, include_replies) in [
284 (ChannelNotificationLevel::BannerAndFeed, false),
285 (ChannelNotificationLevel::Feed, true),
286 (ChannelNotificationLevel::Off, true),
287 ] {
288 conversations
289 .set_channel_notifications(
290 "19:a@thread.tacv2",
291 ChannelNotifications {
292 level,
293 include_replies,
294 },
295 )
296 .await
297 .unwrap();
298 }
299 let requests = transport.requests.lock().unwrap();
300 assert_eq!(requests[0].method, Method::Put);
301 assert_eq!(
302 requests[0].url,
303 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Aa%40thread.tacv2/properties?name=channelNotificationSettings"
304 );
305 assert_eq!(
306 requests[0].body,
307 Some(
308 json!({"channelNotificationSettings": "{\"allNewPosts\":\"On\",\"dskNotif\":\"On\",\"includeReplies\":false}"})
309 )
310 );
311 assert_eq!(
312 requests[1].body,
313 Some(
314 json!({"channelNotificationSettings": "{\"allNewPosts\":\"On\",\"includeReplies\":true}"})
315 )
316 );
317 assert_eq!(
318 requests[2].body,
319 Some(
320 json!({"channelNotificationSettings": "{\"allNewPosts\":\"Off\",\"includeReplies\":false}"})
321 )
322 );
323 }
324}