| 1 | use serde_json::Value; |
| 2 | use session::Scope; |
| 3 | |
| 4 | use crate::client::Graph; |
| 5 | use crate::error::Result; |
| 6 | use crate::urls; |
| 7 | |
| 8 | const TABS_SCOPE: &str = "TeamsTab.ReadWrite.All"; |
| 9 | const MEMBERS_SCOPE: &str = "ChannelMember.Read.All"; |
| 10 | |
| 11 | fn web_url(tab: &Value) -> Option<String> { |
| 12 | tab.get("webUrl") |
| 13 | .and_then(Value::as_str) |
| 14 | .filter(|url| url.starts_with("https://")) |
| 15 | .map(str::to_owned) |
| 16 | } |
| 17 | |
| 18 | impl Graph { |
| 19 | pub async fn channel_tab_web_url( |
| 20 | &self, |
| 21 | team_id: &str, |
| 22 | channel_id: &str, |
| 23 | tab_id: &str, |
| 24 | ) -> Result<Option<String>> { |
| 25 | let tab = self |
| 26 | .get( |
| 27 | &urls::channel_tab(team_id, channel_id, tab_id), |
| 28 | &Scope::graph(TABS_SCOPE), |
| 29 | ) |
| 30 | .await?; |
| 31 | Ok(web_url(&tab)) |
| 32 | } |
| 33 | |
| 34 | pub async fn channel_member_count(&self, team_id: &str, channel_id: &str) -> Result<usize> { |
| 35 | let members: Vec<Value> = self |
| 36 | .get_all( |
| 37 | &urls::channel_members(team_id, channel_id), |
| 38 | Scope::graph(MEMBERS_SCOPE), |
| 39 | ) |
| 40 | .await?; |
| 41 | Ok(members.len()) |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | #[cfg(test)] |
| 46 | mod tests { |
| 47 | use serde_json::json; |
| 48 | |
| 49 | use super::*; |
| 50 | |
| 51 | #[test] |
| 52 | fn the_tab_deep_link_is_its_web_url() { |
| 53 | let tab = json!({"id": "t1", "displayName": "Plan", "webUrl": "https://teams.microsoft.com/l/channel/19%3Ac/tab%3A%3At1?groupId=g&tenantId=t"}); |
| 54 | assert_eq!( |
| 55 | web_url(&tab).as_deref(), |
| 56 | Some("https://teams.microsoft.com/l/channel/19%3Ac/tab%3A%3At1?groupId=g&tenantId=t") |
| 57 | ); |
| 58 | } |
| 59 | |
| 60 | #[test] |
| 61 | fn a_tab_without_a_usable_web_url_has_none() { |
| 62 | assert_eq!(web_url(&json!({"id": "t1"})), None); |
| 63 | assert_eq!(web_url(&json!({"webUrl": "javascript:alert(1)"})), None); |
| 64 | } |
| 65 | |
| 66 | #[test] |
| 67 | fn the_tab_url_names_team_channel_and_tab() { |
| 68 | assert_eq!( |
| 69 | urls::channel_tab("team", "19:c@thread.tacv2", "tab-1"), |
| 70 | "https://graph.microsoft.com/v1.0/teams/team/channels/19%3Ac%40thread.tacv2/tabs/tab-1" |
| 71 | ); |
| 72 | } |
| 73 | } |