user.rs

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