user.rs

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