BlueGit

ict rusty-teams

Files

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

teams.rs

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