| 1 | use serde_json::{Value, json}; |
| 2 | use session::{Method, PRESENCE, Request, Scope, Session}; |
| 3 | use uuid::Uuid; |
| 4 | |
| 5 | use crate::error::Result; |
| 6 | |
| 7 | pub const MAX_PRESENCE_IDS: usize = 650; |
| 8 | pub const MAX_SUBSCRIBE_IDS: usize = 200; |
| 9 | const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/"; |
| 10 | const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation"; |
| 11 | const PRESENCE_SUBSCRIBE_URL: &str = |
| 12 | "https://presence.teams.microsoft.com/v1/pubsub/subscriptions/"; |
| 13 | const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213"; |
| 14 | const ORGID_PREFIX: &str = "8:orgid:"; |
| 15 | |
| 16 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 17 | pub struct UserPresence { |
| 18 | pub user_id: String, |
| 19 | pub availability: String, |
| 20 | pub activity: Option<String>, |
| 21 | } |
| 22 | |
| 23 | pub struct PresenceLookup { |
| 24 | session: Session, |
| 25 | } |
| 26 | |
| 27 | impl PresenceLookup { |
| 28 | pub fn new(session: &Session) -> Self { |
| 29 | PresenceLookup { |
| 30 | session: session.clone(), |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | /// Graph `Presence.Read.All` is not in the web app tokens. |
| 35 | pub async fn presences(&self, user_ids: &[String]) -> Result<Vec<UserPresence>> { |
| 36 | let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE); |
| 37 | let mut presences = Vec::with_capacity(user_ids.len()); |
| 38 | for chunk in user_ids.chunks(MAX_PRESENCE_IDS) { |
| 39 | let body: Vec<Value> = chunk |
| 40 | .iter() |
| 41 | .map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}")})) |
| 42 | .collect(); |
| 43 | let answer = self |
| 44 | .session |
| 45 | .request( |
| 46 | Method::Post, |
| 47 | PRESENCE_SERVICE_URL, |
| 48 | &scope, |
| 49 | Some(Value::Array(body)), |
| 50 | ) |
| 51 | .await?; |
| 52 | presences.extend(parse_service_presences(&answer.body)); |
| 53 | } |
| 54 | Ok(presences) |
| 55 | } |
| 56 | |
| 57 | pub async fn subscribe( |
| 58 | &self, |
| 59 | endpoint_id: &str, |
| 60 | trouter_uri: &str, |
| 61 | user_ids: &[String], |
| 62 | purge: bool, |
| 63 | ) -> Result<()> { |
| 64 | let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE); |
| 65 | let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}"); |
| 66 | for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() { |
| 67 | let request = Request { |
| 68 | method: Method::Post, |
| 69 | headers: subscribe_headers(endpoint_id), |
| 70 | body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)), |
| 71 | ..Request::get(url.clone()) |
| 72 | }; |
| 73 | let answer = self.session.send(request, &scope).await?; |
| 74 | if !(200..300).contains(&answer.status) { |
| 75 | return Err(session::Error::api(answer.status, &url, answer.body).into()); |
| 76 | } |
| 77 | } |
| 78 | Ok(()) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // The service answers 400 naming each of the three x-ms-* client headers when one is missing. |
| 83 | fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> { |
| 84 | vec![ |
| 85 | ("x-ms-client-user-agent".into(), "Teams-V2-Web".into()), |
| 86 | ("x-ms-correlation-id".into(), Uuid::new_v4().to_string()), |
| 87 | ("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()), |
| 88 | ("x-ms-endpoint-id".into(), endpoint_id.into()), |
| 89 | ("x-ms-client-type".into(), "cdlworker".into()), |
| 90 | ] |
| 91 | } |
| 92 | |
| 93 | fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value { |
| 94 | let additions: Vec<Value> = user_ids |
| 95 | .iter() |
| 96 | .map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"})) |
| 97 | .collect(); |
| 98 | json!({ |
| 99 | "trouterUri": trouter_uri, |
| 100 | "shouldPurgePreviousSubscriptions": purge, |
| 101 | "subscriptionsToAdd": additions, |
| 102 | "subscriptionsToRemove": [], |
| 103 | }) |
| 104 | } |
| 105 | |
| 106 | fn parse_service_presences(body: &Value) -> Vec<UserPresence> { |
| 107 | body.as_array() |
| 108 | .into_iter() |
| 109 | .flatten() |
| 110 | .filter_map(|entry| { |
| 111 | let mri = entry.get("mri")?.as_str()?; |
| 112 | let presence = entry.get("presence")?; |
| 113 | Some(UserPresence { |
| 114 | user_id: mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned(), |
| 115 | availability: presence.get("availability")?.as_str()?.to_owned(), |
| 116 | activity: if presence |
| 117 | .pointer("/calendarData/isOutOfOffice") |
| 118 | .and_then(Value::as_bool) |
| 119 | .unwrap_or(false) |
| 120 | { |
| 121 | Some("OutOfOffice".to_owned()) |
| 122 | } else { |
| 123 | presence |
| 124 | .get("activity") |
| 125 | .and_then(Value::as_str) |
| 126 | .map(str::to_owned) |
| 127 | }, |
| 128 | }) |
| 129 | }) |
| 130 | .collect() |
| 131 | } |
| 132 | |
| 133 | #[cfg(test)] |
| 134 | mod tests { |
| 135 | use super::*; |
| 136 | |
| 137 | #[test] |
| 138 | fn subscribe_body_carries_mris_and_purge_flag() { |
| 139 | let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true); |
| 140 | assert_eq!( |
| 141 | body, |
| 142 | json!({ |
| 143 | "trouterUri": "https://t/unifiedPresenceService", |
| 144 | "shouldPurgePreviousSubscriptions": true, |
| 145 | "subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}], |
| 146 | "subscriptionsToRemove": [], |
| 147 | }) |
| 148 | ); |
| 149 | } |
| 150 | |
| 151 | #[test] |
| 152 | fn subscribe_headers_use_a_fresh_correlation_id() { |
| 153 | let correlation = |headers: &[(String, String)]| { |
| 154 | headers |
| 155 | .iter() |
| 156 | .find(|(name, _)| name == "x-ms-correlation-id") |
| 157 | .map(|(_, value)| value.clone()) |
| 158 | }; |
| 159 | let first = subscribe_headers("e"); |
| 160 | assert_ne!(correlation(&first), correlation(&subscribe_headers("e"))); |
| 161 | assert!( |
| 162 | first |
| 163 | .iter() |
| 164 | .any(|(name, value)| name == "x-ms-endpoint-id" && value == "e") |
| 165 | ); |
| 166 | } |
| 167 | |
| 168 | #[test] |
| 169 | fn service_presences_strip_the_mri_prefix() { |
| 170 | let parsed = parse_service_presences(&json!([ |
| 171 | {"mri": "8:orgid:a", "presence": {"availability": "Away", "activity": "Away"}}, |
| 172 | {"mri": "8:orgid:b"} |
| 173 | ])); |
| 174 | assert_eq!(parsed.len(), 1); |
| 175 | assert_eq!(parsed[0].user_id, "a"); |
| 176 | } |
| 177 | |
| 178 | #[test] |
| 179 | fn out_of_office_from_the_calendar_becomes_the_activity() { |
| 180 | let parsed = parse_service_presences(&json!([ |
| 181 | {"mri": "8:orgid:a", "presence": {"availability": "Offline", "activity": "OffWork", "calendarData": {"isOutOfOffice": true}}}, |
| 182 | {"mri": "8:orgid:b", "presence": {"availability": "Available", "activity": "Available", "calendarData": {"isOutOfOffice": false}}} |
| 183 | ])); |
| 184 | assert_eq!(parsed[0].activity.as_deref(), Some("OutOfOffice")); |
| 185 | assert_eq!(parsed[1].activity.as_deref(), Some("Available")); |
| 186 | } |
| 187 | } |