| 1 | use base64::Engine as _; |
| 2 | use base64::engine::general_purpose::STANDARD; |
| 3 | use serde::Deserialize; |
| 4 | use session::{ApiResponse, Request, Scope}; |
| 5 | |
| 6 | use crate::client::{BATCH_SIZE, Graph}; |
| 7 | use crate::error::{Error, Result}; |
| 8 | use crate::models::Photo; |
| 9 | use crate::urls; |
| 10 | |
| 11 | const PHOTO_SCOPE: &str = "User.ReadBasic.All"; |
| 12 | |
| 13 | #[derive(Debug, Deserialize)] |
| 14 | struct BinaryBody { |
| 15 | base64: String, |
| 16 | #[serde(rename = "contentType")] |
| 17 | content_type: Option<String>, |
| 18 | } |
| 19 | |
| 20 | impl Graph { |
| 21 | /// `Ok(None)` for users without a photo. A 404 on the sized rendition |
| 22 | /// also comes back for photos stored smaller in Entra ID, so those ask for the original. |
| 23 | pub async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> { |
| 24 | let mut photos = self.photo_batch(user_ids, urls::user_photo).await?; |
| 25 | let missing: Vec<usize> = photos |
| 26 | .iter() |
| 27 | .enumerate() |
| 28 | .filter(|(_, photo)| matches!(photo, Ok(None))) |
| 29 | .map(|(index, _)| index) |
| 30 | .collect(); |
| 31 | if missing.is_empty() { |
| 32 | return Ok(photos); |
| 33 | } |
| 34 | let missing_ids: Vec<String> = missing |
| 35 | .iter() |
| 36 | .map(|index| user_ids[*index].clone()) |
| 37 | .collect(); |
| 38 | let originals = self |
| 39 | .photo_batch(&missing_ids, urls::user_photo_original) |
| 40 | .await?; |
| 41 | for (index, original) in missing.into_iter().zip(originals) { |
| 42 | photos[index] = original; |
| 43 | } |
| 44 | Ok(photos) |
| 45 | } |
| 46 | |
| 47 | pub async fn team_photos(&self, team_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> { |
| 48 | self.photo_batch(team_ids, urls::team_photo).await |
| 49 | } |
| 50 | |
| 51 | async fn photo_batch( |
| 52 | &self, |
| 53 | user_ids: &[String], |
| 54 | url: fn(&str) -> String, |
| 55 | ) -> Result<Vec<Result<Option<Photo>>>> { |
| 56 | let scope = Scope::graph(PHOTO_SCOPE); |
| 57 | let mut photos = Vec::with_capacity(user_ids.len()); |
| 58 | for chunk in user_ids.chunks(BATCH_SIZE) { |
| 59 | let requests: Vec<Request> = chunk |
| 60 | .iter() |
| 61 | .map(|user_id| Request::binary_get(url(user_id))) |
| 62 | .collect(); |
| 63 | let answers = self.session().batch(&requests, &scope).await?; |
| 64 | photos.extend( |
| 65 | requests |
| 66 | .iter() |
| 67 | .zip(answers) |
| 68 | .map(|(request, answer)| parse_photo(&request.url, answer)), |
| 69 | ); |
| 70 | } |
| 71 | Ok(photos) |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> { |
| 76 | match answer.status { |
| 77 | 404 => Ok(None), |
| 78 | _ => decode_binary(url, answer).map(Some), |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | pub(crate) fn decode_binary(url: &str, answer: ApiResponse) -> Result<Photo> { |
| 83 | match answer.status { |
| 84 | 200..=299 => { |
| 85 | let body: BinaryBody = serde_json::from_value(answer.body)?; |
| 86 | let bytes = STANDARD |
| 87 | .decode(body.base64.as_bytes()) |
| 88 | .map_err(|error| Error::Decode(error.to_string()))?; |
| 89 | Ok(Photo { |
| 90 | bytes, |
| 91 | content_type: body.content_type.unwrap_or_default(), |
| 92 | }) |
| 93 | } |
| 94 | status => Err(session::Error::api(status, url, answer.body).into()), |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | #[cfg(test)] |
| 99 | mod tests { |
| 100 | use serde_json::{Value, json}; |
| 101 | |
| 102 | use super::*; |
| 103 | |
| 104 | fn answer(status: u16, body: Value) -> ApiResponse { |
| 105 | ApiResponse { |
| 106 | status, |
| 107 | body, |
| 108 | retry_after: None, |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | #[test] |
| 113 | fn photo_decodes_base64_and_content_type() { |
| 114 | let body = json!({"base64": STANDARD.encode([1u8, 2, 3]), "contentType": "image/jpeg"}); |
| 115 | let photo = parse_photo("u", answer(200, body)).unwrap().unwrap(); |
| 116 | assert_eq!(photo.bytes, [1, 2, 3]); |
| 117 | assert_eq!(photo.content_type, "image/jpeg"); |
| 118 | } |
| 119 | |
| 120 | #[test] |
| 121 | fn missing_photo_is_none_and_other_errors_surface() { |
| 122 | assert!(parse_photo("u", answer(404, json!("x"))).unwrap().is_none()); |
| 123 | assert!(parse_photo("u", answer(403, json!("x"))).is_err()); |
| 124 | } |
| 125 | } |