| 1 | use base64::Engine as _; |
| 2 | use base64::engine::general_purpose::STANDARD; |
| 3 | use serde::Deserialize; |
| 4 | use serde_json::{Value, json}; |
| 5 | use session::{ApiResponse, Method, PRESENCE, Request, Scope}; |
| 6 | |
| 7 | use crate::client::{BATCH_SIZE, Graph}; |
| 8 | use crate::error::{Error, Result}; |
| 9 | use crate::models::{Photo, Presence}; |
| 10 | use crate::urls; |
| 11 | |
| 12 | pub const MAX_PRESENCE_IDS: usize = 650; |
| 13 | const PHOTO_SCOPE: &str = "User.ReadBasic.All"; |
| 14 | const PRESENCE_SERVICE_URL: &str = "https://presence.teams.microsoft.com/v1/presence/getpresence/"; |
| 15 | const PRESENCE_SERVICE_SCOPE: &str = "user_impersonation"; |
| 16 | const ORGID_PREFIX: &str = "8:orgid:"; |
| 17 | |
| 18 | #[derive(Debug, Deserialize)] |
| 19 | struct BinaryBody { |
| 20 | base64: String, |
| 21 | #[serde(rename = "contentType")] |
| 22 | content_type: Option<String>, |
| 23 | } |
| 24 | |
| 25 | impl Graph { |
| 26 | /// `Ok(None)` for users without a photo (404). |
| 27 | pub async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> { |
| 28 | let scope = Scope::graph(PHOTO_SCOPE); |
| 29 | let mut photos = Vec::with_capacity(user_ids.len()); |
| 30 | for chunk in user_ids.chunks(BATCH_SIZE) { |
| 31 | let requests: Vec<Request> = chunk |
| 32 | .iter() |
| 33 | .map(|user_id| Request::binary_get(urls::user_photo(user_id))) |
| 34 | .collect(); |
| 35 | let answers = self.session().batch(&requests, &scope).await?; |
| 36 | photos.extend( |
| 37 | requests |
| 38 | .iter() |
| 39 | .zip(answers) |
| 40 | .map(|(request, answer)| parse_photo(&request.url, answer)), |
| 41 | ); |
| 42 | } |
| 43 | Ok(photos) |
| 44 | } |
| 45 | |
| 46 | /// Teams presence service. Graph `Presence.Read.All` is not in the web app tokens. |
| 47 | pub async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> { |
| 48 | let scope = Scope::new(PRESENCE, PRESENCE_SERVICE_SCOPE); |
| 49 | let mut presences = Vec::with_capacity(user_ids.len()); |
| 50 | for chunk in user_ids.chunks(MAX_PRESENCE_IDS) { |
| 51 | let body: Vec<Value> = chunk |
| 52 | .iter() |
| 53 | .map(|user_id| json!({"mri": format!("{ORGID_PREFIX}{user_id}")})) |
| 54 | .collect(); |
| 55 | let answer = self |
| 56 | .session() |
| 57 | .request( |
| 58 | Method::Post, |
| 59 | PRESENCE_SERVICE_URL, |
| 60 | &scope, |
| 61 | Some(Value::Array(body)), |
| 62 | ) |
| 63 | .await?; |
| 64 | presences.extend(parse_service_presences(&answer.body)); |
| 65 | } |
| 66 | Ok(presences) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> { |
| 71 | match answer.status { |
| 72 | 404 => Ok(None), |
| 73 | _ => decode_binary(url, answer).map(Some), |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | pub(crate) fn decode_binary(url: &str, answer: ApiResponse) -> Result<Photo> { |
| 78 | match answer.status { |
| 79 | 200..=299 => { |
| 80 | let body: BinaryBody = serde_json::from_value(answer.body)?; |
| 81 | let bytes = STANDARD |
| 82 | .decode(body.base64.as_bytes()) |
| 83 | .map_err(|error| Error::Decode(error.to_string()))?; |
| 84 | Ok(Photo { |
| 85 | bytes, |
| 86 | content_type: body.content_type.unwrap_or_default(), |
| 87 | }) |
| 88 | } |
| 89 | status => Err(session::Error::api(status, url, answer.body).into()), |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | fn parse_service_presences(body: &Value) -> Vec<Presence> { |
| 94 | body.as_array() |
| 95 | .into_iter() |
| 96 | .flatten() |
| 97 | .filter_map(|entry| { |
| 98 | let mri = entry.get("mri")?.as_str()?; |
| 99 | let presence = entry.get("presence")?; |
| 100 | Some(Presence { |
| 101 | user_id: mri.strip_prefix(ORGID_PREFIX).unwrap_or(mri).to_owned(), |
| 102 | availability: presence.get("availability")?.as_str()?.to_owned(), |
| 103 | activity: presence |
| 104 | .get("activity") |
| 105 | .and_then(Value::as_str) |
| 106 | .map(str::to_owned), |
| 107 | }) |
| 108 | }) |
| 109 | .collect() |
| 110 | } |
| 111 | |
| 112 | #[cfg(test)] |
| 113 | mod tests { |
| 114 | use super::*; |
| 115 | |
| 116 | fn answer(status: u16, body: Value) -> ApiResponse { |
| 117 | ApiResponse { |
| 118 | status, |
| 119 | body, |
| 120 | retry_after: None, |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | #[test] |
| 125 | fn photo_decodes_base64_and_content_type() { |
| 126 | let body = json!({"base64": STANDARD.encode([1u8, 2, 3]), "contentType": "image/jpeg"}); |
| 127 | let photo = parse_photo("u", answer(200, body)).unwrap().unwrap(); |
| 128 | assert_eq!(photo.bytes, [1, 2, 3]); |
| 129 | assert_eq!(photo.content_type, "image/jpeg"); |
| 130 | } |
| 131 | |
| 132 | #[test] |
| 133 | fn missing_photo_is_none_and_other_errors_surface() { |
| 134 | assert!(parse_photo("u", answer(404, json!("x"))).unwrap().is_none()); |
| 135 | assert!(parse_photo("u", answer(403, json!("x"))).is_err()); |
| 136 | } |
| 137 | |
| 138 | #[test] |
| 139 | fn service_presences_strip_the_mri_prefix() { |
| 140 | let parsed = parse_service_presences(&json!([ |
| 141 | {"mri": "8:orgid:a", "presence": {"availability": "Away", "activity": "Away"}}, |
| 142 | {"mri": "8:orgid:b"} |
| 143 | ])); |
| 144 | assert_eq!(parsed.len(), 1); |
| 145 | assert_eq!(parsed[0].user_id, "a"); |
| 146 | } |
| 147 | } |