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