BlueGit

ict rusty-teams

Files

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

teams.rs

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