BlueGit

ict rusty-teams

Files

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

people.rs

people.rs 2.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 (404).
22 pub async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> {
23 let scope = Scope::graph(PHOTO_SCOPE);
24 let mut photos = Vec::with_capacity(user_ids.len());
25 for chunk in user_ids.chunks(BATCH_SIZE) {
26 let requests: Vec<Request> = chunk
27 .iter()
28 .map(|user_id| Request::binary_get(urls::user_photo(user_id)))
29 .collect();
30 let answers = self.session().batch(&requests, &scope).await?;
31 photos.extend(
32 requests
33 .iter()
34 .zip(answers)
35 .map(|(request, answer)| parse_photo(&request.url, answer)),
36 );
37 }
38 Ok(photos)
39 }
40}
41
42fn parse_photo(url: &str, answer: ApiResponse) -> Result<Option<Photo>> {
43 match answer.status {
44 404 => Ok(None),
45 _ => decode_binary(url, answer).map(Some),
46 }
47}
48
49pub(crate) fn decode_binary(url: &str, answer: ApiResponse) -> Result<Photo> {
50 match answer.status {
51 200..=299 => {
52 let body: BinaryBody = serde_json::from_value(answer.body)?;
53 let bytes = STANDARD
54 .decode(body.base64.as_bytes())
55 .map_err(|error| Error::Decode(error.to_string()))?;
56 Ok(Photo {
57 bytes,
58 content_type: body.content_type.unwrap_or_default(),
59 })
60 }
61 status => Err(session::Error::api(status, url, answer.body).into()),
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use serde_json::{Value, json};
68
69 use super::*;
70
71 fn answer(status: u16, body: Value) -> ApiResponse {
72 ApiResponse {
73 status,
74 body,
75 retry_after: None,
76 }
77 }
78
79 #[test]
80 fn photo_decodes_base64_and_content_type() {
81 let body = json!({"base64": STANDARD.encode([1u8, 2, 3]), "contentType": "image/jpeg"});
82 let photo = parse_photo("u", answer(200, body)).unwrap().unwrap();
83 assert_eq!(photo.bytes, [1, 2, 3]);
84 assert_eq!(photo.content_type, "image/jpeg");
85 }
86
87 #[test]
88 fn missing_photo_is_none_and_other_errors_surface() {
89 assert!(parse_photo("u", answer(404, json!("x"))).unwrap().is_none());
90 assert!(parse_photo("u", answer(403, json!("x"))).is_err());
91 }
92}