BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / user_profiles.rs

user_profiles.rs

user_profiles.rs 4.8 KiB Download Raw
1use serde_json::{Value, json};
2use session::{Method, Request, SPACES, Scope, Session};
3
4use crate::error::Result;
5use crate::language_settings::with_headers;
6use crate::messages::ensure_success;
7use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
9const SKYPE_SCOPE: &str = "user_impersonation";
10const ORGID_PREFIX: &str = "8:orgid:";
11const PROFILE_QUERY: &str =
12 "isMailAddress=false&enableGuest=true&includeIBBarredUsers=true&skypeTeamsInfo=true";
13const PROFILES_PER_REQUEST: usize = 100;
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct UserProfile {
17 pub user_id: String,
18 pub display_name: Option<String>,
19 pub email: Option<String>,
20 pub user_principal_name: Option<String>,
21 pub job_title: Option<String>,
22 pub department: Option<String>,
23}
24
25pub struct UserProfiles<T: CsaTransport = SessionTransport> {
26 transport: T,
27 url: String,
28}
29
30impl UserProfiles<SessionTransport> {
31 pub fn new(session: &Session) -> Self {
32 let transport = SessionTransport::with_scope(session, Scope::new(SPACES, SKYPE_SCOPE));
33 UserProfiles::with_transport(transport, DEFAULT_REGION)
34 }
35}
36
37impl<T: CsaTransport> UserProfiles<T> {
38 pub fn with_transport(transport: T, region: &str) -> Self {
39 UserProfiles {
40 transport,
41 url: format!(
42 "https://teams.cloud.microsoft/api/mt/{region}/beta/users/fetchShortProfile?{PROFILE_QUERY}"
43 ),
44 }
45 }
46
47 pub async fn fetch(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> {
48 let mut profiles = Vec::new();
49 for chunk in user_ids.chunks(PROFILES_PER_REQUEST) {
50 let mris: Vec<Value> = chunk
51 .iter()
52 .map(|user_id| json!(format!("{ORGID_PREFIX}{user_id}")))
53 .collect();
54 let answer = self
55 .transport
56 .send(with_headers(Request::with_body(
57 Method::Post,
58 self.url.clone(),
59 Value::Array(mris),
60 )))
61 .await?;
62 ensure_success(&answer)?;
63 profiles.extend(parse_user_profiles(&answer.body));
64 }
65 Ok(profiles)
66 }
67}
68
69pub fn parse_user_profiles(body: &Value) -> Vec<UserProfile> {
70 body.get("value")
71 .and_then(Value::as_array)
72 .map(Vec::as_slice)
73 .unwrap_or_default()
74 .iter()
75 .filter_map(|profile| {
76 let user_id = profile
77 .get("objectId")
78 .and_then(Value::as_str)
79 .filter(|id| !id.is_empty())
80 .or_else(|| {
81 profile
82 .get("mri")
83 .and_then(Value::as_str)?
84 .strip_prefix(ORGID_PREFIX)
85 })?
86 .to_owned();
87 Some(UserProfile {
88 user_id,
89 display_name: text(profile, "displayName"),
90 email: text(profile, "email"),
91 user_principal_name: text(profile, "userPrincipalName"),
92 job_title: text(profile, "jobTitle"),
93 department: text(profile, "department"),
94 })
95 })
96 .collect()
97}
98
99fn text(profile: &Value, key: &str) -> Option<String> {
100 profile
101 .get(key)
102 .and_then(Value::as_str)
103 .map(str::trim)
104 .filter(|text| !text.is_empty())
105 .map(str::to_owned)
106}
107
108#[cfg(test)]
109mod tests {
110 use std::sync::Mutex;
111
112 use session::ApiResponse;
113
114 use super::*;
115
116 struct Canned {
117 requests: Mutex<Vec<Request>>,
118 }
119
120 impl CsaTransport for &Canned {
121 async fn send(&self, request: Request) -> Result<ApiResponse> {
122 self.requests.lock().unwrap().push(request);
123 Ok(ApiResponse {
124 status: 200,
125 body: json!({"value": [
126 {"mri": "8:orgid:ann", "objectId": "ann", "displayName": "Ann Example", "email": "ann@example.com"},
127 {"mri": "8:orgid:bob", "displayName": " "},
128 ]}),
129 retry_after: None,
130 })
131 }
132 }
133
134 #[tokio::test]
135 async fn profiles_post_mris_and_read_names() {
136 let canned = Canned {
137 requests: Mutex::new(Vec::new()),
138 };
139 let profiles = UserProfiles::with_transport(&canned, "emea")
140 .fetch(&["ann".into(), "bob".into()])
141 .await
142 .unwrap();
143 assert_eq!(profiles[0].display_name.as_deref(), Some("Ann Example"));
144 assert_eq!(profiles[0].email.as_deref(), Some("ann@example.com"));
145 assert_eq!(profiles[1].user_id, "bob");
146 assert_eq!(profiles[1].display_name, None);
147 let requests = canned.requests.lock().unwrap();
148 assert_eq!(
149 requests[0].body,
150 Some(json!(["8:orgid:ann", "8:orgid:bob"]))
151 );
152 }
153}