BlueGit

ict rusty-teams

Files

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

teams.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
teams.rs 13.9 KiB Download Raw
1use percent_encoding::percent_decode_str;
2use serde_json::Value;
3use session::Request;
4
5use super::Pins;
6use super::chats::ensure_success;
7use super::transport::CsaTransport;
8use crate::channel_notifications::{ChannelNotifications, parse_property};
9use crate::error::{Error, Result};
10
11const TEAMS_QUERY: &str = "isPrefetch=false&enableMembershipSummary=true";
12const WIKI_DEFINITION_ID: &str = "com.microsoft.teamspace.tab.wiki";
13const TAB_URL_KEYS: [&str; 3] = ["websiteUrl", "componentUrl", "url"];
14const OWNER_ROLE: i64 = 2;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct ChannelTab {
18 pub id: String,
19 pub name: String,
20 pub definition_id: String,
21 pub open_url: Option<String>,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct ChannelLayout {
26 pub channel_id: String,
27 pub general: bool,
28 pub hidden: bool,
29 pub tabs: Vec<ChannelTab>,
30 pub notifications: Option<ChannelNotifications>,
31 pub followed: bool,
32 pub substrate_group_id: Option<String>,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub struct TeamRights {
37 pub owner: bool,
38 pub add_channel: bool,
39 pub add_private_channel: bool,
40 pub edit_channel: bool,
41 pub delete_channel: bool,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct TeamLayout {
46 pub team_id: String,
47 pub group_id: Option<String>,
48 pub hidden: bool,
49 pub rights: TeamRights,
50 pub channels: Vec<ChannelLayout>,
51}
52
53impl<T: CsaTransport> Pins<T> {
54 pub async fn team_layout(&self) -> Result<Vec<TeamLayout>> {
55 let answer = self
56 .transport
57 .send(Request::get(format!("{}?{TEAMS_QUERY}", self.base_url)))
58 .await?;
59 ensure_success(&answer)?;
60 parse_team_layout(&answer.body)
61 }
62}
63
64pub fn parse_team_layout(body: &Value) -> Result<Vec<TeamLayout>> {
65 let teams = body
66 .get("teams")
67 .and_then(Value::as_array)
68 .ok_or_else(|| Error::UnexpectedAnswer("teams missing".into()))?;
69 Ok(teams.iter().filter_map(parse_team).collect())
70}
71
72fn flag(value: &Value, key: &str) -> Option<bool> {
73 value.get(key).and_then(Value::as_bool)
74}
75
76fn tab_open_url(settings: &Value) -> Option<String> {
77 TAB_URL_KEYS
78 .iter()
79 .filter_map(|key| settings.get(key).and_then(Value::as_str))
80 .map(str::trim)
81 .find(|url| url.starts_with("http") && !url.contains('{'))
82 .map(str::to_owned)
83}
84
85fn decode_tab_name(name: &str) -> String {
86 percent_decode_str(name)
87 .decode_utf8()
88 .map_or_else(|_| name.to_owned(), |decoded| decoded.into_owned())
89}
90
91fn parse_tab(tab: &Value) -> Option<(i64, ChannelTab)> {
92 let definition_id = tab.get("definitionId")?.as_str()?;
93 if definition_id == WIKI_DEFINITION_ID {
94 return None;
95 }
96 let order = tab
97 .get("order")
98 .and_then(|order| order.as_i64().or_else(|| order.as_str()?.parse().ok()))
99 .unwrap_or(i64::MAX);
100 let settings = tab.get("settings").unwrap_or(&Value::Null);
101 Some((
102 order,
103 ChannelTab {
104 id: tab.get("id")?.as_str()?.to_owned(),
105 name: decode_tab_name(tab.get("name")?.as_str()?),
106 definition_id: definition_id.to_owned(),
107 open_url: tab_open_url(settings),
108 },
109 ))
110}
111
112pub fn parse_channel_tabs(channel: &Value) -> Vec<ChannelTab> {
113 let mut tabs: Vec<(i64, ChannelTab)> = channel
114 .get("tabs")
115 .and_then(Value::as_array)
116 .map(|tabs| tabs.iter().filter_map(parse_tab).collect())
117 .unwrap_or_default();
118 tabs.sort_by_key(|(order, _)| *order);
119 tabs.into_iter().map(|(_, tab)| tab).collect()
120}
121
122pub fn parse_team_rights(team: &Value) -> TeamRights {
123 if flag(team, "channelOnlyMember") == Some(true) || flag(team, "isArchived") == Some(true) {
124 return TeamRights::default();
125 }
126 let owner = team.get("memberRole").and_then(Value::as_i64) == Some(OWNER_ROLE);
127 let settings = team.get("teamSettings").unwrap_or(&Value::Null);
128 let allowed = |key: &str| owner || flag(settings, key) == Some(true);
129 TeamRights {
130 owner,
131 add_channel: allowed("createTopic"),
132 add_private_channel: allowed("isPrivateChannelCreationEnabled"),
133 edit_channel: allowed("updateTopic"),
134 delete_channel: allowed("deleteTopic"),
135 }
136}
137
138fn parse_team(team: &Value) -> Option<TeamLayout> {
139 if flag(team, "isDeleted") == Some(true) {
140 return None;
141 }
142 let general_shown = flag(team, "isGeneralChannelFavorite").unwrap_or(true);
143 let channels = team
144 .get("channels")
145 .and_then(Value::as_array)
146 .map(|channels| {
147 channels
148 .iter()
149 .filter(|channel| flag(channel, "isDeleted") != Some(true))
150 .filter_map(|channel| {
151 let general = flag(channel, "isGeneral").unwrap_or(false);
152 let shown = if general {
153 general_shown
154 } else {
155 flag(channel, "isFavorite").unwrap_or(true)
156 };
157 Some(ChannelLayout {
158 channel_id: channel.get("id")?.as_str()?.to_owned(),
159 general,
160 hidden: !shown,
161 tabs: parse_channel_tabs(channel),
162 notifications: channel
163 .get("channelNotificationSettings")
164 .and_then(Value::as_str)
165 .and_then(parse_property),
166 followed: flag(channel, "isFollowed").unwrap_or(false),
167 substrate_group_id: channel
168 .get("substrateGroupId")
169 .and_then(Value::as_str)
170 .map(str::to_owned),
171 })
172 })
173 .collect()
174 })
175 .unwrap_or_default();
176 Some(TeamLayout {
177 team_id: team.get("id")?.as_str()?.to_owned(),
178 group_id: team
179 .get("teamSiteInformation")
180 .and_then(|site| site.get("groupId"))
181 .and_then(Value::as_str)
182 .map(str::to_owned),
183 hidden: flag(team, "isFavorite") == Some(false),
184 rights: parse_team_rights(team),
185 channels,
186 })
187}
188
189#[cfg(test)]
190mod tests {
191 use serde_json::json;
192
193 use super::*;
194
195 #[test]
196 fn general_visibility_follows_the_team_flag_only() {
197 let body = json!({"teams": [
198 {"id": "19:a@thread.tacv2", "isGeneralChannelFavorite": false, "channels": [
199 {"id": "19:a@thread.tacv2", "isGeneral": true, "isFavorite": true}
200 ]},
201 {"id": "19:b@thread.tacv2", "isGeneralChannelFavorite": true, "channels": [
202 {"id": "19:b@thread.tacv2", "isGeneral": true, "isFavorite": false}
203 ]},
204 {"id": "19:c@thread.tacv2", "channels": [
205 {"id": "19:c@thread.tacv2", "isGeneral": true, "isFavorite": false}
206 ]}
207 ]});
208 let layout = parse_team_layout(&body).unwrap();
209 assert!(layout[0].channels[0].hidden);
210 assert!(!layout[1].channels[0].hidden);
211 assert!(!layout[2].channels[0].hidden);
212 }
213
214 #[test]
215 fn members_get_the_rights_the_team_settings_grant() {
216 let settings = json!({"createTopic": true, "isPrivateChannelCreationEnabled": false,
217 "updateTopic": true, "deleteTopic": false});
218 let member = json!({"memberRole": 1, "teamSettings": settings});
219 assert_eq!(
220 parse_team_rights(&member),
221 TeamRights {
222 owner: false,
223 add_channel: true,
224 add_private_channel: false,
225 edit_channel: true,
226 delete_channel: false,
227 }
228 );
229 let owner = json!({"memberRole": 2, "teamSettings": {}});
230 let owner_rights = parse_team_rights(&owner);
231 assert!(
232 owner_rights.owner && owner_rights.add_private_channel && owner_rights.delete_channel
233 );
234 let archived = json!({"memberRole": 2, "isArchived": true});
235 assert_eq!(parse_team_rights(&archived), TeamRights::default());
236 let channel_only =
237 json!({"memberRole": 1, "channelOnlyMember": true, "teamSettings": settings});
238 assert_eq!(parse_team_rights(&channel_only), TeamRights::default());
239 }
240
241 #[test]
242 fn reads_the_group_id_the_graph_team_id_uses() {
243 let body = json!({"teams": [
244 {"id": "19:a@thread.skype", "teamSiteInformation": {"groupId": "group-a"}, "channels": []},
245 {"id": "19:b@thread.tacv2", "channels": []}
246 ]});
247 let layout = parse_team_layout(&body).unwrap();
248 assert_eq!(layout[0].group_id.as_deref(), Some("group-a"));
249 assert_eq!(layout[1].group_id, None);
250 }
251
252 #[test]
253 fn keeps_the_service_order_and_reads_hidden_flags() {
254 let body = json!({"teams": [
255 {"id": "19:b@thread.tacv2", "isFavorite": true, "channels": [
256 {"id": "19:b2@thread.tacv2", "isFavorite": false},
257 {"id": "19:b@thread.tacv2", "isGeneral": true, "isFavorite": true}
258 ]},
259 {"id": "19:gone@thread.tacv2", "isDeleted": true, "channels": []},
260 {"id": "19:a@thread.tacv2", "isFavorite": false, "isGeneralChannelFavorite": false, "channels": [
261 {"id": "19:a@thread.tacv2", "isGeneral": true},
262 {"id": "19:a2@thread.tacv2"}
263 ]}
264 ]});
265 let layout = parse_team_layout(&body).unwrap();
266 let ids: Vec<&str> = layout.iter().map(|team| team.team_id.as_str()).collect();
267 assert_eq!(ids, ["19:b@thread.tacv2", "19:a@thread.tacv2"]);
268 assert!(!layout[0].hidden);
269 assert!(layout[1].hidden);
270 assert_eq!(
271 layout[0].channels,
272 [
273 ChannelLayout {
274 channel_id: "19:b2@thread.tacv2".into(),
275 general: false,
276 hidden: true,
277 tabs: Vec::new(),
278 notifications: None,
279 followed: false,
280 substrate_group_id: None,
281 },
282 ChannelLayout {
283 channel_id: "19:b@thread.tacv2".into(),
284 general: true,
285 hidden: false,
286 tabs: Vec::new(),
287 notifications: None,
288 followed: false,
289 substrate_group_id: None,
290 },
291 ]
292 );
293 assert!(layout[1].channels[0].hidden);
294 assert!(!layout[1].channels[1].hidden);
295 }
296
297 #[test]
298 fn tabs_follow_the_order_field_and_hide_wiki() {
299 let channel = json!({"id": "19:a@thread.tacv2", "tabs": [
300 {"id": "t3", "name": "Notes", "definitionId": "0d820ecd-def2-4297-adad-78056cde7c78",
301 "order": 30, "settings": {
302 "url": "https://onenote.example/{tid}/content",
303 "websiteUrl": "https://onenote.example/web"}},
304 {"id": "t0", "name": "Wiki", "definitionId": "com.microsoft.teamspace.tab.wiki", "order": 5},
305 {"id": "t1", "name": "Docs", "definitionId": "com.microsoft.teamspace.tab.web",
306 "order": 10, "settings": {"url": "https://docs.example", "websiteUrl": "https://docs.example"}},
307 {"id": "t2", "name": "Plan", "definitionId": "com.microsoft.teamspace.tab.planner",
308 "order": "20", "settings": {"url": "https://tasks.example/{locale}"}}
309 ]});
310 let tabs = parse_channel_tabs(&channel);
311 let names: Vec<&str> = tabs.iter().map(|tab| tab.name.as_str()).collect();
312 assert_eq!(names, ["Docs", "Plan", "Notes"]);
313 assert_eq!(tabs[0].open_url.as_deref(), Some("https://docs.example"));
314 assert_eq!(tabs[1].open_url, None);
315 assert_eq!(
316 tabs[2].open_url.as_deref(),
317 Some("https://onenote.example/web")
318 );
319 }
320
321 #[test]
322 fn reads_the_notification_string_and_the_followed_flag() {
323 let body = json!({"teams": [
324 {"id": "19:a@thread.tacv2", "channels": [
325 {"id": "19:a1", "channelNotificationSettings": "{\"allNewPosts\":\"On\",\"dskNotif\":\"On\",\"includeReplies\":true}", "isFollowed": true},
326 {"id": "19:a2", "channelNotificationSettings": null, "isFollowed": true},
327 {"id": "19:a3"}
328 ]}
329 ]});
330 let channels = &parse_team_layout(&body).unwrap()[0].channels;
331 assert_eq!(
332 channels[0].notifications,
333 Some(ChannelNotifications {
334 level: crate::ChannelNotificationLevel::BannerAndFeed,
335 include_replies: true
336 })
337 );
338 assert_eq!(
339 (channels[1].notifications, channels[1].followed),
340 (None, true)
341 );
342 assert_eq!(
343 (channels[2].notifications, channels[2].followed),
344 (None, false)
345 );
346 }
347
348 #[test]
349 fn percent_encoded_tab_names_are_decoded() {
350 let channel = json!({"id": "19:a@thread.tacv2", "tabs": [
351 {"id": "t1", "name": "Lunch%20Order%20Board%20%F0%9F%8D%BD%EF%B8%8F",
352 "definitionId": "com.microsoft.teamspace.tab.web", "order": 1},
353 {"id": "t2", "name": "100% done", "definitionId": "com.microsoft.teamspace.tab.web", "order": 2},
354 {"id": "t3", "name": "Bad%FFbytes", "definitionId": "com.microsoft.teamspace.tab.web", "order": 3}
355 ]});
356 let names: Vec<String> = parse_channel_tabs(&channel)
357 .into_iter()
358 .map(|tab| tab.name)
359 .collect();
360 assert_eq!(
361 names,
362 [
363 "Lunch Order Board \u{1F37D}\u{FE0F}",
364 "100% done",
365 "Bad%FFbytes"
366 ]
367 );
368 }
369
370 #[test]
371 fn a_channel_without_tabs_has_none() {
372 assert!(parse_channel_tabs(&json!({"id": "19:a@thread.tacv2"})).is_empty());
373 }
374
375 #[test]
376 fn rejects_an_answer_without_teams() {
377 assert!(parse_team_layout(&json!({"chats": []})).is_err());
378 }
379}