feat(search): resolve people outside the organization (#87)
@@ -314,6 +314,7 @@ mod tests {
314
314
user_id: "bob".to_owned(),
315
315
name: "Bob".to_owned(),
316
316
mail: None,
317
organization: None,
317
318
}];
318
319
let people = group_chat_people(&members, Some("me"), &picks);
319
320
assert_eq!(people, [member("ann", "Ann"), member("bob", "Bob")]);
@@ -314,6 +314,7 @@ mod tests {314
user_id: "bob".to_owned(),314
user_id: "bob".to_owned(),315
name: "Bob".to_owned(),315
name: "Bob".to_owned(),316
mail: None,316
mail: None,317
organization: None,317
}];318
}];318
let people = group_chat_people(&members, Some("me"), &picks);319
let people = group_chat_people(&members, Some("me"), &picks);319
assert_eq!(people, [member("ann", "Ann"), member("bob", "Bob")]);320
assert_eq!(people, [member("ann", "Ann"), member("bob", "Bob")]);@@ -1226,6 +1226,7 @@ impl ConversationView {
1226
1226
user_id: person.user_id?,
1227
1227
name: person.display_name,
1228
1228
mail: None,
1229
organization: None,
1229
1230
})
1230
1231
})
1231
1232
.collect();
@@ -1226,6 +1226,7 @@ impl ConversationView {1226
user_id: person.user_id?,1226
user_id: person.user_id?,1227
name: person.display_name,1227
name: person.display_name,1228
mail: None,1228
mail: None,1229
organization: None,1229
})1230
})1230
})1231
})1231
.collect();1232
.collect();@@ -10,6 +10,7 @@ use gpui_kit::component::{
10
10
use gpui_kit::prelude::FluentBuilder as _;
11
11
use gpui_kit::*;
12
12
use store::ChatRecord;
13
use teams_core::substrate_search::{SearchPerson, SearchSession};
13
14
use teams_core::MentionCandidate;
14
15
15
16
use super::avatar::person_avatar;
@@ -39,6 +40,7 @@ pub struct Pick {
39
40
pub user_id: String,
40
41
pub name: String,
41
42
pub mail: Option<String>,
43
pub organization: Option<String>,
42
44
}
43
45
44
46
pub enum NewChatEvent {
@@ -78,6 +80,7 @@ fn people_in(chats: &[ChatRecord], me: Option<&Person>, one_on_one_only: bool) -
78
80
user_id,
79
81
name,
80
82
mail: None,
83
organization: None,
81
84
})
82
85
})
83
86
.collect()
@@ -143,22 +146,67 @@ pub fn composer_placeholder(chips: &[Pick], group_name: &str) -> String {
143
146
}
144
147
}
145
148
149
fn pick_detail(pick: &Pick) -> String {
150
match (&pick.mail, pick.organization.as_deref()) {
151
(Some(mail), Some(organization)) if !organization.is_empty() => {
152
format!("{mail} · {organization}")
153
}
154
(Some(mail), _) => mail.clone(),
155
(None, Some(organization)) if !organization.is_empty() => organization.to_owned(),
156
_ => String::new(),
157
}
158
}
159
146
160
fn pick_from_user(user: graph::User) -> Option<Pick> {
147
161
let mail = user.mail.or(user.user_principal_name);
148
162
let name = user.display_name.or_else(|| mail.clone())?;
163
let organization =
164
teams_core::native::known_profile(&user.id).and_then(|profile| profile.tenant_name);
149
165
Some(Pick {
150
166
user_id: user.id,
151
167
name,
152
168
mail,
169
organization,
170
})
171
}
172
173
fn pick_from_search_person(person: &SearchPerson) -> Option<Pick> {
174
let user_id = person.user_id.clone()?;
175
let mail = person
176
.email_addresses
177
.first()
178
.cloned()
179
.or_else(|| person.user_principal_name.clone());
180
let name = if person.display_name.is_empty() {
181
mail.clone()?
182
} else {
183
person.display_name.clone()
184
};
185
let organization = person.company_name.clone().filter(|name| !name.is_empty());
186
Some(Pick {
187
user_id,
188
name,
189
mail,
190
organization,
153
191
})
154
192
}
155
193
194
pub fn merge_remote(suggestions: Vec<Pick>, directory: Vec<Pick>) -> Vec<Pick> {
195
let mut seen = HashSet::new();
196
suggestions
197
.into_iter()
198
.chain(directory)
199
.filter(|pick| seen.insert(pick.user_id.clone()))
200
.collect()
201
}
202
156
203
fn pick_from_candidate(candidate: MentionCandidate) -> Option<Pick> {
157
204
match candidate {
158
205
MentionCandidate::Person(person) => Some(Pick {
159
206
user_id: person.user_id,
160
207
name: person.display_name,
161
208
mail: person.mail,
209
organization: None,
162
210
}),
163
211
_ => None,
164
212
}
@@ -176,6 +224,7 @@ pub struct NewChatDraft {
176
224
popup_open: bool,
177
225
searching: bool,
178
226
search_failed: bool,
227
search_session: SearchSession,
179
228
generation: u64,
180
229
search: Option<Task<()>>,
181
230
_subscriptions: Vec<Subscription>,
@@ -203,6 +252,7 @@ impl NewChatDraft {
203
252
popup_open: true,
204
253
searching: false,
205
254
search_failed: false,
255
search_session: SearchSession::new(),
206
256
generation: 0,
207
257
search: None,
208
258
_subscriptions: subscriptions,
@@ -353,10 +403,20 @@ impl NewChatDraft {
353
403
} else if let Some(engine) = engine {
354
404
self.searching = true;
355
405
let generation = self.generation;
406
let search_session = self.search_session.clone();
356
407
self.search = Some(cx.spawn(async move |this, cx| {
357
408
cx.background_executor().timer(SEARCH_DEBOUNCE).await;
358
let receiver =
359
runtime::spawn(async move { engine.search_people(&query).await });
409
let receiver = runtime::spawn(async move {
410
let (directory, suggestions) = tokio::join!(
411
engine.search_people(&query),
412
engine
413
.server_suggestions_without_email_lookup(&search_session, &query,),
414
);
415
let suggestions = suggestions
416
.map(|suggestions| suggestions.people)
417
.unwrap_or_default();
418
(directory, suggestions)
419
});
360
420
let result = receiver.await;
361
421
this.update(cx, |this, cx| this.apply_search(generation, result, cx))
362
422
.ok();
@@ -370,7 +430,7 @@ impl NewChatDraft {
370
430
&mut self,
371
431
generation: u64,
372
432
result: Result<
373
teams_core::Result<Vec<graph::User>>,
433
(teams_core::Result<Vec<graph::User>>, Vec<SearchPerson>),
374
434
tokio::sync::oneshot::error::RecvError,
375
435
>,
376
436
cx: &mut Context<Self>,
@@ -385,7 +445,23 @@ impl NewChatDraft {
385
445
.nth(self.highlighted)
386
446
.map(|pick| pick.user_id);
387
447
match result {
388
Ok(Ok(users)) => self.remote = users.into_iter().filter_map(pick_from_user).collect(),
448
Ok((Ok(users), suggestions)) => {
449
self.search_failed = false;
450
self.remote = merge_remote(
451
suggestions
452
.iter()
453
.filter_map(pick_from_search_person)
454
.collect(),
455
users.into_iter().filter_map(pick_from_user).collect(),
456
);
457
}
458
Ok((Err(_), suggestions)) if !suggestions.is_empty() => {
459
self.search_failed = false;
460
self.remote = suggestions
461
.iter()
462
.filter_map(pick_from_search_person)
463
.collect();
464
}
389
465
_ => self.search_failed = true,
390
466
}
391
467
self.highlighted = held
@@ -512,7 +588,7 @@ impl NewChatDraft {
512
588
"People"
513
589
};
514
590
let rows = results.into_iter().enumerate().map(|(index, pick)| {
515
let detail = pick.mail.clone().unwrap_or_default();
591
let detail = pick_detail(&pick);
516
592
let chosen = pick.clone();
517
593
h_flex()
518
594
.id(ElementId::Name(format!("new-chat-result-{index}").into()))
@@ -836,9 +912,10 @@ mod tests {
836
912
use store::{ChatRecord, MemberRecord};
837
913
838
914
use super::{
839
EnterAction, Pick, composer_placeholder, enter_action, search_results, suggested_people,
915
composer_placeholder, enter_action, merge_remote, pick_detail, search_results,
916
suggested_people, EnterAction, Pick,
840
917
};
841
use crate::data::{Person, existing_one_on_one};
918
use crate::data::{existing_one_on_one, Person};
842
919
843
920
fn me() -> Person {
844
921
Person {
@@ -852,6 +929,7 @@ mod tests {
852
929
user_id: user_id.into(),
853
930
name: name.into(),
854
931
mail: mail.map(str::to_owned),
932
organization: None,
855
933
}
856
934
}
857
935
@@ -925,6 +1003,19 @@ mod tests {
925
1003
assert!(found.iter().all(|pick| pick.user_id != "u0"));
926
1004
}
927
1005
1006
#[test]
1007
fn suggestion_people_lead_and_keep_their_organization() {
1008
let suggestions = vec![Pick {
1009
organization: Some("Other AG".into()),
1010
..pick("ada", "Ada", Some("ada@other.example"))
1011
}];
1012
let directory = vec![pick("ada", "Ada Directory", Some("ada@other.example"))];
1013
let merged = merge_remote(suggestions, directory);
1014
assert_eq!(merged.len(), 1);
1015
assert_eq!(merged[0].name, "Ada");
1016
assert_eq!(pick_detail(&merged[0]), "ada@other.example · Other AG");
1017
}
1018
928
1019
#[test]
929
1020
fn local_search_matches_the_mail_address() {
930
1021
let known = vec![pick("ann", "Ann", Some("a.nowak@example.com"))];
@@ -10,6 +10,7 @@ use gpui_kit::component::{10
use gpui_kit::prelude::FluentBuilder as _;10
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::*;11
use gpui_kit::*;12
use store::ChatRecord;12
use store::ChatRecord;13
use teams_core::substrate_search::{SearchPerson, SearchSession};13
use teams_core::MentionCandidate;14
use teams_core::MentionCandidate;14
15
15
use super::avatar::person_avatar;16
use super::avatar::person_avatar;@@ -39,6 +40,7 @@ pub struct Pick {39
pub user_id: String,40
pub user_id: String,40
pub name: String,41
pub name: String,41
pub mail: Option<String>,42
pub mail: Option<String>,43
pub organization: Option<String>,42
}44
}43
45
44
pub enum NewChatEvent {46
pub enum NewChatEvent {@@ -78,6 +80,7 @@ fn people_in(chats: &[ChatRecord], me: Option<&Person>, one_on_one_only: bool) -78
user_id,80
user_id,79
name,81
name,80
mail: None,82
mail: None,83
organization: None,81
})84
})82
})85
})83
.collect()86
.collect()@@ -143,22 +146,67 @@ pub fn composer_placeholder(chips: &[Pick], group_name: &str) -> String {143
}146
}144
}147
}145
148
149
fn pick_detail(pick: &Pick) -> String {150
match (&pick.mail, pick.organization.as_deref()) {151
(Some(mail), Some(organization)) if !organization.is_empty() => {152
format!("{mail} · {organization}")153
}154
(Some(mail), _) => mail.clone(),155
(None, Some(organization)) if !organization.is_empty() => organization.to_owned(),156
_ => String::new(),157
}158
}159
146
fn pick_from_user(user: graph::User) -> Option<Pick> {160
fn pick_from_user(user: graph::User) -> Option<Pick> {147
let mail = user.mail.or(user.user_principal_name);161
let mail = user.mail.or(user.user_principal_name);148
let name = user.display_name.or_else(|| mail.clone())?;162
let name = user.display_name.or_else(|| mail.clone())?;163
let organization =164
teams_core::native::known_profile(&user.id).and_then(|profile| profile.tenant_name);149
Some(Pick {165
Some(Pick {150
user_id: user.id,166
user_id: user.id,151
name,167
name,152
mail,168
mail,169
organization,170
})171
}172
173
fn pick_from_search_person(person: &SearchPerson) -> Option<Pick> {174
let user_id = person.user_id.clone()?;175
let mail = person176
.email_addresses177
.first()178
.cloned()179
.or_else(|| person.user_principal_name.clone());180
let name = if person.display_name.is_empty() {181
mail.clone()?182
} else {183
person.display_name.clone()184
};185
let organization = person.company_name.clone().filter(|name| !name.is_empty());186
Some(Pick {187
user_id,188
name,189
mail,190
organization,153
})191
})154
}192
}155
193
194
pub fn merge_remote(suggestions: Vec<Pick>, directory: Vec<Pick>) -> Vec<Pick> {195
let mut seen = HashSet::new();196
suggestions197
.into_iter()198
.chain(directory)199
.filter(|pick| seen.insert(pick.user_id.clone()))200
.collect()201
}202
156
fn pick_from_candidate(candidate: MentionCandidate) -> Option<Pick> {203
fn pick_from_candidate(candidate: MentionCandidate) -> Option<Pick> {157
match candidate {204
match candidate {158
MentionCandidate::Person(person) => Some(Pick {205
MentionCandidate::Person(person) => Some(Pick {159
user_id: person.user_id,206
user_id: person.user_id,160
name: person.display_name,207
name: person.display_name,161
mail: person.mail,208
mail: person.mail,209
organization: None,162
}),210
}),163
_ => None,211
_ => None,164
}212
}@@ -176,6 +224,7 @@ pub struct NewChatDraft {176
popup_open: bool,224
popup_open: bool,177
searching: bool,225
searching: bool,178
search_failed: bool,226
search_failed: bool,227
search_session: SearchSession,179
generation: u64,228
generation: u64,180
search: Option<Task<()>>,229
search: Option<Task<()>>,181
_subscriptions: Vec<Subscription>,230
_subscriptions: Vec<Subscription>,@@ -203,6 +252,7 @@ impl NewChatDraft {203
popup_open: true,252
popup_open: true,204
searching: false,253
searching: false,205
search_failed: false,254
search_failed: false,255
search_session: SearchSession::new(),206
generation: 0,256
generation: 0,207
search: None,257
search: None,208
_subscriptions: subscriptions,258
_subscriptions: subscriptions,@@ -353,10 +403,20 @@ impl NewChatDraft {353
} else if let Some(engine) = engine {403
} else if let Some(engine) = engine {354
self.searching = true;404
self.searching = true;355
let generation = self.generation;405
let generation = self.generation;406
let search_session = self.search_session.clone();356
self.search = Some(cx.spawn(async move |this, cx| {407
self.search = Some(cx.spawn(async move |this, cx| {357
cx.background_executor().timer(SEARCH_DEBOUNCE).await;408
cx.background_executor().timer(SEARCH_DEBOUNCE).await;358
let receiver =409
let receiver = runtime::spawn(async move {359
runtime::spawn(async move { engine.search_people(&query).await });410
let (directory, suggestions) = tokio::join!(411
engine.search_people(&query),412
engine413
.server_suggestions_without_email_lookup(&search_session, &query,),414
);415
let suggestions = suggestions416
.map(|suggestions| suggestions.people)417
.unwrap_or_default();418
(directory, suggestions)419
});360
let result = receiver.await;420
let result = receiver.await;361
this.update(cx, |this, cx| this.apply_search(generation, result, cx))421
this.update(cx, |this, cx| this.apply_search(generation, result, cx))362
.ok();422
.ok();@@ -370,7 +430,7 @@ impl NewChatDraft {370
&mut self,430
&mut self,371
generation: u64,431
generation: u64,372
result: Result<432
result: Result<373
teams_core::Result<Vec<graph::User>>,433
(teams_core::Result<Vec<graph::User>>, Vec<SearchPerson>),374
tokio::sync::oneshot::error::RecvError,434
tokio::sync::oneshot::error::RecvError,375
>,435
>,376
cx: &mut Context<Self>,436
cx: &mut Context<Self>,@@ -385,7 +445,23 @@ impl NewChatDraft {385
.nth(self.highlighted)445
.nth(self.highlighted)386
.map(|pick| pick.user_id);446
.map(|pick| pick.user_id);387
match result {447
match result {388
Ok(Ok(users)) => self.remote = users.into_iter().filter_map(pick_from_user).collect(),448
Ok((Ok(users), suggestions)) => {449
self.search_failed = false;450
self.remote = merge_remote(451
suggestions452
.iter()453
.filter_map(pick_from_search_person)454
.collect(),455
users.into_iter().filter_map(pick_from_user).collect(),456
);457
}458
Ok((Err(_), suggestions)) if !suggestions.is_empty() => {459
self.search_failed = false;460
self.remote = suggestions461
.iter()462
.filter_map(pick_from_search_person)463
.collect();464
}389
_ => self.search_failed = true,465
_ => self.search_failed = true,390
}466
}391
self.highlighted = held467
self.highlighted = held@@ -512,7 +588,7 @@ impl NewChatDraft {512
"People"588
"People"513
};589
};514
let rows = results.into_iter().enumerate().map(|(index, pick)| {590
let rows = results.into_iter().enumerate().map(|(index, pick)| {515
let detail = pick.mail.clone().unwrap_or_default();591
let detail = pick_detail(&pick);516
let chosen = pick.clone();592
let chosen = pick.clone();517
h_flex()593
h_flex()518
.id(ElementId::Name(format!("new-chat-result-{index}").into()))594
.id(ElementId::Name(format!("new-chat-result-{index}").into()))@@ -836,9 +912,10 @@ mod tests {836
use store::{ChatRecord, MemberRecord};912
use store::{ChatRecord, MemberRecord};837
913
838
use super::{914
use super::{839
EnterAction, Pick, composer_placeholder, enter_action, search_results, suggested_people,915
composer_placeholder, enter_action, merge_remote, pick_detail, search_results,916
suggested_people, EnterAction, Pick,840
};917
};841
use crate::data::{Person, existing_one_on_one};918
use crate::data::{existing_one_on_one, Person};842
919
843
fn me() -> Person {920
fn me() -> Person {844
Person {921
Person {@@ -852,6 +929,7 @@ mod tests {852
user_id: user_id.into(),929
user_id: user_id.into(),853
name: name.into(),930
name: name.into(),854
mail: mail.map(str::to_owned),931
mail: mail.map(str::to_owned),932
organization: None,855
}933
}856
}934
}857
935
@@ -925,6 +1003,19 @@ mod tests {925
assert!(found.iter().all(|pick| pick.user_id != "u0"));1003
assert!(found.iter().all(|pick| pick.user_id != "u0"));926
}1004
}927
1005
1006
#[test]1007
fn suggestion_people_lead_and_keep_their_organization() {1008
let suggestions = vec![Pick {1009
organization: Some("Other AG".into()),1010
..pick("ada", "Ada", Some("ada@other.example"))1011
}];1012
let directory = vec![pick("ada", "Ada Directory", Some("ada@other.example"))];1013
let merged = merge_remote(suggestions, directory);1014
assert_eq!(merged.len(), 1);1015
assert_eq!(merged[0].name, "Ada");1016
assert_eq!(pick_detail(&merged[0]), "ada@other.example · Other AG");1017
}1018
928
#[test]1019
#[test]929
fn local_search_matches_the_mail_address() {1020
fn local_search_matches_the_mail_address() {930
let known = vec![pick("ann", "Ann", Some("a.nowak@example.com"))];1021
let known = vec![pick("ann", "Ann", Some("a.nowak@example.com"))];@@ -275,6 +275,7 @@ impl ProfileCard {
275
275
user_id: user_id.clone(),
276
276
name: name.clone(),
277
277
mail: email,
278
organization: None,
278
279
};
279
280
let chat_id = user_id.clone();
280
281
let (video_id, audio_id) = (user_id.clone(), user_id.clone());
@@ -275,6 +275,7 @@ impl ProfileCard {275
user_id: user_id.clone(),275
user_id: user_id.clone(),276
name: name.clone(),276
name: name.clone(),277
mail: email,277
mail: email,278
organization: None,278
};279
};279
let chat_id = user_id.clone();280
let chat_id = user_id.clone();280
let (video_id, audio_id) = (user_id.clone(), user_id.clone());281
let (video_id, audio_id) = (user_id.clone(), user_id.clone());@@ -24,12 +24,7 @@ pub fn people_results(
24
24
.iter()
25
25
.filter_map(|person| {
26
26
let user_id = person.user_id.clone()?;
27
let subtitle = [person.job_title.as_deref(), person.department.as_deref()]
28
.into_iter()
29
.flatten()
30
.filter(|part| !part.is_empty())
31
.collect::<Vec<_>>()
32
.join(", ");
27
let subtitle = person_subtitle(person);
33
28
Some(PersonResult {
34
29
user_id,
35
30
name: person.display_name.clone(),
@@ -42,6 +37,35 @@ pub fn people_results(
42
37
.collect()
43
38
}
44
39
40
fn person_subtitle(person: &SearchPerson) -> String {
41
let primary = person
42
.job_title
43
.as_deref()
44
.filter(|title| !title.is_empty())
45
.or_else(|| person.email_addresses.first().map(String::as_str));
46
let extra = person
47
.company_name
48
.as_deref()
49
.filter(|name| !name.is_empty())
50
.or_else(|| {
51
person
52
.job_title
53
.as_deref()
54
.filter(|title| !title.is_empty())
55
.and_then(|_| {
56
person
57
.department
58
.as_deref()
59
.filter(|department| !department.is_empty())
60
})
61
});
62
[primary, extra]
63
.into_iter()
64
.flatten()
65
.collect::<Vec<_>>()
66
.join(", ")
67
}
68
45
69
pub fn server_message_results(
46
70
messages: &[SearchMessage],
47
71
conversations: &HashMap<String, (String, Selection)>,
@@ -148,6 +172,17 @@ mod tests {
148
172
);
149
173
}
150
174
175
#[test]
176
fn an_external_person_shows_email_and_organization() {
177
let mut person = person("ada", "Ada Lovelace");
178
person.job_title = None;
179
person.department = None;
180
person.email_addresses = vec!["ada@other.example".into()];
181
person.company_name = Some("Other AG".into());
182
let results = people_results(&[person], &HashSet::new(), None, 5);
183
assert_eq!(results[0].subtitle, "ada@other.example, Other AG");
184
}
185
151
186
#[test]
152
187
fn server_messages_need_a_known_conversation_and_keep_highlights() {
153
188
let conversations = HashMap::from([(
@@ -24,12 +24,7 @@ pub fn people_results(24
.iter()24
.iter()25
.filter_map(|person| {25
.filter_map(|person| {26
let user_id = person.user_id.clone()?;26
let user_id = person.user_id.clone()?;27
let subtitle = [person.job_title.as_deref(), person.department.as_deref()]27
let subtitle = person_subtitle(person);28
.into_iter()29
.flatten()30
.filter(|part| !part.is_empty())31
.collect::<Vec<_>>()32
.join(", ");33
Some(PersonResult {28
Some(PersonResult {34
user_id,29
user_id,35
name: person.display_name.clone(),30
name: person.display_name.clone(),@@ -42,6 +37,35 @@ pub fn people_results(42
.collect()37
.collect()43
}38
}44
39
40
fn person_subtitle(person: &SearchPerson) -> String {41
let primary = person42
.job_title43
.as_deref()44
.filter(|title| !title.is_empty())45
.or_else(|| person.email_addresses.first().map(String::as_str));46
let extra = person47
.company_name48
.as_deref()49
.filter(|name| !name.is_empty())50
.or_else(|| {51
person52
.job_title53
.as_deref()54
.filter(|title| !title.is_empty())55
.and_then(|_| {56
person57
.department58
.as_deref()59
.filter(|department| !department.is_empty())60
})61
});62
[primary, extra]63
.into_iter()64
.flatten()65
.collect::<Vec<_>>()66
.join(", ")67
}68
45
pub fn server_message_results(69
pub fn server_message_results(46
messages: &[SearchMessage],70
messages: &[SearchMessage],47
conversations: &HashMap<String, (String, Selection)>,71
conversations: &HashMap<String, (String, Selection)>,@@ -148,6 +172,17 @@ mod tests {148
);172
);149
}173
}150
174
175
#[test]176
fn an_external_person_shows_email_and_organization() {177
let mut person = person("ada", "Ada Lovelace");178
person.job_title = None;179
person.department = None;180
person.email_addresses = vec!["ada@other.example".into()];181
person.company_name = Some("Other AG".into());182
let results = people_results(&[person], &HashSet::new(), None, 5);183
assert_eq!(results[0].subtitle, "ada@other.example, Other AG");184
}185
151
#[test]186
#[test]152
fn server_messages_need_a_known_conversation_and_keep_highlights() {187
fn server_messages_need_a_known_conversation_and_keep_highlights() {153
let conversations = HashMap::from([(188
let conversations = HashMap::from([(@@ -384,10 +384,20 @@ fn members(value: &Value, key: &str) -> Vec<ChatMember> {
384
384
.unwrap_or_default()
385
385
}
386
386
387
fn person_id(value: &Value) -> Option<String> {
388
string(value, "ExternalDirectoryObjectId").or_else(|| {
389
string(value, "MRI")
390
.as_deref()
391
.and_then(|mri| mri.strip_prefix("8:orgid:"))
392
.filter(|id| !id.is_empty())
393
.map(str::to_owned)
394
})
395
}
396
387
397
fn person(value: &Value) -> Option<SearchPerson> {
388
398
Some(SearchPerson {
389
399
reference_id: string(value, "ReferenceId"),
390
user_id: string(value, "ExternalDirectoryObjectId"),
400
user_id: person_id(value),
391
401
mri: string(value, "MRI"),
392
402
display_name: string(value, "DisplayName")?,
393
403
given_name: string(value, "GivenName"),
@@ -384,10 +384,20 @@ fn members(value: &Value, key: &str) -> Vec<ChatMember> {384
.unwrap_or_default()384
.unwrap_or_default()385
}385
}386
386
387
fn person_id(value: &Value) -> Option<String> {388
string(value, "ExternalDirectoryObjectId").or_else(|| {389
string(value, "MRI")390
.as_deref()391
.and_then(|mri| mri.strip_prefix("8:orgid:"))392
.filter(|id| !id.is_empty())393
.map(str::to_owned)394
})395
}396
387
fn person(value: &Value) -> Option<SearchPerson> {397
fn person(value: &Value) -> Option<SearchPerson> {388
Some(SearchPerson {398
Some(SearchPerson {389
reference_id: string(value, "ReferenceId"),399
reference_id: string(value, "ReferenceId"),390
user_id: string(value, "ExternalDirectoryObjectId"),400
user_id: person_id(value),391
mri: string(value, "MRI"),401
mri: string(value, "MRI"),392
display_name: string(value, "DisplayName")?,402
display_name: string(value, "DisplayName")?,393
given_name: string(value, "GivenName"),403
given_name: string(value, "GivenName"),@@ -265,7 +265,17 @@ fn people_filter() -> Value {
265
265
any_term("PeopleType", &["Person", "Other"]),
266
266
any_term(
267
267
"PeopleSubtype",
268
&["OrganizationUser", "MTOUser", "PersonalContact", "Guest"],
268
&[
269
"OrganizationUser",
270
"MTOUser",
271
"PersonalContact",
272
"Guest",
273
"ImplicitContact",
274
"ChatImplicitContact",
275
"OrganizationContact",
276
"EDUser",
277
"Unknown",
278
],
269
279
),
270
280
any_term("Flags", &["NonHidden"]),
271
281
]})
@@ -297,6 +307,18 @@ mod tests {
297
307
body["EntityRequests"][0]["Provenances"],
298
308
json!(["Mailbox", "Directory"])
299
309
);
310
let subtypes = body["EntityRequests"][0]["Filter"]["And"][1]["Or"]
311
.as_array()
312
.unwrap();
313
let names: Vec<&str> = subtypes
314
.iter()
315
.map(|term| term["Term"]["PeopleSubtype"].as_str().unwrap())
316
.collect();
317
assert!(names.contains(&"EDUser"));
318
assert!(names.contains(&"ChatImplicitContact"));
319
assert!(names.contains(&"ImplicitContact"));
320
assert!(names.contains(&"OrganizationContact"));
321
assert!(names.contains(&"Unknown"));
300
322
}
301
323
302
324
#[test]
@@ -265,7 +265,17 @@ fn people_filter() -> Value {265
any_term("PeopleType", &["Person", "Other"]),265
any_term("PeopleType", &["Person", "Other"]),266
any_term(266
any_term(267
"PeopleSubtype",267
"PeopleSubtype",268
&["OrganizationUser", "MTOUser", "PersonalContact", "Guest"],268
&[269
"OrganizationUser",270
"MTOUser",271
"PersonalContact",272
"Guest",273
"ImplicitContact",274
"ChatImplicitContact",275
"OrganizationContact",276
"EDUser",277
"Unknown",278
],269
),279
),270
any_term("Flags", &["NonHidden"]),280
any_term("Flags", &["NonHidden"]),271
]})281
]})@@ -297,6 +307,18 @@ mod tests {297
body["EntityRequests"][0]["Provenances"],307
body["EntityRequests"][0]["Provenances"],298
json!(["Mailbox", "Directory"])308
json!(["Mailbox", "Directory"])299
);309
);310
let subtypes = body["EntityRequests"][0]["Filter"]["And"][1]["Or"]311
.as_array()312
.unwrap();313
let names: Vec<&str> = subtypes314
.iter()315
.map(|term| term["Term"]["PeopleSubtype"].as_str().unwrap())316
.collect();317
assert!(names.contains(&"EDUser"));318
assert!(names.contains(&"ChatImplicitContact"));319
assert!(names.contains(&"ImplicitContact"));320
assert!(names.contains(&"OrganizationContact"));321
assert!(names.contains(&"Unknown"));300
}322
}301
323
302
#[test]324
#[test]@@ -1,7 +1,7 @@
1
1
use std::collections::VecDeque;
2
2
use std::sync::Mutex;
3
3
4
use serde_json::{Value, json};
4
use serde_json::{json, Value};
5
5
use session::{ApiResponse, Method, Request};
6
6
7
7
use super::*;
@@ -197,6 +197,19 @@ fn suggestions_fixture_parses_every_group() {
197
197
assert_eq!(suggestions.best_matches[0].group, "People");
198
198
}
199
199
200
#[test]
201
fn a_person_without_a_directory_id_uses_the_orgid_mri() {
202
let suggestions = parse_suggestions(&json!({"Groups": [{"Type": "People", "Suggestions": [{
203
"DisplayName": "Ada Lovelace",
204
"MRI": "8:orgid:ada-id",
205
"EmailAddresses": ["ada@other.example"],
206
"CompanyName": "Other AG"
207
}]}]}));
208
let person = &suggestions.people[0];
209
assert_eq!(person.user_id.as_deref(), Some("ada-id"));
210
assert_eq!(person.company_name.as_deref(), Some("Other AG"));
211
}
212
200
213
#[test]
201
214
fn query_fixture_maps_channel_replies_to_their_root() {
202
215
let results = parse_query_results(&fixture(QUERY));
@@ -1,7 +1,7 @@1
use std::collections::VecDeque;1
use std::collections::VecDeque;2
use std::sync::Mutex;2
use std::sync::Mutex;3
3
4
use serde_json::{Value, json};4
use serde_json::{json, Value};5
use session::{ApiResponse, Method, Request};5
use session::{ApiResponse, Method, Request};6
6
7
use super::*;7
use super::*;@@ -197,6 +197,19 @@ fn suggestions_fixture_parses_every_group() {197
assert_eq!(suggestions.best_matches[0].group, "People");197
assert_eq!(suggestions.best_matches[0].group, "People");198
}198
}199
199
200
#[test]201
fn a_person_without_a_directory_id_uses_the_orgid_mri() {202
let suggestions = parse_suggestions(&json!({"Groups": [{"Type": "People", "Suggestions": [{203
"DisplayName": "Ada Lovelace",204
"MRI": "8:orgid:ada-id",205
"EmailAddresses": ["ada@other.example"],206
"CompanyName": "Other AG"207
}]}]}));208
let person = &suggestions.people[0];209
assert_eq!(person.user_id.as_deref(), Some("ada-id"));210
assert_eq!(person.company_name.as_deref(), Some("Other AG"));211
}212
200
#[test]213
#[test]201
fn query_fixture_maps_channel_replies_to_their_root() {214
fn query_fixture_maps_channel_replies_to_their_root() {202
let results = parse_query_results(&fixture(QUERY));215
let results = parse_query_results(&fixture(QUERY));@@ -8,6 +8,7 @@ use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
8
9
9
const SKYPE_SCOPE: &str = "user_impersonation";
10
10
const ORGID_PREFIX: &str = "8:orgid:";
11
const LIVE_PREFIX: &str = "8:live:";
11
12
const PROFILE_QUERY: &str =
12
13
"isMailAddress=false&enableGuest=true&includeIBBarredUsers=true&skypeTeamsInfo=true";
13
14
const PROFILES_PER_REQUEST: usize = 100;
@@ -62,13 +63,13 @@ impl<T: CsaTransport> UserProfiles<T> {
62
63
let answer = self
63
64
.transport
64
65
.send(with_headers(Request::get(format!(
65
"{}/{}/externalsearchv3?includeTFLUsers=true",
66
"{}/{}/externalsearchv3?includeTFLUsers=true&includeEDUsers=true",
66
67
self.users_url,
67
68
encode(email.trim())
68
69
))))
69
70
.await?;
70
71
ensure_success(&answer)?;
71
Ok(parse_user_profiles(&json!({"value": answer.body})))
72
Ok(parse_user_profiles(&answer.body))
72
73
}
73
74
74
75
async fn post_mris(&self, url: &str, user_ids: &[String]) -> Result<Vec<UserProfile>> {
@@ -93,28 +94,37 @@ impl<T: CsaTransport> UserProfiles<T> {
93
94
}
94
95
}
95
96
97
fn profile_items(body: &Value) -> Vec<&Value> {
98
match body {
99
Value::Array(items) => items.iter().collect(),
100
Value::Object(_) => {
101
if let Some(items) = body.get("value").and_then(Value::as_array) {
102
return items.iter().collect();
103
}
104
if let Some(profile) = body.get("value").filter(|value| value.is_object()) {
105
return vec![profile];
106
}
107
if body.get("mri").is_some() || body.get("objectId").is_some() {
108
return vec![body];
109
}
110
Vec::new()
111
}
112
_ => Vec::new(),
113
}
114
}
115
96
116
pub 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()
117
profile_items(body)
118
.into_iter()
102
119
.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();
120
let user_id = profile_user_id(profile)?;
114
121
Some(UserProfile {
115
122
user_id,
116
123
display_name: text(profile, "displayName"),
117
email: text(profile, "email"),
124
email: text(profile, "email")
125
.or_else(|| text(profile, "mail"))
126
.or_else(|| email_from_info(profile))
127
.or_else(|| text(profile, "userPrincipalName")),
118
128
user_principal_name: text(profile, "userPrincipalName"),
119
129
job_title: text(profile, "jobTitle"),
120
130
department: text(profile, "department"),
@@ -124,6 +134,40 @@ pub fn parse_user_profiles(body: &Value) -> Vec<UserProfile> {
124
134
.collect()
125
135
}
126
136
137
fn profile_user_id(profile: &Value) -> Option<String> {
138
if let Some(id) = text(profile, "objectId") {
139
return Some(id);
140
}
141
let mri = profile.get("mri").and_then(Value::as_str)?;
142
if let Some(id) = mri.strip_prefix(ORGID_PREFIX).filter(|id| !id.is_empty()) {
143
return Some(id.to_owned());
144
}
145
mri.starts_with(LIVE_PREFIX)
146
.then(|| mri.to_owned())
147
.filter(|id| id.len() > LIVE_PREFIX.len())
148
}
149
150
fn email_from_info(profile: &Value) -> Option<String> {
151
match profile.get("emailsInfo")? {
152
Value::String(value) => text_value(value),
153
Value::Array(items) => items.iter().find_map(email_info_item),
154
Value::Object(_) => email_info_item(profile.get("emailsInfo")?),
155
_ => None,
156
}
157
}
158
159
fn email_info_item(item: &Value) -> Option<String> {
160
text(item, "address")
161
.or_else(|| text(item, "email"))
162
.or_else(|| text(item, "smtp"))
163
.or_else(|| item.as_str().and_then(text_value))
164
}
165
166
fn text_value(value: &str) -> Option<String> {
167
let value = value.trim();
168
(!value.is_empty()).then(|| value.to_owned())
169
}
170
127
171
fn text(profile: &Value, key: &str) -> Option<String> {
128
172
profile
129
173
.get(key)
@@ -194,6 +238,55 @@ mod tests {
194
238
assert_eq!(requests[0].body, Some(json!(["8:orgid:ann"])));
195
239
}
196
240
241
#[tokio::test]
242
async fn external_search_includes_federated_work_accounts() {
243
let canned = Canned {
244
requests: Mutex::new(Vec::new()),
245
};
246
UserProfiles::with_transport(&canned, "emea")
247
.search_external("ada@other.example")
248
.await
249
.unwrap();
250
let requests = canned.requests.lock().unwrap();
251
assert!(requests[0].url.contains("includeTFLUsers=true"));
252
assert!(requests[0].url.contains("includeEDUsers=true"));
253
assert!(
254
requests[0].url.contains("ada%40other.example")
255
|| requests[0].url.contains("ada@other.example")
256
);
257
}
258
259
#[test]
260
fn an_external_profile_reads_mail_or_the_principal_name() {
261
let from_mail = parse_user_profiles(&json!(
262
{"mri": "8:orgid:ada", "displayName": "Ada", "mail": "ada@other.example"}
263
));
264
assert_eq!(from_mail[0].email.as_deref(), Some("ada@other.example"));
265
let from_upn = parse_user_profiles(&json!({"value": {
266
"objectId": "bea",
267
"displayName": "Bea",
268
"userPrincipalName": "bea@other.example"
269
}}));
270
assert_eq!(from_upn[0].user_id, "bea");
271
assert_eq!(from_upn[0].email.as_deref(), Some("bea@other.example"));
272
}
273
274
#[test]
275
fn a_personal_account_keeps_its_live_mri_and_email() {
276
let profiles = parse_user_profiles(&json!([{
277
"mri": "8:live:cid",
278
"displayName": "Joe",
279
"userPrincipalName": "live.cid",
280
"emailsInfo": [{"address": "joe@example.net"}],
281
"skypeId": "x",
282
"type": "TflUser"
283
}]));
284
assert_eq!(profiles.len(), 1);
285
assert_eq!(profiles[0].user_id, "8:live:cid");
286
assert_eq!(profiles[0].email.as_deref(), Some("joe@example.net"));
287
assert_eq!(profiles[0].display_name.as_deref(), Some("Joe"));
288
}
289
197
290
#[test]
198
291
fn a_federated_profile_carries_its_organization() {
199
292
let profiles = parse_user_profiles(&json!({"value": [
@@ -8,6 +8,7 @@ use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};8
8
9
const SKYPE_SCOPE: &str = "user_impersonation";9
const SKYPE_SCOPE: &str = "user_impersonation";10
const ORGID_PREFIX: &str = "8:orgid:";10
const ORGID_PREFIX: &str = "8:orgid:";11
const LIVE_PREFIX: &str = "8:live:";11
const PROFILE_QUERY: &str =12
const PROFILE_QUERY: &str =12
"isMailAddress=false&enableGuest=true&includeIBBarredUsers=true&skypeTeamsInfo=true";13
"isMailAddress=false&enableGuest=true&includeIBBarredUsers=true&skypeTeamsInfo=true";13
const PROFILES_PER_REQUEST: usize = 100;14
const PROFILES_PER_REQUEST: usize = 100;@@ -62,13 +63,13 @@ impl<T: CsaTransport> UserProfiles<T> {62
let answer = self63
let answer = self63
.transport64
.transport64
.send(with_headers(Request::get(format!(65
.send(with_headers(Request::get(format!(65
"{}/{}/externalsearchv3?includeTFLUsers=true",66
"{}/{}/externalsearchv3?includeTFLUsers=true&includeEDUsers=true",66
self.users_url,67
self.users_url,67
encode(email.trim())68
encode(email.trim())68
))))69
))))69
.await?;70
.await?;70
ensure_success(&answer)?;71
ensure_success(&answer)?;71
Ok(parse_user_profiles(&json!({"value": answer.body})))72
Ok(parse_user_profiles(&answer.body))72
}73
}73
74
74
async fn post_mris(&self, url: &str, user_ids: &[String]) -> Result<Vec<UserProfile>> {75
async fn post_mris(&self, url: &str, user_ids: &[String]) -> Result<Vec<UserProfile>> {@@ -93,28 +94,37 @@ impl<T: CsaTransport> UserProfiles<T> {93
}94
}94
}95
}95
96
97
fn profile_items(body: &Value) -> Vec<&Value> {98
match body {99
Value::Array(items) => items.iter().collect(),100
Value::Object(_) => {101
if let Some(items) = body.get("value").and_then(Value::as_array) {102
return items.iter().collect();103
}104
if let Some(profile) = body.get("value").filter(|value| value.is_object()) {105
return vec![profile];106
}107
if body.get("mri").is_some() || body.get("objectId").is_some() {108
return vec![body];109
}110
Vec::new()111
}112
_ => Vec::new(),113
}114
}115
96
pub fn parse_user_profiles(body: &Value) -> Vec<UserProfile> {116
pub fn parse_user_profiles(body: &Value) -> Vec<UserProfile> {97
body.get("value")117
profile_items(body)98
.and_then(Value::as_array)118
.into_iter()99
.map(Vec::as_slice)100
.unwrap_or_default()101
.iter()102
.filter_map(|profile| {119
.filter_map(|profile| {103
let user_id = profile120
let user_id = profile_user_id(profile)?;104
.get("objectId")105
.and_then(Value::as_str)106
.filter(|id| !id.is_empty())107
.or_else(|| {108
profile109
.get("mri")110
.and_then(Value::as_str)?111
.strip_prefix(ORGID_PREFIX)112
})?113
.to_owned();114
Some(UserProfile {121
Some(UserProfile {115
user_id,122
user_id,116
display_name: text(profile, "displayName"),123
display_name: text(profile, "displayName"),117
email: text(profile, "email"),124
email: text(profile, "email")125
.or_else(|| text(profile, "mail"))126
.or_else(|| email_from_info(profile))127
.or_else(|| text(profile, "userPrincipalName")),118
user_principal_name: text(profile, "userPrincipalName"),128
user_principal_name: text(profile, "userPrincipalName"),119
job_title: text(profile, "jobTitle"),129
job_title: text(profile, "jobTitle"),120
department: text(profile, "department"),130
department: text(profile, "department"),@@ -124,6 +134,40 @@ pub fn parse_user_profiles(body: &Value) -> Vec<UserProfile> {124
.collect()134
.collect()125
}135
}126
136
137
fn profile_user_id(profile: &Value) -> Option<String> {138
if let Some(id) = text(profile, "objectId") {139
return Some(id);140
}141
let mri = profile.get("mri").and_then(Value::as_str)?;142
if let Some(id) = mri.strip_prefix(ORGID_PREFIX).filter(|id| !id.is_empty()) {143
return Some(id.to_owned());144
}145
mri.starts_with(LIVE_PREFIX)146
.then(|| mri.to_owned())147
.filter(|id| id.len() > LIVE_PREFIX.len())148
}149
150
fn email_from_info(profile: &Value) -> Option<String> {151
match profile.get("emailsInfo")? {152
Value::String(value) => text_value(value),153
Value::Array(items) => items.iter().find_map(email_info_item),154
Value::Object(_) => email_info_item(profile.get("emailsInfo")?),155
_ => None,156
}157
}158
159
fn email_info_item(item: &Value) -> Option<String> {160
text(item, "address")161
.or_else(|| text(item, "email"))162
.or_else(|| text(item, "smtp"))163
.or_else(|| item.as_str().and_then(text_value))164
}165
166
fn text_value(value: &str) -> Option<String> {167
let value = value.trim();168
(!value.is_empty()).then(|| value.to_owned())169
}170
127
fn text(profile: &Value, key: &str) -> Option<String> {171
fn text(profile: &Value, key: &str) -> Option<String> {128
profile172
profile129
.get(key)173
.get(key)@@ -194,6 +238,55 @@ mod tests {194
assert_eq!(requests[0].body, Some(json!(["8:orgid:ann"])));238
assert_eq!(requests[0].body, Some(json!(["8:orgid:ann"])));195
}239
}196
240
241
#[tokio::test]242
async fn external_search_includes_federated_work_accounts() {243
let canned = Canned {244
requests: Mutex::new(Vec::new()),245
};246
UserProfiles::with_transport(&canned, "emea")247
.search_external("ada@other.example")248
.await249
.unwrap();250
let requests = canned.requests.lock().unwrap();251
assert!(requests[0].url.contains("includeTFLUsers=true"));252
assert!(requests[0].url.contains("includeEDUsers=true"));253
assert!(254
requests[0].url.contains("ada%40other.example")255
|| requests[0].url.contains("ada@other.example")256
);257
}258
259
#[test]260
fn an_external_profile_reads_mail_or_the_principal_name() {261
let from_mail = parse_user_profiles(&json!(262
{"mri": "8:orgid:ada", "displayName": "Ada", "mail": "ada@other.example"}263
));264
assert_eq!(from_mail[0].email.as_deref(), Some("ada@other.example"));265
let from_upn = parse_user_profiles(&json!({"value": {266
"objectId": "bea",267
"displayName": "Bea",268
"userPrincipalName": "bea@other.example"269
}}));270
assert_eq!(from_upn[0].user_id, "bea");271
assert_eq!(from_upn[0].email.as_deref(), Some("bea@other.example"));272
}273
274
#[test]275
fn a_personal_account_keeps_its_live_mri_and_email() {276
let profiles = parse_user_profiles(&json!([{277
"mri": "8:live:cid",278
"displayName": "Joe",279
"userPrincipalName": "live.cid",280
"emailsInfo": [{"address": "joe@example.net"}],281
"skypeId": "x",282
"type": "TflUser"283
}]));284
assert_eq!(profiles.len(), 1);285
assert_eq!(profiles[0].user_id, "8:live:cid");286
assert_eq!(profiles[0].email.as_deref(), Some("joe@example.net"));287
assert_eq!(profiles[0].display_name.as_deref(), Some("Joe"));288
}289
197
#[test]290
#[test]198
fn a_federated_profile_carries_its_organization() {291
fn a_federated_profile_carries_its_organization() {199
let profiles = parse_user_profiles(&json!({"value": [292
let profiles = parse_user_profiles(&json!({"value": [@@ -7,6 +7,7 @@ pub use chat::{NativeMember, chat_type, graph_chat, graph_chat_from_aggregator};
7
7
pub use message::graph_message;
8
8
pub use source::{
9
9
NativeChats, external_people, is_email_address, known_profile, remember_external,
10
user_has_address,
10
11
};
11
12
12
13
#[cfg(test)]
@@ -7,6 +7,7 @@ pub use chat::{NativeMember, chat_type, graph_chat, graph_chat_from_aggregator};7
pub use message::graph_message;7
pub use message::graph_message;8
pub use source::{8
pub use source::{9
NativeChats, external_people, is_email_address, known_profile, remember_external,9
NativeChats, external_people, is_email_address, known_profile, remember_external,10
user_has_address,10
};11
};11
12
12
#[cfg(test)]13
#[cfg(test)]@@ -315,6 +315,18 @@ pub fn remember_external(profiles: Vec<UserProfile>) -> Vec<graph::User> {
315
315
.collect()
316
316
}
317
317
318
pub fn user_has_address(
319
mail: Option<&str>,
320
user_principal_name: Option<&str>,
321
query: &str,
322
) -> bool {
323
let query = query.trim();
324
[mail, user_principal_name]
325
.into_iter()
326
.flatten()
327
.any(|address| address.eq_ignore_ascii_case(query))
328
}
329
318
330
pub fn is_email_address(query: &str) -> bool {
319
331
let query = query.trim();
320
332
query.split_once('@').is_some_and(|(local, domain)| {
@@ -393,4 +405,18 @@ mod tests {
393
405
assert!(!super::is_email_address("ann example@x.com"));
394
406
assert!(!super::is_email_address("@example.com"));
395
407
}
408
409
#[test]
410
fn an_address_matches_mail_or_the_principal_name() {
411
assert!(super::user_has_address(
412
None,
413
Some("Ada@Other.Example"),
414
"ada@other.example"
415
));
416
assert!(!super::user_has_address(
417
Some("other@example.com"),
418
Some("ada@other.example"),
419
"missing@example.com"
420
));
421
}
396
422
}
@@ -315,6 +315,18 @@ pub fn remember_external(profiles: Vec<UserProfile>) -> Vec<graph::User> {315
.collect()315
.collect()316
}316
}317
317
318
pub fn user_has_address(319
mail: Option<&str>,320
user_principal_name: Option<&str>,321
query: &str,322
) -> bool {323
let query = query.trim();324
[mail, user_principal_name]325
.into_iter()326
.flatten()327
.any(|address| address.eq_ignore_ascii_case(query))328
}329
318
pub fn is_email_address(query: &str) -> bool {330
pub fn is_email_address(query: &str) -> bool {319
let query = query.trim();331
let query = query.trim();320
query.split_once('@').is_some_and(|(local, domain)| {332
query.split_once('@').is_some_and(|(local, domain)| {@@ -393,4 +405,18 @@ mod tests {393
assert!(!super::is_email_address("ann example@x.com"));405
assert!(!super::is_email_address("ann example@x.com"));394
assert!(!super::is_email_address("@example.com"));406
assert!(!super::is_email_address("@example.com"));395
}407
}408
409
#[test]410
fn an_address_matches_mail_or_the_principal_name() {411
assert!(super::user_has_address(412
None,413
Some("Ada@Other.Example"),414
"ada@other.example"415
));416
assert!(!super::user_has_address(417
Some("other@example.com"),418
Some("ada@other.example"),419
"missing@example.com"420
));421
}396
}422
}@@ -7,9 +7,9 @@ use chatsvc::substrate_search::{
7
7
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
8
8
};
9
9
use chatsvc::{
10
ActivityFeed, ActivitySnapshot, AppConsumptionHorizon, ChatNotificationMode,
11
ChatNotificationWrite, ChatSettingChange, ChatSettingsClient, ChatSettingsDocument,
12
DesktopNotifications, UserSettings, parse_app_consumption_horizon,
10
parse_app_consumption_horizon, ActivityFeed, ActivitySnapshot, AppConsumptionHorizon,
11
ChatNotificationMode, ChatNotificationWrite, ChatSettingChange, ChatSettingsClient,
12
ChatSettingsDocument, DesktopNotifications, UserSettings,
13
13
};
14
14
use chatsvc::{
15
15
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
@@ -1058,18 +1058,53 @@ impl Remote for Graph {
1058
1058
}
1059
1059
1060
1060
async fn search_people(&self, query: &str) -> Result<Vec<User>> {
1061
let mut users = Graph::search_people(self, query).await?;
1062
if crate::native::is_email_address(query)
1063
&& !users.iter().any(|user| {
1064
user.mail
1065
.as_deref()
1066
.is_some_and(|mail| mail.eq_ignore_ascii_case(query.trim()))
1067
})
1068
&& let Ok(external) = chatsvc::UserProfiles::new(self.session())
1061
let email = crate::native::is_email_address(query);
1062
let directory = Graph::search_people(self, query).await;
1063
let (mut users, directory_error) = match directory {
1064
Ok(users) => (users, None),
1065
Err(error) if email && directory_address_unknown(&error) => (Vec::new(), None),
1066
Err(error) if email => (Vec::new(), Some(error)),
1067
Err(error) => return Err(error.into()),
1068
};
1069
let known = users.iter().any(|user| {
1070
crate::native::user_has_address(
1071
user.mail.as_deref(),
1072
user.user_principal_name.as_deref(),
1073
query,
1074
)
1075
});
1076
if email && !known {
1077
match chatsvc::UserProfiles::new(self.session())
1069
1078
.search_external(query)
1070
1079
.await
1071
{
1072
users.extend(crate::native::remember_external(external));
1080
{
1081
Ok(external) => {
1082
let found = crate::native::remember_external(external);
1083
if let Some(error) = directory_error {
1084
let matched: Vec<User> = found
1085
.into_iter()
1086
.filter(|user| {
1087
crate::native::user_has_address(
1088
user.mail.as_deref(),
1089
user.user_principal_name.as_deref(),
1090
query,
1091
)
1092
})
1093
.collect();
1094
if matched.is_empty() {
1095
return Err(error.into());
1096
}
1097
users.extend(matched);
1098
} else {
1099
users.extend(found);
1100
}
1101
}
1102
Err(_) => {
1103
if let Some(error) = directory_error {
1104
return Err(error.into());
1105
}
1106
}
1107
}
1073
1108
}
1074
1109
Ok(users)
1075
1110
}
@@ -1715,10 +1750,45 @@ impl From<graph::Page<Chat>> for ChatsPage {
1715
1750
}
1716
1751
}
1717
1752
1753
/// HTTP 400 and 404 on a mail lookup mean the address is not in the directory.
1754
/// A 401, a 5xx, or a transport failure is a real search error.
1755
fn directory_address_unknown(error: &graph::Error) -> bool {
1756
matches!(
1757
error,
1758
graph::Error::Session(session::Error::Api {
1759
status: 400 | 404,
1760
..
1761
})
1762
)
1763
}
1764
1718
1765
#[cfg(test)]
1719
1766
mod tests {
1720
1767
use super::*;
1721
1768
1769
#[test]
1770
fn only_a_missing_address_is_an_unknown_directory() {
1771
let missing = graph::Error::Session(session::Error::api(
1772
404,
1773
"https://graph.test/users",
1774
serde_json::json!({}),
1775
));
1776
let invalid = graph::Error::Session(session::Error::api(
1777
400,
1778
"https://graph.test/users",
1779
serde_json::json!({}),
1780
));
1781
let denied = graph::Error::Session(session::Error::api(
1782
401,
1783
"https://graph.test/users",
1784
serde_json::json!({}),
1785
));
1786
assert!(directory_address_unknown(&missing));
1787
assert!(directory_address_unknown(&invalid));
1788
assert!(!directory_address_unknown(&denied));
1789
assert!(!directory_address_unknown(&graph::Error::NotAMember));
1790
}
1791
1722
1792
#[test]
1723
1793
fn channel_targets_route_to_chatsvc() {
1724
1794
let root = MessageTarget::channel("t", "19:c@thread.tacv2", "m1", None);
@@ -7,9 +7,9 @@ use chatsvc::substrate_search::{7
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,7
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,8
};8
};9
use chatsvc::{9
use chatsvc::{10
ActivityFeed, ActivitySnapshot, AppConsumptionHorizon, ChatNotificationMode,10
parse_app_consumption_horizon, ActivityFeed, ActivitySnapshot, AppConsumptionHorizon,11
ChatNotificationWrite, ChatSettingChange, ChatSettingsClient, ChatSettingsDocument,11
ChatNotificationMode, ChatNotificationWrite, ChatSettingChange, ChatSettingsClient,12
DesktopNotifications, UserSettings, parse_app_consumption_horizon,12
ChatSettingsDocument, DesktopNotifications, UserSettings,13
};13
};14
use chatsvc::{14
use chatsvc::{15
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,15
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,@@ -1058,18 +1058,53 @@ impl Remote for Graph {1058
}1058
}1059
1059
1060
async fn search_people(&self, query: &str) -> Result<Vec<User>> {1060
async fn search_people(&self, query: &str) -> Result<Vec<User>> {1061
let mut users = Graph::search_people(self, query).await?;1061
let email = crate::native::is_email_address(query);1062
if crate::native::is_email_address(query)1062
let directory = Graph::search_people(self, query).await;1063
&& !users.iter().any(|user| {1063
let (mut users, directory_error) = match directory {1064
user.mail1064
Ok(users) => (users, None),1065
.as_deref()1065
Err(error) if email && directory_address_unknown(&error) => (Vec::new(), None),1066
.is_some_and(|mail| mail.eq_ignore_ascii_case(query.trim()))1066
Err(error) if email => (Vec::new(), Some(error)),1067
})1067
Err(error) => return Err(error.into()),1068
&& let Ok(external) = chatsvc::UserProfiles::new(self.session())1068
};1069
let known = users.iter().any(|user| {1070
crate::native::user_has_address(1071
user.mail.as_deref(),1072
user.user_principal_name.as_deref(),1073
query,1074
)1075
});1076
if email && !known {1077
match chatsvc::UserProfiles::new(self.session())1069
.search_external(query)1078
.search_external(query)1070
.await1079
.await1071
{1080
{1072
users.extend(crate::native::remember_external(external));1081
Ok(external) => {1082
let found = crate::native::remember_external(external);1083
if let Some(error) = directory_error {1084
let matched: Vec<User> = found1085
.into_iter()1086
.filter(|user| {1087
crate::native::user_has_address(1088
user.mail.as_deref(),1089
user.user_principal_name.as_deref(),1090
query,1091
)1092
})1093
.collect();1094
if matched.is_empty() {1095
return Err(error.into());1096
}1097
users.extend(matched);1098
} else {1099
users.extend(found);1100
}1101
}1102
Err(_) => {1103
if let Some(error) = directory_error {1104
return Err(error.into());1105
}1106
}1107
}1073
}1108
}1074
Ok(users)1109
Ok(users)1075
}1110
}@@ -1715,10 +1750,45 @@ impl From<graph::Page<Chat>> for ChatsPage {1715
}1750
}1716
}1751
}1717
1752
1753
/// HTTP 400 and 404 on a mail lookup mean the address is not in the directory.1754
/// A 401, a 5xx, or a transport failure is a real search error.1755
fn directory_address_unknown(error: &graph::Error) -> bool {1756
matches!(1757
error,1758
graph::Error::Session(session::Error::Api {1759
status: 400 | 404,1760
..1761
})1762
)1763
}1764
1718
#[cfg(test)]1765
#[cfg(test)]1719
mod tests {1766
mod tests {1720
use super::*;1767
use super::*;1721
1768
1769
#[test]1770
fn only_a_missing_address_is_an_unknown_directory() {1771
let missing = graph::Error::Session(session::Error::api(1772
404,1773
"https://graph.test/users",1774
serde_json::json!({}),1775
));1776
let invalid = graph::Error::Session(session::Error::api(1777
400,1778
"https://graph.test/users",1779
serde_json::json!({}),1780
));1781
let denied = graph::Error::Session(session::Error::api(1782
401,1783
"https://graph.test/users",1784
serde_json::json!({}),1785
));1786
assert!(directory_address_unknown(&missing));1787
assert!(directory_address_unknown(&invalid));1788
assert!(!directory_address_unknown(&denied));1789
assert!(!directory_address_unknown(&graph::Error::NotAMember));1790
}1791
1722
#[test]1792
#[test]1723
fn channel_targets_route_to_chatsvc() {1793
fn channel_targets_route_to_chatsvc() {1724
let root = MessageTarget::channel("t", "19:c@thread.tacv2", "m1", None);1794
let root = MessageTarget::channel("t", "19:c@thread.tacv2", "m1", None);@@ -15,36 +15,45 @@ impl<R: Remote> SyncEngine<R> {
15
15
}
16
16
17
17
/// An empty text returns the zero-query state (top people, recent searches).
18
/// A complete email that the people index misses is resolved through `search_people`.
18
19
pub async fn server_suggestions(
19
20
&self,
20
21
search_session: &SearchSession,
21
22
text: &str,
23
) -> Result<Suggestions> {
24
self.collect_suggestions(search_session, text, true).await
25
}
26
27
/// People-index suggestions without the complete-email directory lookup.
28
/// The new-chat field calls `search_people` itself.
29
pub async fn server_suggestions_without_email_lookup(
30
&self,
31
search_session: &SearchSession,
32
text: &str,
33
) -> Result<Suggestions> {
34
self.collect_suggestions(search_session, text, false).await
35
}
36
37
async fn collect_suggestions(
38
&self,
39
search_session: &SearchSession,
40
text: &str,
41
resolve_email: bool,
22
42
) -> Result<Suggestions> {
23
43
let identity = self.search_identity().await?;
24
44
let mut suggestions = self
25
45
.remote
26
46
.server_suggestions(&identity, search_session, text)
27
47
.await?;
28
if crate::native::is_email_address(text) && !has_person_with_email(&suggestions, text) {
48
if resolve_email
49
&& crate::native::is_email_address(text)
50
&& !has_person_with_email(&suggestions, text)
51
{
29
52
let external = self.search_people(text).await.unwrap_or_default();
30
53
suggestions.people.extend(
31
54
external
32
55
.into_iter()
33
.filter(|user| {
34
user.mail
35
.as_deref()
36
.is_some_and(|mail| mail.eq_ignore_ascii_case(text.trim()))
37
})
38
.map(|user| SearchPerson {
39
company_name: crate::native::known_profile(&user.id)
40
.and_then(|profile| profile.tenant_name),
41
mri: Some(format!("8:orgid:{}", user.id)),
42
email_addresses: user.mail.into_iter().collect(),
43
display_name: user.display_name.unwrap_or_default(),
44
user_principal_name: user.user_principal_name,
45
user_id: Some(user.id),
46
..SearchPerson::default()
47
}),
56
.filter_map(|user| search_person(user, text)),
48
57
);
49
58
}
50
59
Ok(suggestions)
@@ -70,10 +79,59 @@ impl<R: Remote> SyncEngine<R> {
70
79
}
71
80
72
81
fn has_person_with_email(suggestions: &Suggestions, email: &str) -> bool {
82
let email = email.trim();
73
83
suggestions.people.iter().any(|person| {
74
84
person
75
85
.email_addresses
76
86
.iter()
77
.any(|address| address.eq_ignore_ascii_case(email.trim()))
87
.any(|address| address.eq_ignore_ascii_case(email))
88
|| person
89
.user_principal_name
90
.as_deref()
91
.is_some_and(|address| address.eq_ignore_ascii_case(email))
92
})
93
}
94
95
fn search_person(user: graph::User, query: &str) -> Option<SearchPerson> {
96
if !crate::native::user_has_address(
97
user.mail.as_deref(),
98
user.user_principal_name.as_deref(),
99
query,
100
) {
101
return None;
102
}
103
let email = user
104
.mail
105
.clone()
106
.or_else(|| user.user_principal_name.clone());
107
Some(SearchPerson {
108
company_name: crate::native::known_profile(&user.id)
109
.and_then(|profile| profile.tenant_name),
110
mri: Some(chatsvc::members::user_mri(&user.id)),
111
email_addresses: email.into_iter().collect(),
112
display_name: user.display_name.unwrap_or_default(),
113
user_principal_name: user.user_principal_name,
114
user_id: Some(user.id),
115
..SearchPerson::default()
78
116
})
79
117
}
118
119
#[cfg(test)]
120
mod tests {
121
use super::*;
122
123
#[test]
124
fn a_principal_name_still_becomes_a_person_row() {
125
let user = graph::User {
126
id: "ada".into(),
127
display_name: Some("Ada".into()),
128
mail: None,
129
user_principal_name: Some("ada@other.example".into()),
130
job_title: None,
131
department: None,
132
};
133
let person = search_person(user, "Ada@Other.Example").unwrap();
134
assert_eq!(person.user_id.as_deref(), Some("ada"));
135
assert_eq!(person.email_addresses, ["ada@other.example"]);
136
}
137
}
@@ -15,36 +15,45 @@ impl<R: Remote> SyncEngine<R> {15
}15
}16
16
17
/// An empty text returns the zero-query state (top people, recent searches).17
/// An empty text returns the zero-query state (top people, recent searches).18
/// A complete email that the people index misses is resolved through `search_people`.18
pub async fn server_suggestions(19
pub async fn server_suggestions(19
&self,20
&self,20
search_session: &SearchSession,21
search_session: &SearchSession,21
text: &str,22
text: &str,23
) -> Result<Suggestions> {24
self.collect_suggestions(search_session, text, true).await25
}26
27
/// People-index suggestions without the complete-email directory lookup.28
/// The new-chat field calls `search_people` itself.29
pub async fn server_suggestions_without_email_lookup(30
&self,31
search_session: &SearchSession,32
text: &str,33
) -> Result<Suggestions> {34
self.collect_suggestions(search_session, text, false).await35
}36
37
async fn collect_suggestions(38
&self,39
search_session: &SearchSession,40
text: &str,41
resolve_email: bool,22
) -> Result<Suggestions> {42
) -> Result<Suggestions> {23
let identity = self.search_identity().await?;43
let identity = self.search_identity().await?;24
let mut suggestions = self44
let mut suggestions = self25
.remote45
.remote26
.server_suggestions(&identity, search_session, text)46
.server_suggestions(&identity, search_session, text)27
.await?;47
.await?;28
if crate::native::is_email_address(text) && !has_person_with_email(&suggestions, text) {48
if resolve_email49
&& crate::native::is_email_address(text)50
&& !has_person_with_email(&suggestions, text)51
{29
let external = self.search_people(text).await.unwrap_or_default();52
let external = self.search_people(text).await.unwrap_or_default();30
suggestions.people.extend(53
suggestions.people.extend(31
external54
external32
.into_iter()55
.into_iter()33
.filter(|user| {56
.filter_map(|user| search_person(user, text)),34
user.mail35
.as_deref()36
.is_some_and(|mail| mail.eq_ignore_ascii_case(text.trim()))37
})38
.map(|user| SearchPerson {39
company_name: crate::native::known_profile(&user.id)40
.and_then(|profile| profile.tenant_name),41
mri: Some(format!("8:orgid:{}", user.id)),42
email_addresses: user.mail.into_iter().collect(),43
display_name: user.display_name.unwrap_or_default(),44
user_principal_name: user.user_principal_name,45
user_id: Some(user.id),46
..SearchPerson::default()47
}),48
);57
);49
}58
}50
Ok(suggestions)59
Ok(suggestions)@@ -70,10 +79,59 @@ impl<R: Remote> SyncEngine<R> {70
}79
}71
80
72
fn has_person_with_email(suggestions: &Suggestions, email: &str) -> bool {81
fn has_person_with_email(suggestions: &Suggestions, email: &str) -> bool {82
let email = email.trim();73
suggestions.people.iter().any(|person| {83
suggestions.people.iter().any(|person| {74
person84
person75
.email_addresses85
.email_addresses76
.iter()86
.iter()77
.any(|address| address.eq_ignore_ascii_case(email.trim()))87
.any(|address| address.eq_ignore_ascii_case(email))88
|| person89
.user_principal_name90
.as_deref()91
.is_some_and(|address| address.eq_ignore_ascii_case(email))92
})93
}94
95
fn search_person(user: graph::User, query: &str) -> Option<SearchPerson> {96
if !crate::native::user_has_address(97
user.mail.as_deref(),98
user.user_principal_name.as_deref(),99
query,100
) {101
return None;102
}103
let email = user104
.mail105
.clone()106
.or_else(|| user.user_principal_name.clone());107
Some(SearchPerson {108
company_name: crate::native::known_profile(&user.id)109
.and_then(|profile| profile.tenant_name),110
mri: Some(chatsvc::members::user_mri(&user.id)),111
email_addresses: email.into_iter().collect(),112
display_name: user.display_name.unwrap_or_default(),113
user_principal_name: user.user_principal_name,114
user_id: Some(user.id),115
..SearchPerson::default()78
})116
})79
}117
}118
119
#[cfg(test)]120
mod tests {121
use super::*;122
123
#[test]124
fn a_principal_name_still_becomes_a_person_row() {125
let user = graph::User {126
id: "ada".into(),127
display_name: Some("Ada".into()),128
mail: None,129
user_principal_name: Some("ada@other.example".into()),130
job_title: None,131
department: None,132
};133
let person = search_person(user, "Ada@Other.Example").unwrap();134
assert_eq!(person.user_id.as_deref(), Some("ada"));135
assert_eq!(person.email_addresses, ["ada@other.example"]);136
}137
}