1use super::{Client, Status, TypedEnvelope, proto};
2use anyhow::{Context as _, Result, anyhow};
3use chrono::{DateTime, Utc};
4use collections::{HashMap, HashSet, hash_map::Entry};
5use feature_flags::FeatureFlagAppExt;
6use futures::{Future, StreamExt, channel::mpsc};
7use gpui::{
8 App, AsyncApp, Context, Entity, EventEmitter, SharedString, SharedUri, Task, WeakEntity,
9};
10use postage::{sink::Sink, watch};
11use rpc::proto::{RequestMessage, UsersResponse};
12use std::sync::{Arc, Weak};
13use text::ReplicaId;
14use util::TryFutureExt as _;
15
16pub type UserId = u64;
17
18#[derive(
19 Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, serde::Serialize, serde::Deserialize,
20)]
21pub struct ChannelId(pub u64);
22
23impl std::fmt::Display for ChannelId {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 self.0.fmt(f)
26 }
27}
28
29#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
30pub struct ProjectId(pub u64);
31
32impl ProjectId {
33 pub fn to_proto(&self) -> u64 {
34 self.0
35 }
36}
37
38#[derive(
39 Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, serde::Serialize, serde::Deserialize,
40)]
41pub struct DevServerProjectId(pub u64);
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct ParticipantIndex(pub u32);
45
46#[derive(Default, Debug)]
47pub struct User {
48 pub id: UserId,
49 pub github_login: String,
50 pub avatar_uri: SharedUri,
51 pub name: Option<String>,
52 pub email: Option<String>,
53}
54
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct Collaborator {
57 pub peer_id: proto::PeerId,
58 pub replica_id: ReplicaId,
59 pub user_id: UserId,
60 pub is_host: bool,
61}
62
63impl PartialOrd for User {
64 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
65 Some(self.cmp(other))
66 }
67}
68
69impl Ord for User {
70 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
71 self.github_login.cmp(&other.github_login)
72 }
73}
74
75impl PartialEq for User {
76 fn eq(&self, other: &Self) -> bool {
77 self.id == other.id && self.github_login == other.github_login
78 }
79}
80
81impl Eq for User {}
82
83#[derive(Debug, PartialEq)]
84pub struct Contact {
85 pub user: Arc<User>,
86 pub online: bool,
87 pub busy: bool,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum ContactRequestStatus {
92 None,
93 RequestSent,
94 RequestReceived,
95 RequestAccepted,
96}
97
98pub struct UserStore {
99 users: HashMap<u64, Arc<User>>,
100 by_github_login: HashMap<String, u64>,
101 participant_indices: HashMap<u64, ParticipantIndex>,
102 update_contacts_tx: mpsc::UnboundedSender<UpdateContacts>,
103 current_plan: Option<proto::Plan>,
104 current_user: watch::Receiver<Option<Arc<User>>>,
105 accepted_tos_at: Option<Option<DateTime<Utc>>>,
106 contacts: Vec<Arc<Contact>>,
107 incoming_contact_requests: Vec<Arc<User>>,
108 outgoing_contact_requests: Vec<Arc<User>>,
109 pending_contact_requests: HashMap<u64, usize>,
110 invite_info: Option<InviteInfo>,
111 client: Weak<Client>,
112 _maintain_contacts: Task<()>,
113 _maintain_current_user: Task<Result<()>>,
114 weak_self: WeakEntity<Self>,
115}
116
117#[derive(Clone)]
118pub struct InviteInfo {
119 pub count: u32,
120 pub url: Arc<str>,
121}
122
123pub enum Event {
124 Contact {
125 user: Arc<User>,
126 kind: ContactEventKind,
127 },
128 ShowContacts,
129 ParticipantIndicesChanged,
130 PrivateUserInfoUpdated,
131}
132
133#[derive(Clone, Copy)]
134pub enum ContactEventKind {
135 Requested,
136 Accepted,
137 Cancelled,
138}
139
140impl EventEmitter<Event> for UserStore {}
141
142enum UpdateContacts {
143 Update(proto::UpdateContacts),
144 Wait(postage::barrier::Sender),
145 Clear(postage::barrier::Sender),
146}
147
148impl UserStore {
149 pub fn new(client: Arc<Client>, cx: &Context<Self>) -> Self {
150 let (mut current_user_tx, current_user_rx) = watch::channel();
151 let (update_contacts_tx, mut update_contacts_rx) = mpsc::unbounded();
152 let rpc_subscriptions = vec![
153 client.add_message_handler(cx.weak_entity(), Self::handle_update_plan),
154 client.add_message_handler(cx.weak_entity(), Self::handle_update_contacts),
155 client.add_message_handler(cx.weak_entity(), Self::handle_update_invite_info),
156 client.add_message_handler(cx.weak_entity(), Self::handle_show_contacts),
157 ];
158 Self {
159 users: Default::default(),
160 by_github_login: Default::default(),
161 current_user: current_user_rx,
162 current_plan: None,
163 accepted_tos_at: None,
164 contacts: Default::default(),
165 incoming_contact_requests: Default::default(),
166 participant_indices: Default::default(),
167 outgoing_contact_requests: Default::default(),
168 invite_info: None,
169 client: Arc::downgrade(&client),
170 update_contacts_tx,
171 _maintain_contacts: cx.spawn(async move |this, cx| {
172 let _subscriptions = rpc_subscriptions;
173 while let Some(message) = update_contacts_rx.next().await {
174 if let Ok(task) = this.update(cx, |this, cx| this.update_contacts(message, cx))
175 {
176 task.log_err().await;
177 } else {
178 break;
179 }
180 }
181 }),
182 _maintain_current_user: cx.spawn(async move |this, cx| {
183 let mut status = client.status();
184 let weak = Arc::downgrade(&client);
185 drop(client);
186 while let Some(status) = status.next().await {
187 // if the client is dropped, the app is shutting down.
188 let Some(client) = weak.upgrade() else {
189 return Ok(());
190 };
191 match status {
192 Status::Connected { .. } => {
193 if let Some(user_id) = client.user_id() {
194 let fetch_user = if let Ok(fetch_user) =
195 this.update(cx, |this, cx| this.get_user(user_id, cx).log_err())
196 {
197 fetch_user
198 } else {
199 break;
200 };
201 let fetch_private_user_info =
202 client.request(proto::GetPrivateUserInfo {}).log_err();
203 let (user, info) =
204 futures::join!(fetch_user, fetch_private_user_info);
205
206 cx.update(|cx| {
207 if let Some(info) = info {
208 let staff =
209 info.staff && !*feature_flags::ZED_DISABLE_STAFF;
210 cx.update_flags(staff, info.flags);
211 client.telemetry.set_authenticated_user_info(
212 Some(info.metrics_id.clone()),
213 staff,
214 );
215
216 this.update(cx, |this, cx| {
217 let accepted_tos_at = {
218 #[cfg(debug_assertions)]
219 if std::env::var("ZED_IGNORE_ACCEPTED_TOS").is_ok()
220 {
221 None
222 } else {
223 info.accepted_tos_at
224 }
225
226 #[cfg(not(debug_assertions))]
227 info.accepted_tos_at
228 };
229
230 this.set_current_user_accepted_tos_at(accepted_tos_at);
231 cx.emit(Event::PrivateUserInfoUpdated);
232 })
233 } else {
234 anyhow::Ok(())
235 }
236 })??;
237
238 current_user_tx.send(user).await.ok();
239
240 this.update(cx, |_, cx| cx.notify())?;
241 }
242 }
243 Status::SignedOut => {
244 current_user_tx.send(None).await.ok();
245 this.update(cx, |this, cx| {
246 this.accepted_tos_at = None;
247 cx.emit(Event::PrivateUserInfoUpdated);
248 cx.notify();
249 this.clear_contacts()
250 })?
251 .await;
252 }
253 Status::ConnectionLost => {
254 this.update(cx, |this, cx| {
255 cx.notify();
256 this.clear_contacts()
257 })?
258 .await;
259 }
260 _ => {}
261 }
262 }
263 Ok(())
264 }),
265 pending_contact_requests: Default::default(),
266 weak_self: cx.weak_entity(),
267 }
268 }
269
270 #[cfg(feature = "test-support")]
271 pub fn clear_cache(&mut self) {
272 self.users.clear();
273 self.by_github_login.clear();
274 }
275
276 async fn handle_update_invite_info(
277 this: Entity<Self>,
278 message: TypedEnvelope<proto::UpdateInviteInfo>,
279 mut cx: AsyncApp,
280 ) -> Result<()> {
281 this.update(&mut cx, |this, cx| {
282 this.invite_info = Some(InviteInfo {
283 url: Arc::from(message.payload.url),
284 count: message.payload.count,
285 });
286 cx.notify();
287 })?;
288 Ok(())
289 }
290
291 async fn handle_show_contacts(
292 this: Entity<Self>,
293 _: TypedEnvelope<proto::ShowContacts>,
294 mut cx: AsyncApp,
295 ) -> Result<()> {
296 this.update(&mut cx, |_, cx| cx.emit(Event::ShowContacts))?;
297 Ok(())
298 }
299
300 pub fn invite_info(&self) -> Option<&InviteInfo> {
301 self.invite_info.as_ref()
302 }
303
304 async fn handle_update_contacts(
305 this: Entity<Self>,
306 message: TypedEnvelope<proto::UpdateContacts>,
307 mut cx: AsyncApp,
308 ) -> Result<()> {
309 this.update(&mut cx, |this, _| {
310 this.update_contacts_tx
311 .unbounded_send(UpdateContacts::Update(message.payload))
312 .unwrap();
313 })?;
314 Ok(())
315 }
316
317 async fn handle_update_plan(
318 this: Entity<Self>,
319 message: TypedEnvelope<proto::UpdateUserPlan>,
320 mut cx: AsyncApp,
321 ) -> Result<()> {
322 this.update(&mut cx, |this, cx| {
323 this.current_plan = Some(message.payload.plan());
324 cx.notify();
325 })?;
326 Ok(())
327 }
328
329 fn update_contacts(&mut self, message: UpdateContacts, cx: &Context<Self>) -> Task<Result<()>> {
330 match message {
331 UpdateContacts::Wait(barrier) => {
332 drop(barrier);
333 Task::ready(Ok(()))
334 }
335 UpdateContacts::Clear(barrier) => {
336 self.contacts.clear();
337 self.incoming_contact_requests.clear();
338 self.outgoing_contact_requests.clear();
339 drop(barrier);
340 Task::ready(Ok(()))
341 }
342 UpdateContacts::Update(message) => {
343 let mut user_ids = HashSet::default();
344 for contact in &message.contacts {
345 user_ids.insert(contact.user_id);
346 }
347 user_ids.extend(message.incoming_requests.iter().map(|req| req.requester_id));
348 user_ids.extend(message.outgoing_requests.iter());
349
350 let load_users = self.get_users(user_ids.into_iter().collect(), cx);
351 cx.spawn(async move |this, cx| {
352 load_users.await?;
353
354 // Users are fetched in parallel above and cached in call to get_users
355 // No need to parallelize here
356 let mut updated_contacts = Vec::new();
357 let this = this
358 .upgrade()
359 .ok_or_else(|| anyhow!("can't upgrade user store handle"))?;
360 for contact in message.contacts {
361 updated_contacts
362 .push(Arc::new(Contact::from_proto(contact, &this, cx).await?));
363 }
364
365 let mut incoming_requests = Vec::new();
366 for request in message.incoming_requests {
367 incoming_requests.push({
368 this.update(cx, |this, cx| this.get_user(request.requester_id, cx))?
369 .await?
370 });
371 }
372
373 let mut outgoing_requests = Vec::new();
374 for requested_user_id in message.outgoing_requests {
375 outgoing_requests.push(
376 this.update(cx, |this, cx| this.get_user(requested_user_id, cx))?
377 .await?,
378 );
379 }
380
381 let removed_contacts =
382 HashSet::<u64>::from_iter(message.remove_contacts.iter().copied());
383 let removed_incoming_requests =
384 HashSet::<u64>::from_iter(message.remove_incoming_requests.iter().copied());
385 let removed_outgoing_requests =
386 HashSet::<u64>::from_iter(message.remove_outgoing_requests.iter().copied());
387
388 this.update(cx, |this, cx| {
389 // Remove contacts
390 this.contacts
391 .retain(|contact| !removed_contacts.contains(&contact.user.id));
392 // Update existing contacts and insert new ones
393 for updated_contact in updated_contacts {
394 match this.contacts.binary_search_by_key(
395 &&updated_contact.user.github_login,
396 |contact| &contact.user.github_login,
397 ) {
398 Ok(ix) => this.contacts[ix] = updated_contact,
399 Err(ix) => this.contacts.insert(ix, updated_contact),
400 }
401 }
402
403 // Remove incoming contact requests
404 this.incoming_contact_requests.retain(|user| {
405 if removed_incoming_requests.contains(&user.id) {
406 cx.emit(Event::Contact {
407 user: user.clone(),
408 kind: ContactEventKind::Cancelled,
409 });
410 false
411 } else {
412 true
413 }
414 });
415 // Update existing incoming requests and insert new ones
416 for user in incoming_requests {
417 match this
418 .incoming_contact_requests
419 .binary_search_by_key(&&user.github_login, |contact| {
420 &contact.github_login
421 }) {
422 Ok(ix) => this.incoming_contact_requests[ix] = user,
423 Err(ix) => this.incoming_contact_requests.insert(ix, user),
424 }
425 }
426
427 // Remove outgoing contact requests
428 this.outgoing_contact_requests
429 .retain(|user| !removed_outgoing_requests.contains(&user.id));
430 // Update existing incoming requests and insert new ones
431 for request in outgoing_requests {
432 match this
433 .outgoing_contact_requests
434 .binary_search_by_key(&&request.github_login, |contact| {
435 &contact.github_login
436 }) {
437 Ok(ix) => this.outgoing_contact_requests[ix] = request,
438 Err(ix) => this.outgoing_contact_requests.insert(ix, request),
439 }
440 }
441
442 cx.notify();
443 })?;
444
445 Ok(())
446 })
447 }
448 }
449 }
450
451 pub fn contacts(&self) -> &[Arc<Contact>] {
452 &self.contacts
453 }
454
455 pub fn has_contact(&self, user: &Arc<User>) -> bool {
456 self.contacts
457 .binary_search_by_key(&&user.github_login, |contact| &contact.user.github_login)
458 .is_ok()
459 }
460
461 pub fn incoming_contact_requests(&self) -> &[Arc<User>] {
462 &self.incoming_contact_requests
463 }
464
465 pub fn outgoing_contact_requests(&self) -> &[Arc<User>] {
466 &self.outgoing_contact_requests
467 }
468
469 pub fn is_contact_request_pending(&self, user: &User) -> bool {
470 self.pending_contact_requests.contains_key(&user.id)
471 }
472
473 pub fn contact_request_status(&self, user: &User) -> ContactRequestStatus {
474 if self
475 .contacts
476 .binary_search_by_key(&&user.github_login, |contact| &contact.user.github_login)
477 .is_ok()
478 {
479 ContactRequestStatus::RequestAccepted
480 } else if self
481 .outgoing_contact_requests
482 .binary_search_by_key(&&user.github_login, |user| &user.github_login)
483 .is_ok()
484 {
485 ContactRequestStatus::RequestSent
486 } else if self
487 .incoming_contact_requests
488 .binary_search_by_key(&&user.github_login, |user| &user.github_login)
489 .is_ok()
490 {
491 ContactRequestStatus::RequestReceived
492 } else {
493 ContactRequestStatus::None
494 }
495 }
496
497 pub fn request_contact(
498 &mut self,
499 responder_id: u64,
500 cx: &mut Context<Self>,
501 ) -> Task<Result<()>> {
502 self.perform_contact_request(responder_id, proto::RequestContact { responder_id }, cx)
503 }
504
505 pub fn remove_contact(&mut self, user_id: u64, cx: &mut Context<Self>) -> Task<Result<()>> {
506 self.perform_contact_request(user_id, proto::RemoveContact { user_id }, cx)
507 }
508
509 pub fn has_incoming_contact_request(&self, user_id: u64) -> bool {
510 self.incoming_contact_requests
511 .iter()
512 .any(|user| user.id == user_id)
513 }
514
515 pub fn respond_to_contact_request(
516 &mut self,
517 requester_id: u64,
518 accept: bool,
519 cx: &mut Context<Self>,
520 ) -> Task<Result<()>> {
521 self.perform_contact_request(
522 requester_id,
523 proto::RespondToContactRequest {
524 requester_id,
525 response: if accept {
526 proto::ContactRequestResponse::Accept
527 } else {
528 proto::ContactRequestResponse::Decline
529 } as i32,
530 },
531 cx,
532 )
533 }
534
535 pub fn dismiss_contact_request(
536 &self,
537 requester_id: u64,
538 cx: &Context<Self>,
539 ) -> Task<Result<()>> {
540 let client = self.client.upgrade();
541 cx.spawn(async move |_, _| {
542 client
543 .ok_or_else(|| anyhow!("can't upgrade client reference"))?
544 .request(proto::RespondToContactRequest {
545 requester_id,
546 response: proto::ContactRequestResponse::Dismiss as i32,
547 })
548 .await?;
549 Ok(())
550 })
551 }
552
553 fn perform_contact_request<T: RequestMessage>(
554 &mut self,
555 user_id: u64,
556 request: T,
557 cx: &mut Context<Self>,
558 ) -> Task<Result<()>> {
559 let client = self.client.upgrade();
560 *self.pending_contact_requests.entry(user_id).or_insert(0) += 1;
561 cx.notify();
562
563 cx.spawn(async move |this, cx| {
564 let response = client
565 .ok_or_else(|| anyhow!("can't upgrade client reference"))?
566 .request(request)
567 .await;
568 this.update(cx, |this, cx| {
569 if let Entry::Occupied(mut request_count) =
570 this.pending_contact_requests.entry(user_id)
571 {
572 *request_count.get_mut() -= 1;
573 if *request_count.get() == 0 {
574 request_count.remove();
575 }
576 }
577 cx.notify();
578 })?;
579 response?;
580 Ok(())
581 })
582 }
583
584 pub fn clear_contacts(&self) -> impl Future<Output = ()> + use<> {
585 let (tx, mut rx) = postage::barrier::channel();
586 self.update_contacts_tx
587 .unbounded_send(UpdateContacts::Clear(tx))
588 .unwrap();
589 async move {
590 rx.next().await;
591 }
592 }
593
594 pub fn contact_updates_done(&self) -> impl Future<Output = ()> {
595 let (tx, mut rx) = postage::barrier::channel();
596 self.update_contacts_tx
597 .unbounded_send(UpdateContacts::Wait(tx))
598 .unwrap();
599 async move {
600 rx.next().await;
601 }
602 }
603
604 pub fn get_users(
605 &self,
606 user_ids: Vec<u64>,
607 cx: &Context<Self>,
608 ) -> Task<Result<Vec<Arc<User>>>> {
609 let mut user_ids_to_fetch = user_ids.clone();
610 user_ids_to_fetch.retain(|id| !self.users.contains_key(id));
611
612 cx.spawn(async move |this, cx| {
613 if !user_ids_to_fetch.is_empty() {
614 this.update(cx, |this, cx| {
615 this.load_users(
616 proto::GetUsers {
617 user_ids: user_ids_to_fetch,
618 },
619 cx,
620 )
621 })?
622 .await?;
623 }
624
625 this.update(cx, |this, _| {
626 user_ids
627 .iter()
628 .map(|user_id| {
629 this.users
630 .get(user_id)
631 .cloned()
632 .ok_or_else(|| anyhow!("user {} not found", user_id))
633 })
634 .collect()
635 })?
636 })
637 }
638
639 pub fn fuzzy_search_users(
640 &self,
641 query: String,
642 cx: &Context<Self>,
643 ) -> Task<Result<Vec<Arc<User>>>> {
644 self.load_users(proto::FuzzySearchUsers { query }, cx)
645 }
646
647 pub fn get_cached_user(&self, user_id: u64) -> Option<Arc<User>> {
648 self.users.get(&user_id).cloned()
649 }
650
651 pub fn get_user_optimistic(&self, user_id: u64, cx: &Context<Self>) -> Option<Arc<User>> {
652 if let Some(user) = self.users.get(&user_id).cloned() {
653 return Some(user);
654 }
655
656 self.get_user(user_id, cx).detach_and_log_err(cx);
657 None
658 }
659
660 pub fn get_user(&self, user_id: u64, cx: &Context<Self>) -> Task<Result<Arc<User>>> {
661 if let Some(user) = self.users.get(&user_id).cloned() {
662 return Task::ready(Ok(user));
663 }
664
665 let load_users = self.get_users(vec![user_id], cx);
666 cx.spawn(async move |this, cx| {
667 load_users.await?;
668 this.update(cx, |this, _| {
669 this.users
670 .get(&user_id)
671 .cloned()
672 .ok_or_else(|| anyhow!("server responded with no users"))
673 })?
674 })
675 }
676
677 pub fn cached_user_by_github_login(&self, github_login: &str) -> Option<Arc<User>> {
678 self.by_github_login
679 .get(github_login)
680 .and_then(|id| self.users.get(id).cloned())
681 }
682
683 pub fn current_user(&self) -> Option<Arc<User>> {
684 self.current_user.borrow().clone()
685 }
686
687 pub fn current_plan(&self) -> Option<proto::Plan> {
688 self.current_plan
689 }
690
691 pub fn watch_current_user(&self) -> watch::Receiver<Option<Arc<User>>> {
692 self.current_user.clone()
693 }
694
695 pub fn current_user_has_accepted_terms(&self) -> Option<bool> {
696 self.accepted_tos_at
697 .map(|accepted_tos_at| accepted_tos_at.is_some())
698 }
699
700 pub fn accept_terms_of_service(&self, cx: &Context<Self>) -> Task<Result<()>> {
701 if self.current_user().is_none() {
702 return Task::ready(Err(anyhow!("no current user")));
703 };
704
705 let client = self.client.clone();
706 cx.spawn(async move |this, cx| {
707 if let Some(client) = client.upgrade() {
708 let response = client
709 .request(proto::AcceptTermsOfService {})
710 .await
711 .context("error accepting tos")?;
712
713 this.update(cx, |this, cx| {
714 this.set_current_user_accepted_tos_at(Some(response.accepted_tos_at));
715 cx.emit(Event::PrivateUserInfoUpdated);
716 })
717 } else {
718 Err(anyhow!("client not found"))
719 }
720 })
721 }
722
723 fn set_current_user_accepted_tos_at(&mut self, accepted_tos_at: Option<u64>) {
724 self.accepted_tos_at = Some(
725 accepted_tos_at.and_then(|timestamp| DateTime::from_timestamp(timestamp as i64, 0)),
726 );
727 }
728
729 fn load_users(
730 &self,
731 request: impl RequestMessage<Response = UsersResponse>,
732 cx: &Context<Self>,
733 ) -> Task<Result<Vec<Arc<User>>>> {
734 let client = self.client.clone();
735 cx.spawn(async move |this, cx| {
736 if let Some(rpc) = client.upgrade() {
737 let response = rpc.request(request).await.context("error loading users")?;
738 let users = response.users;
739
740 this.update(cx, |this, _| this.insert(users))
741 } else {
742 Ok(Vec::new())
743 }
744 })
745 }
746
747 pub fn insert(&mut self, users: Vec<proto::User>) -> Vec<Arc<User>> {
748 let mut ret = Vec::with_capacity(users.len());
749 for user in users {
750 let user = User::new(user);
751 if let Some(old) = self.users.insert(user.id, user.clone()) {
752 if old.github_login != user.github_login {
753 self.by_github_login.remove(&old.github_login);
754 }
755 }
756 self.by_github_login
757 .insert(user.github_login.clone(), user.id);
758 ret.push(user)
759 }
760 ret
761 }
762
763 pub fn set_participant_indices(
764 &mut self,
765 participant_indices: HashMap<u64, ParticipantIndex>,
766 cx: &mut Context<Self>,
767 ) {
768 if participant_indices != self.participant_indices {
769 self.participant_indices = participant_indices;
770 cx.emit(Event::ParticipantIndicesChanged);
771 }
772 }
773
774 pub fn participant_indices(&self) -> &HashMap<u64, ParticipantIndex> {
775 &self.participant_indices
776 }
777
778 pub fn participant_names(
779 &self,
780 user_ids: impl Iterator<Item = u64>,
781 cx: &App,
782 ) -> HashMap<u64, SharedString> {
783 let mut ret = HashMap::default();
784 let mut missing_user_ids = Vec::new();
785 for id in user_ids {
786 if let Some(github_login) = self.get_cached_user(id).map(|u| u.github_login.clone()) {
787 ret.insert(id, github_login.into());
788 } else {
789 missing_user_ids.push(id)
790 }
791 }
792 if !missing_user_ids.is_empty() {
793 let this = self.weak_self.clone();
794 cx.spawn(async move |cx| {
795 this.update(cx, |this, cx| this.get_users(missing_user_ids, cx))?
796 .await
797 })
798 .detach_and_log_err(cx);
799 }
800 ret
801 }
802}
803
804impl User {
805 fn new(message: proto::User) -> Arc<Self> {
806 Arc::new(User {
807 id: message.id,
808 github_login: message.github_login,
809 avatar_uri: message.avatar_url.into(),
810 name: message.name,
811 email: message.email,
812 })
813 }
814}
815
816impl Contact {
817 async fn from_proto(
818 contact: proto::Contact,
819 user_store: &Entity<UserStore>,
820 cx: &mut AsyncApp,
821 ) -> Result<Self> {
822 let user = user_store
823 .update(cx, |user_store, cx| {
824 user_store.get_user(contact.user_id, cx)
825 })?
826 .await?;
827 Ok(Self {
828 user,
829 online: contact.online,
830 busy: contact.busy,
831 })
832 }
833}
834
835impl Collaborator {
836 pub fn from_proto(message: proto::Collaborator) -> Result<Self> {
837 Ok(Self {
838 peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
839 replica_id: message.replica_id as ReplicaId,
840 user_id: message.user_id as UserId,
841 is_host: message.is_host,
842 })
843 }
844}