| 1 | use chrono::{DateTime, Duration, SecondsFormat, Utc}; |
| 2 | use serde::Deserialize; |
| 3 | use serde_json::{Value, json}; |
| 4 | use session::{ApiResponse, Method, Request, Scope}; |
| 5 | |
| 6 | use crate::client::Graph; |
| 7 | use crate::error::Result; |
| 8 | use crate::urls; |
| 9 | |
| 10 | const PROFILE_SCOPE: &str = "User.ReadBasic.All"; |
| 11 | const SCHEDULE_SCOPE: &str = "Calendars.Read.Shared"; |
| 12 | |
| 13 | #[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)] |
| 14 | #[serde(rename_all = "camelCase", default)] |
| 15 | pub struct UserProfile { |
| 16 | pub id: String, |
| 17 | pub display_name: Option<String>, |
| 18 | pub job_title: Option<String>, |
| 19 | pub department: Option<String>, |
| 20 | pub company_name: Option<String>, |
| 21 | pub office_location: Option<String>, |
| 22 | pub mail: Option<String>, |
| 23 | pub user_principal_name: Option<String>, |
| 24 | pub business_phones: Vec<String>, |
| 25 | pub mobile_phone: Option<String>, |
| 26 | } |
| 27 | |
| 28 | #[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)] |
| 29 | #[serde(rename_all = "camelCase", default)] |
| 30 | pub struct OrgPerson { |
| 31 | pub id: String, |
| 32 | pub display_name: Option<String>, |
| 33 | pub job_title: Option<String>, |
| 34 | } |
| 35 | |
| 36 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 37 | pub struct ProfileDetails { |
| 38 | pub user: UserProfile, |
| 39 | pub manager: Option<OrgPerson>, |
| 40 | pub direct_reports: Vec<OrgPerson>, |
| 41 | } |
| 42 | |
| 43 | impl Graph { |
| 44 | pub async fn user_profile(&self, user_id: &str) -> Result<ProfileDetails> { |
| 45 | let requests = [ |
| 46 | Request::get(urls::user_profile(user_id)), |
| 47 | Request::get(urls::user_manager(user_id)), |
| 48 | Request::get(urls::user_direct_reports(user_id)), |
| 49 | ]; |
| 50 | let mut answers = self |
| 51 | .session() |
| 52 | .batch(&requests, &Scope::graph(PROFILE_SCOPE)) |
| 53 | .await? |
| 54 | .into_iter(); |
| 55 | let (Some(profile), Some(manager), Some(reports)) = |
| 56 | (answers.next(), answers.next(), answers.next()) |
| 57 | else { |
| 58 | return Err(session::Error::api(0, &requests[0].url, Value::Null).into()); |
| 59 | }; |
| 60 | parse_profile_details(&requests[0].url, profile, manager, reports) |
| 61 | } |
| 62 | |
| 63 | pub async fn user_mail(&self, user_id: &str) -> Result<Option<String>> { |
| 64 | let body = self |
| 65 | .get(&urls::user_mail(user_id), &Scope::graph(PROFILE_SCOPE)) |
| 66 | .await?; |
| 67 | Ok(parse_mail(&body)) |
| 68 | } |
| 69 | |
| 70 | pub async fn time_zone_name(&self, mail: &str) -> Result<Option<String>> { |
| 71 | let body = schedule_body(mail, Utc::now()); |
| 72 | let answer = self |
| 73 | .session() |
| 74 | .send( |
| 75 | Request::with_body(Method::Post, urls::get_schedule(), body), |
| 76 | &Scope::graph(SCHEDULE_SCOPE), |
| 77 | ) |
| 78 | .await?; |
| 79 | Ok(parse_time_zone_name(&answer.body)) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | fn parse_profile_details( |
| 84 | url: &str, |
| 85 | profile: ApiResponse, |
| 86 | manager: ApiResponse, |
| 87 | reports: ApiResponse, |
| 88 | ) -> Result<ProfileDetails> { |
| 89 | if !profile.is_success() { |
| 90 | return Err(session::Error::api(profile.status, url, profile.body).into()); |
| 91 | } |
| 92 | let manager = manager |
| 93 | .is_success() |
| 94 | .then(|| serde_json::from_value(manager.body).ok()) |
| 95 | .flatten(); |
| 96 | let direct_reports = reports |
| 97 | .is_success() |
| 98 | .then(|| reports.body.get("value").cloned()) |
| 99 | .flatten() |
| 100 | .and_then(|value| serde_json::from_value(value).ok()) |
| 101 | .unwrap_or_default(); |
| 102 | Ok(ProfileDetails { |
| 103 | user: serde_json::from_value(profile.body)?, |
| 104 | manager, |
| 105 | direct_reports, |
| 106 | }) |
| 107 | } |
| 108 | |
| 109 | fn schedule_body(mail: &str, now: DateTime<Utc>) -> Value { |
| 110 | let stamp = |moment: DateTime<Utc>| { |
| 111 | json!({ |
| 112 | "dateTime": moment.to_rfc3339_opts(SecondsFormat::Secs, true).trim_end_matches('Z'), |
| 113 | "timeZone": "UTC", |
| 114 | }) |
| 115 | }; |
| 116 | json!({ |
| 117 | "schedules": [mail], |
| 118 | "startTime": stamp(now), |
| 119 | "endTime": stamp(now + Duration::hours(1)), |
| 120 | "availabilityViewInterval": 60, |
| 121 | }) |
| 122 | } |
| 123 | |
| 124 | fn parse_mail(body: &Value) -> Option<String> { |
| 125 | ["mail", "userPrincipalName"] |
| 126 | .iter() |
| 127 | .filter_map(|key| body.get(key)?.as_str()) |
| 128 | .map(str::trim) |
| 129 | .find(|address| !address.is_empty()) |
| 130 | .map(str::to_owned) |
| 131 | } |
| 132 | |
| 133 | fn parse_time_zone_name(body: &Value) -> Option<String> { |
| 134 | let name = body |
| 135 | .pointer("/value/0/workingHours/timeZone/name")? |
| 136 | .as_str()? |
| 137 | .trim(); |
| 138 | (!name.is_empty()).then(|| name.to_owned()) |
| 139 | } |
| 140 | |
| 141 | #[cfg(test)] |
| 142 | mod tests { |
| 143 | use chrono::TimeZone; |
| 144 | |
| 145 | use super::*; |
| 146 | |
| 147 | fn answer(status: u16, body: Value) -> ApiResponse { |
| 148 | ApiResponse { |
| 149 | status, |
| 150 | body, |
| 151 | retry_after: None, |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | fn now() -> DateTime<Utc> { |
| 156 | Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap() |
| 157 | } |
| 158 | |
| 159 | #[test] |
| 160 | fn the_mail_falls_back_to_the_user_principal_name() { |
| 161 | assert_eq!( |
| 162 | parse_mail(&json!({"mail": null, "userPrincipalName": "bea@example.invalid"})), |
| 163 | Some("bea@example.invalid".to_owned()) |
| 164 | ); |
| 165 | assert_eq!( |
| 166 | parse_mail( |
| 167 | &json!({"mail": "a@example.invalid", "userPrincipalName": "b@example.invalid"}) |
| 168 | ), |
| 169 | Some("a@example.invalid".to_owned()) |
| 170 | ); |
| 171 | assert_eq!(parse_mail(&json!({"mail": " "})), None); |
| 172 | } |
| 173 | |
| 174 | #[test] |
| 175 | fn profile_details_parse_fields_manager_and_reports() { |
| 176 | let profile = json!({ |
| 177 | "id": "u1", |
| 178 | "displayName": "Ada Lovelace", |
| 179 | "jobTitle": "Engineer", |
| 180 | "department": null, |
| 181 | "mail": "ada@example.com", |
| 182 | "businessPhones": ["+49 1"], |
| 183 | "mobilePhone": null |
| 184 | }); |
| 185 | let manager = json!({"id": "m1", "displayName": "Grace", "jobTitle": "Lead"}); |
| 186 | let reports = json!({"value": [{"@odata.type": "#microsoft.graph.user", "id": "r1", "displayName": "Bob"}]}); |
| 187 | let details = parse_profile_details( |
| 188 | "u", |
| 189 | answer(200, profile), |
| 190 | answer(200, manager), |
| 191 | answer(200, reports), |
| 192 | ) |
| 193 | .unwrap(); |
| 194 | assert_eq!(details.user.display_name.as_deref(), Some("Ada Lovelace")); |
| 195 | assert_eq!(details.user.department, None); |
| 196 | assert_eq!(details.user.business_phones, vec!["+49 1"]); |
| 197 | assert_eq!(details.manager.unwrap().id, "m1"); |
| 198 | assert_eq!( |
| 199 | details.direct_reports[0].display_name.as_deref(), |
| 200 | Some("Bob") |
| 201 | ); |
| 202 | } |
| 203 | |
| 204 | #[test] |
| 205 | fn missing_manager_and_failed_reports_do_not_fail_the_profile() { |
| 206 | let details = parse_profile_details( |
| 207 | "u", |
| 208 | answer(200, json!({"id": "u1"})), |
| 209 | answer(404, json!({})), |
| 210 | answer(403, json!({})), |
| 211 | ) |
| 212 | .unwrap(); |
| 213 | assert!(details.manager.is_none()); |
| 214 | assert!(details.direct_reports.is_empty()); |
| 215 | } |
| 216 | |
| 217 | #[test] |
| 218 | fn a_failed_profile_is_an_error() { |
| 219 | let failed = parse_profile_details( |
| 220 | "u", |
| 221 | answer(404, json!({})), |
| 222 | answer(200, json!({"id": "m"})), |
| 223 | answer(200, json!({"value": []})), |
| 224 | ); |
| 225 | assert!(failed.is_err()); |
| 226 | } |
| 227 | |
| 228 | #[test] |
| 229 | fn schedule_body_asks_one_hour_in_utc() { |
| 230 | let body = schedule_body("ada@example.com", now()); |
| 231 | assert_eq!(body["schedules"], json!(["ada@example.com"])); |
| 232 | assert_eq!( |
| 233 | body["startTime"], |
| 234 | json!({"dateTime": "2026-10-09T12:00:00", "timeZone": "UTC"}) |
| 235 | ); |
| 236 | assert_eq!(body["endTime"]["dateTime"], "2026-10-09T13:00:00"); |
| 237 | } |
| 238 | |
| 239 | #[test] |
| 240 | fn time_zone_comes_from_working_hours() { |
| 241 | let body = |
| 242 | json!({"value": [{"workingHours": {"timeZone": {"name": "W. Europe Standard Time"}}}]}); |
| 243 | assert_eq!( |
| 244 | parse_time_zone_name(&body).as_deref(), |
| 245 | Some("W. Europe Standard Time") |
| 246 | ); |
| 247 | assert_eq!(parse_time_zone_name(&json!({"value": [{}]})), None); |
| 248 | } |
| 249 | } |