BlueGit

ict rusty-teams

Files

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

people.rs

people.rs 3.8 KiB Download Raw
1use base64::Engine as _;
2use base64::engine::general_purpose::STANDARD;
3use serde::Deserialize;
4use session::{ApiResponse, Request, Scope};
5
6use crate::client::{BATCH_SIZE, Graph};
7use crate::error::{Error, Result};
8use crate::models::Photo;
9use crate::urls;
10
11const PHOTO_SCOPE: &str = "User.ReadBasic.All";
12
13#[derive(Debug, Deserialize)]
14struct BinaryBody {
15 base64: String,
16 #[serde(rename = "contentType")]
17 content_type: Option<String>,
18}
19
20impl 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 async fn photo_batch(
48 &self,
49 user_ids: &[String],
50 url: fn(&str) -> String,
51 ) -> Result<Vec<Result<Option<Photo>>>> {
52 let scope = Scope::graph(PHOTO_SCOPE);
53 let mut photos = Vec::with_capacity(user_ids.len());
54 for chunk in user_ids.chunks(BATCH_SIZE) {
55 let requests: Vec<Request> = chunk
56 .iter()
57 .map(|user_id| Request::binary_get(url(user_id)))
58 .collect();
59 let answers = self.session().batch(&requests, &scope).await?;
60 photos.extend(
61 requests
62 .iter()
63 .zip(answers)
64 .map(|(request, answer)| parse_photo(&request.url, answer)),
65 );
66 }
67 Ok(photos)
68 }
69}
70
71fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {
72 match answer.status {
73 404 => Ok(None),
74 _ => decode_binary(url, answer).map(Some),
75 }
76}
77
78pub(crate) fn decode_binary(url: &str, answer: ApiResponse) -> Result<Photo> {
79 match answer.status {
80 200..=299 => {
81 let body: BinaryBody = serde_json::from_value(answer.body)?;
82 let bytes = STANDARD
83 .decode(body.base64.as_bytes())
84 .map_err(|error| Error::Decode(error.to_string()))?;
85 Ok(Photo {
86 bytes,
87 content_type: body.content_type.unwrap_or_default(),
88 })
89 }
90 status => Err(session::Error::api(status, url, answer.body).into()),
91 }
92}
93
94#[cfg(test)]
95mod tests {
96 use serde_json::{Value, json};
97
98 use super::*;
99
100 fn answer(status: u16, body: Value) -> ApiResponse {
101 ApiResponse {
102 status,
103 body,
104 retry_after: None,
105 }
106 }
107
108 #[test]
109 fn photo_decodes_base64_and_content_type() {
110 let body = json!({"base64": STANDARD.encode([1u8, 2, 3]), "contentType": "image/jpeg"});
111 let photo = parse_photo("u", answer(200, body)).unwrap().unwrap();
112 assert_eq!(photo.bytes, [1, 2, 3]);
113 assert_eq!(photo.content_type, "image/jpeg");
114 }
115
116 #[test]
117 fn missing_photo_is_none_and_other_errors_surface() {
118 assert!(parse_photo("u", answer(404, json!("x"))).unwrap().is_none());
119 assert!(parse_photo("u", answer(403, json!("x"))).is_err());
120 }
121}