BlueGit

ict rusty-teams

Files

rusty-teams / crates / graph / src / people.rs

people.rs

people.rs 8.0 KiB Download Raw
1use base64::Engine as _;
2use base64::engine::general_purpose::STANDARD;
3use serde::Deserialize;
4use serde_json::{Value, json};
5use session::{ApiResponse, Method, PRESENCE, Request, Scope};
6use uuid::Uuid;
7
8use crate::client::{BATCH_SIZE, Graph};
9use crate::error::{Error, Result};
10use crate::models::{Photo, Presence};
11use crate::urls;
12
13pub const MAX_PRESENCE_IDS: usize = 650;
14pub const MAX_SUBSCRIBE_IDS: usize = 200;
15const PHOTO_SCOPE: &str = "User.ReadBasic.All";
16const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/";
17const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation";
18const PRESENCE_SUBSCRIBE_URL: &str =
19 "https://presence.teams.microsoft.com/v1/pubsub/subscriptions/";
20const PRESENCE_CLIENT_VERSION: &str = "1415/26091712213";
21const ORGID_PREFIX: &str = "8:orgid:";
22
23#[derive(Debug, Deserialize)]
24struct BinaryBody {
25 base64: String,
26 #[serde(rename = "contentType")]
27 content_type: Option<String>,
28}
29
30impl Graph {
31 /// `Ok(None)` for users without a photo (404).
32 pub async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
33 let scope = Scope::graph(PHOTO_SCOPE);
34 let mut photos = Vec::with_capacity(user_ids.len());
35 for chunk in user_ids.chunks(BATCH_SIZE) {
36 let requests: Vec<Request> = chunk
37 .iter()
38 .map(|user_id| Request::binary_get(urls::user_photo(user_id)))
39 .collect();
40 let answers = self.session().batch(&requests, &scope).await?;
41 photos.extend(
42 requests
43 .iter()
44 .zip(answers)
45 .map(|(request, answer)| parse_photo(&request.url, answer)),
46 );
47 }
48 Ok(photos)
49 }
50
51 /// Teams presence service. Graph `Presence.Read.All` is not in the web app tokens.
52 pub async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {
53 let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
54 let mut presences = Vec::with_capacity(user_ids.len());
55 for chunk in user_ids.chunks(MAX_PRESENCE_IDS) {
56 let body: Vec<Value> = chunk
57 .iter()
58 .map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}")}))
59 .collect();
60 let answer = self
61 .session()
62 .request(
63 Method::Post,
64 PRESENCE_SERVICE_URL,
65 &scope,
66 Some(Value::Array(body)),
67 )
68 .await?;
69 presences.extend(parse_service_presences(&answer.body));
70 }
71 Ok(presences)
72 }
73
74 pub async fn subscribe_presence(
75 &self,
76 endpoint_id: &str,
77 trouter_uri: &str,
78 user_ids: &[String],
79 purge: bool,
80 ) -> Result<()> {
81 let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE);
82 let url = format!("{PRESENCE_SUBSCRIBE_URL}{endpoint_id}");
83 for (index, chunk) in user_ids.chunks(MAX_SUBSCRIBE_IDS).enumerate() {
84 let request = Request {
85 method: Method::Post,
86 headers: subscribe_headers(endpoint_id),
87 body: Some(subscribe_body(trouter_uri, chunk, purge && index == 0)),
88 ..Request::get(url.clone())
89 };
90 let answer = self.session().send(request, &scope).await?;
91 if !(200..300).contains(&answer.status) {
92 return Err(session::Error::api(answer.status, &url, answer.body).into());
93 }
94 }
95 Ok(())
96 }
97}
98
99// The service answers 400 naming each of the three x-ms-* client headers when one is missing.
100fn subscribe_headers(endpoint_id: &str) -> Vec<(String, String)> {
101 vec![
102 ("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),
103 ("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
104 ("x-ms-client-version".into(), PRESENCE_CLIENT_VERSION.into()),
105 ("x-ms-endpoint-id".into(), endpoint_id.into()),
106 ("x-ms-client-type".into(), "cdlworker".into()),
107 ]
108}
109
110fn subscribe_body(trouter_uri: &str, user_ids: &[String], purge: bool) -> Value {
111 let additions: Vec<Value> = user_ids
112 .iter()
113 .map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}"), "source": "ups"}))
114 .collect();
115 json!({
116 "trouterUri": trouter_uri,
117 "shouldPurgePreviousSubscriptions": purge,
118 "subscriptionsToAdd": additions,
119 "subscriptionsToRemove": [],
120 })
121}
122
123fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {
124 match answer.status {
125 404 => Ok(None),
126 _ => decode_binary(url, answer).map(Some),
127 }
128}
129
130pub(crate) fn decode_binary(url: &str, answer: ApiResponse) -> Result<Photo> {
131 match answer.status {
132 200..=299 => {
133 let body: BinaryBody = serde_json::from_value(answer.body)?;
134 let bytes = STANDARD
135 .decode(body.base64.as_bytes())
136 .map_err(|error| Error::Decode(error.to_string()))?;
137 Ok(Photo {
138 bytes,
139 content_type: body.content_type.unwrap_or_default(),
140 })
141 }
142 status => Err(session::Error::api(status, url, answer.body).into()),
143 }
144}
145
146fn parse_service_presences(body: &Value) -> Vec<Presence> {
147 body.as_array()
148 .into_iter()
149 .flatten()
150 .filter_map(|entry| {
151 let mri = entry.get("mri")?.as_str()?;
152 let presence = entry.get("presence")?;
153 Some(Presence {
154 user_id: mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned(),
155 availability: presence.get("availability")?.as_str()?.to_owned(),
156 activity: presence
157 .get("activity")
158 .and_then(Value::as_str)
159 .map(str::to_owned),
160 })
161 })
162 .collect()
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 fn answer(status: u16, body: Value) -> ApiResponse {
170 ApiResponse {
171 status,
172 body,
173 retry_after: None,
174 }
175 }
176
177 #[test]
178 fn photo_decodes_base64_and_content_type() {
179 let body = json!({"base64": STANDARD.encode([1u8, 2, 3]), "contentType": "image/jpeg"});
180 let photo = parse_photo("u", answer(200, body)).unwrap().unwrap();
181 assert_eq!(photo.bytes, [1, 2, 3]);
182 assert_eq!(photo.content_type, "image/jpeg");
183 }
184
185 #[test]
186 fn missing_photo_is_none_and_other_errors_surface() {
187 assert!(parse_photo("u", answer(404, json!("x"))).unwrap().is_none());
188 assert!(parse_photo("u", answer(403, json!("x"))).is_err());
189 }
190
191 #[test]
192 fn subscribe_body_carries_mris_and_purge_flag() {
193 let body = subscribe_body("https://t/unifiedPresenceService", &["a".into()], true);
194 assert_eq!(
195 body,
196 json!({
197 "trouterUri": "https://t/unifiedPresenceService",
198 "shouldPurgePreviousSubscriptions": true,
199 "subscriptionsToAdd": [{"mri": "8:orgid:a", "source": "ups"}],
200 "subscriptionsToRemove": [],
201 })
202 );
203 }
204
205 #[test]
206 fn subscribe_headers_use_a_fresh_correlation_id() {
207 let correlation = |headers: &[(String, String)]| {
208 headers
209 .iter()
210 .find(|(name, _)| name == "x-ms-correlation-id")
211 .map(|(_, value)| value.clone())
212 };
213 let first = subscribe_headers("e");
214 assert_ne!(correlation(&first), correlation(&subscribe_headers("e")));
215 assert!(
216 first
217 .iter()
218 .any(|(name, value)| name == "x-ms-endpoint-id" && value == "e")
219 );
220 }
221
222 #[test]
223 fn service_presences_strip_the_mri_prefix() {
224 let parsed = parse_service_presences(&json!([
225 {"mri": "8:orgid:a", "presence": {"availability": "Away", "activity": "Away"}},
226 {"mri": "8:orgid:b"}
227 ]));
228 assert_eq!(parsed.len(), 1);
229 assert_eq!(parsed[0].user_id, "a");
230 }
231}