BlueGit

ict rusty-teams

Files

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

user_profiles.rs

user_profiles.rs 6.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::{encode, 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 pub tenant_name: Option<String>,
24}
25
26pub struct UserProfiles<T: CsaTransport = SessionTransport> {
27 transport: T,
28 users_url: String,
29}
30
31impl UserProfiles<SessionTransport> {
32 pub fn new(session: &Session) -> Self {
33 let transport = SessionTransport::with_scope(session, Scope::new(SPACES, SKYPE_SCOPE));
34 UserProfiles::with_transport(transport, DEFAULT_REGION)
35 }
36}
37
38impl<T: CsaTransport> UserProfiles<T> {
39 pub fn with_transport(transport: T, region: &str) -> Self {
40 UserProfiles {
41 transport,
42 users_url: format!("https://teams.cloud.microsoft/api/mt/{region}/beta/users"),
43 }
44 }
45
46 pub async fn fetch(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> {
47 self.post_mris(
48 &format!("{}/fetchShortProfile?{PROFILE_QUERY}", self.users_url),
49 user_ids,
50 )
51 .await
52 }
53
54 /// People of other organizations; the short profile lookup answers nothing for them.
55 pub async fn fetch_federated(&self, user_ids: &[String]) -> Result<Vec<UserProfile>> {
56 self.post_mris(&format!("{}/fetchFederated", self.users_url), user_ids)
57 .await
58 }
59
60 /// Teams finds a person of another organization only by the full email address.
61 pub async fn search_external(&self, email: &str) -> Result<Vec<UserProfile>> {
62 let answer = self
63 .transport
64 .send(with_headers(Request::get(format!(
65 "{}/{}/externalsearchv3?includeTFLUsers=true",
66 self.users_url,
67 encode(email.trim())
68 ))))
69 .await?;
70 ensure_success(&answer)?;
71 Ok(parse_user_profiles(&json!({"value": answer.body})))
72 }
73
74 async fn post_mris(&self, url: &str, user_ids: &[String]) -> Result<Vec<UserProfile>> {
75 let mut profiles = Vec::new();
76 for chunk in user_ids.chunks(PROFILES_PER_REQUEST) {
77 let mris: Vec<Value> = chunk
78 .iter()
79 .map(|user_id| json!(format!("{ORGID_PREFIX}{user_id}")))
80 .collect();
81 let answer = self
82 .transport
83 .send(with_headers(Request::with_body(
84 Method::Post,
85 url.to_owned(),
86 Value::Array(mris),
87 )))
88 .await?;
89 ensure_success(&answer)?;
90 profiles.extend(parse_user_profiles(&answer.body));
91 }
92 Ok(profiles)
93 }
94}
95
96pub fn parse_user_profiles(body: &Value) -> Vec<UserProfile> {
97 body.get("value")
98 .and_then(Value::as_array)
99 .map(Vec::as_slice)
100 .unwrap_or_default()
101 .iter()
102 .filter_map(|profile| {
103 let user_id = profile
104 .get("objectId")
105 .and_then(Value::as_str)
106 .filter(|id| !id.is_empty())
107 .or_else(|| {
108 profile
109 .get("mri")
110 .and_then(Value::as_str)?
111 .strip_prefix(ORGID_PREFIX)
112 })?
113 .to_owned();
114 Some(UserProfile {
115 user_id,
116 display_name: text(profile, "displayName"),
117 email: text(profile, "email"),
118 user_principal_name: text(profile, "userPrincipalName"),
119 job_title: text(profile, "jobTitle"),
120 department: text(profile, "department"),
121 tenant_name: text(profile, "tenantName"),
122 })
123 })
124 .collect()
125}
126
127fn text(profile: &Value, key: &str) -> Option<String> {
128 profile
129 .get(key)
130 .and_then(Value::as_str)
131 .map(str::trim)
132 .filter(|text| !text.is_empty())
133 .map(str::to_owned)
134}
135
136#[cfg(test)]
137mod tests {
138 use std::sync::Mutex;
139
140 use session::ApiResponse;
141
142 use super::*;
143
144 struct Canned {
145 requests: Mutex<Vec<Request>>,
146 }
147
148 impl CsaTransport for &Canned {
149 async fn send(&self, request: Request) -> Result<ApiResponse> {
150 self.requests.lock().unwrap().push(request);
151 Ok(ApiResponse {
152 status: 200,
153 body: json!({"value": [
154 {"mri": "8:orgid:ann", "objectId": "ann", "displayName": "Ann Example", "email": "ann@example.com"},
155 {"mri": "8:orgid:bob", "displayName": " "},
156 ]}),
157 retry_after: None,
158 })
159 }
160 }
161
162 #[tokio::test]
163 async fn profiles_post_mris_and_read_names() {
164 let canned = Canned {
165 requests: Mutex::new(Vec::new()),
166 };
167 let profiles = UserProfiles::with_transport(&canned, "emea")
168 .fetch(&["ann".into(), "bob".into()])
169 .await
170 .unwrap();
171 assert_eq!(profiles[0].display_name.as_deref(), Some("Ann Example"));
172 assert_eq!(profiles[0].email.as_deref(), Some("ann@example.com"));
173 assert_eq!(profiles[1].user_id, "bob");
174 assert_eq!(profiles[1].display_name, None);
175 let requests = canned.requests.lock().unwrap();
176 assert_eq!(
177 requests[0].body,
178 Some(json!(["8:orgid:ann", "8:orgid:bob"]))
179 );
180 assert!(requests[0].url.contains("/users/fetchShortProfile?"));
181 }
182
183 #[tokio::test]
184 async fn people_of_other_organizations_come_from_the_federated_lookup() {
185 let canned = Canned {
186 requests: Mutex::new(Vec::new()),
187 };
188 UserProfiles::with_transport(&canned, "emea")
189 .fetch_federated(&["ann".into()])
190 .await
191 .unwrap();
192 let requests = canned.requests.lock().unwrap();
193 assert!(requests[0].url.ends_with("/emea/beta/users/fetchFederated"));
194 assert_eq!(requests[0].body, Some(json!(["8:orgid:ann"])));
195 }
196
197 #[test]
198 fn a_federated_profile_carries_its_organization() {
199 let profiles = parse_user_profiles(&json!({"value": [
200 {"mri": "8:orgid:ann", "objectId": "ann", "displayName": "Ann", "tenantName": "Example Corp"},
201 ]}));
202 assert_eq!(profiles[0].tenant_name.as_deref(), Some("Example Corp"));
203 }
204}