call.rs

  1pub mod call_settings;
  2pub mod participant;
  3pub mod room;
  4
  5use std::sync::Arc;
  6
  7use anyhow::{anyhow, Result};
  8use audio::Audio;
  9use call_settings::CallSettings;
 10use channel::ChannelId;
 11use client::{proto, ClickhouseEvent, Client, TelemetrySettings, TypedEnvelope, User, UserStore};
 12use collections::HashSet;
 13use futures::{future::Shared, FutureExt};
 14use postage::watch;
 15
 16use gpui::{
 17    AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, Subscription, Task,
 18    WeakModelHandle,
 19};
 20use project::Project;
 21
 22pub use participant::ParticipantLocation;
 23pub use room::Room;
 24
 25pub fn init(client: Arc<Client>, user_store: ModelHandle<UserStore>, cx: &mut AppContext) {
 26    settings::register::<CallSettings>(cx);
 27
 28    let active_call = cx.add_model(|cx| ActiveCall::new(client, user_store, cx));
 29    cx.set_global(active_call);
 30}
 31
 32#[derive(Clone)]
 33pub struct IncomingCall {
 34    pub room_id: u64,
 35    pub calling_user: Arc<User>,
 36    pub participants: Vec<Arc<User>>,
 37    pub initial_project: Option<proto::ParticipantProject>,
 38}
 39
 40/// Singleton global maintaining the user's participation in a room across workspaces.
 41pub struct ActiveCall {
 42    room: Option<(ModelHandle<Room>, Vec<Subscription>)>,
 43    pending_room_creation: Option<Shared<Task<Result<ModelHandle<Room>, Arc<anyhow::Error>>>>>,
 44    location: Option<WeakModelHandle<Project>>,
 45    pending_invites: HashSet<u64>,
 46    incoming_call: (
 47        watch::Sender<Option<IncomingCall>>,
 48        watch::Receiver<Option<IncomingCall>>,
 49    ),
 50    client: Arc<Client>,
 51    user_store: ModelHandle<UserStore>,
 52    _subscriptions: Vec<client::Subscription>,
 53}
 54
 55impl Entity for ActiveCall {
 56    type Event = room::Event;
 57}
 58
 59impl ActiveCall {
 60    fn new(
 61        client: Arc<Client>,
 62        user_store: ModelHandle<UserStore>,
 63        cx: &mut ModelContext<Self>,
 64    ) -> Self {
 65        Self {
 66            room: None,
 67            pending_room_creation: None,
 68            location: None,
 69            pending_invites: Default::default(),
 70            incoming_call: watch::channel(),
 71            _subscriptions: vec![
 72                client.add_request_handler(cx.handle(), Self::handle_incoming_call),
 73                client.add_message_handler(cx.handle(), Self::handle_call_canceled),
 74            ],
 75            client,
 76            user_store,
 77        }
 78    }
 79
 80    pub fn channel_id(&self, cx: &AppContext) -> Option<ChannelId> {
 81        self.room()?.read(cx).channel_id()
 82    }
 83
 84    async fn handle_incoming_call(
 85        this: ModelHandle<Self>,
 86        envelope: TypedEnvelope<proto::IncomingCall>,
 87        _: Arc<Client>,
 88        mut cx: AsyncAppContext,
 89    ) -> Result<proto::Ack> {
 90        let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
 91        let call = IncomingCall {
 92            room_id: envelope.payload.room_id,
 93            participants: user_store
 94                .update(&mut cx, |user_store, cx| {
 95                    user_store.get_users(envelope.payload.participant_user_ids, cx)
 96                })
 97                .await?,
 98            calling_user: user_store
 99                .update(&mut cx, |user_store, cx| {
100                    user_store.get_user(envelope.payload.calling_user_id, cx)
101                })
102                .await?,
103            initial_project: envelope.payload.initial_project,
104        };
105        this.update(&mut cx, |this, _| {
106            *this.incoming_call.0.borrow_mut() = Some(call);
107        });
108
109        Ok(proto::Ack {})
110    }
111
112    async fn handle_call_canceled(
113        this: ModelHandle<Self>,
114        envelope: TypedEnvelope<proto::CallCanceled>,
115        _: Arc<Client>,
116        mut cx: AsyncAppContext,
117    ) -> Result<()> {
118        this.update(&mut cx, |this, _| {
119            let mut incoming_call = this.incoming_call.0.borrow_mut();
120            if incoming_call
121                .as_ref()
122                .map_or(false, |call| call.room_id == envelope.payload.room_id)
123            {
124                incoming_call.take();
125            }
126        });
127        Ok(())
128    }
129
130    pub fn global(cx: &AppContext) -> ModelHandle<Self> {
131        cx.global::<ModelHandle<Self>>().clone()
132    }
133
134    pub fn invite(
135        &mut self,
136        called_user_id: u64,
137        initial_project: Option<ModelHandle<Project>>,
138        cx: &mut ModelContext<Self>,
139    ) -> Task<Result<()>> {
140        if !self.pending_invites.insert(called_user_id) {
141            return Task::ready(Err(anyhow!("user was already invited")));
142        }
143        cx.notify();
144
145        let room = if let Some(room) = self.room().cloned() {
146            Some(Task::ready(Ok(room)).shared())
147        } else {
148            self.pending_room_creation.clone()
149        };
150
151        let invite = if let Some(room) = room {
152            cx.spawn_weak(|_, mut cx| async move {
153                let room = room.await.map_err(|err| anyhow!("{:?}", err))?;
154
155                let initial_project_id = if let Some(initial_project) = initial_project {
156                    Some(
157                        room.update(&mut cx, |room, cx| room.share_project(initial_project, cx))
158                            .await?,
159                    )
160                } else {
161                    None
162                };
163
164                room.update(&mut cx, |room, cx| {
165                    room.call(called_user_id, initial_project_id, cx)
166                })
167                .await?;
168
169                anyhow::Ok(())
170            })
171        } else {
172            let client = self.client.clone();
173            let user_store = self.user_store.clone();
174            let room = cx
175                .spawn(|this, mut cx| async move {
176                    let create_room = async {
177                        let room = cx
178                            .update(|cx| {
179                                Room::create(
180                                    called_user_id,
181                                    initial_project,
182                                    client,
183                                    user_store,
184                                    cx,
185                                )
186                            })
187                            .await?;
188
189                        this.update(&mut cx, |this, cx| this.set_room(Some(room.clone()), cx))
190                            .await?;
191
192                        anyhow::Ok(room)
193                    };
194
195                    let room = create_room.await;
196                    this.update(&mut cx, |this, _| this.pending_room_creation = None);
197                    room.map_err(Arc::new)
198                })
199                .shared();
200            self.pending_room_creation = Some(room.clone());
201            cx.foreground().spawn(async move {
202                room.await.map_err(|err| anyhow!("{:?}", err))?;
203                anyhow::Ok(())
204            })
205        };
206
207        cx.spawn(|this, mut cx| async move {
208            let result = invite.await;
209            this.update(&mut cx, |this, cx| {
210                this.pending_invites.remove(&called_user_id);
211                this.report_call_event("invite", cx);
212                cx.notify();
213            });
214            result
215        })
216    }
217
218    pub fn cancel_invite(
219        &mut self,
220        called_user_id: u64,
221        cx: &mut ModelContext<Self>,
222    ) -> Task<Result<()>> {
223        let room_id = if let Some(room) = self.room() {
224            room.read(cx).id()
225        } else {
226            return Task::ready(Err(anyhow!("no active call")));
227        };
228
229        let client = self.client.clone();
230        cx.foreground().spawn(async move {
231            client
232                .request(proto::CancelCall {
233                    room_id,
234                    called_user_id,
235                })
236                .await?;
237            anyhow::Ok(())
238        })
239    }
240
241    pub fn incoming(&self) -> watch::Receiver<Option<IncomingCall>> {
242        self.incoming_call.1.clone()
243    }
244
245    pub fn accept_incoming(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
246        if self.room.is_some() {
247            return Task::ready(Err(anyhow!("cannot join while on another call")));
248        }
249
250        let call = if let Some(call) = self.incoming_call.1.borrow().clone() {
251            call
252        } else {
253            return Task::ready(Err(anyhow!("no incoming call")));
254        };
255
256        let join = Room::join(&call, self.client.clone(), self.user_store.clone(), cx);
257
258        cx.spawn(|this, mut cx| async move {
259            let room = join.await?;
260            this.update(&mut cx, |this, cx| this.set_room(Some(room.clone()), cx))
261                .await?;
262            this.update(&mut cx, |this, cx| {
263                this.report_call_event("accept incoming", cx)
264            });
265            Ok(())
266        })
267    }
268
269    pub fn decline_incoming(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
270        let call = self
271            .incoming_call
272            .0
273            .borrow_mut()
274            .take()
275            .ok_or_else(|| anyhow!("no incoming call"))?;
276        Self::report_call_event_for_room("decline incoming", call.room_id, None, &self.client, cx);
277        self.client.send(proto::DeclineCall {
278            room_id: call.room_id,
279        })?;
280        Ok(())
281    }
282
283    pub fn join_channel(
284        &mut self,
285        channel_id: u64,
286        cx: &mut ModelContext<Self>,
287    ) -> Task<Result<()>> {
288        if let Some(room) = self.room().cloned() {
289            if room.read(cx).channel_id() == Some(channel_id) {
290                return Task::ready(Ok(()));
291            } else {
292                room.update(cx, |room, cx| room.clear_state(cx));
293            }
294        }
295
296        let join = Room::join_channel(channel_id, self.client.clone(), self.user_store.clone(), cx);
297
298        cx.spawn(|this, mut cx| async move {
299            let room = join.await?;
300            this.update(&mut cx, |this, cx| this.set_room(Some(room.clone()), cx))
301                .await?;
302            this.update(&mut cx, |this, cx| {
303                this.report_call_event("join channel", cx)
304            });
305            Ok(())
306        })
307    }
308
309    pub fn hang_up(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
310        cx.notify();
311        self.report_call_event("hang up", cx);
312        Audio::end_call(cx);
313        if let Some((room, _)) = self.room.take() {
314            room.update(cx, |room, cx| room.leave(cx))
315        } else {
316            Task::ready(Ok(()))
317        }
318    }
319
320    pub fn share_project(
321        &mut self,
322        project: ModelHandle<Project>,
323        cx: &mut ModelContext<Self>,
324    ) -> Task<Result<u64>> {
325        if let Some((room, _)) = self.room.as_ref() {
326            self.report_call_event("share project", cx);
327            room.update(cx, |room, cx| room.share_project(project, cx))
328        } else {
329            Task::ready(Err(anyhow!("no active call")))
330        }
331    }
332
333    pub fn unshare_project(
334        &mut self,
335        project: ModelHandle<Project>,
336        cx: &mut ModelContext<Self>,
337    ) -> Result<()> {
338        if let Some((room, _)) = self.room.as_ref() {
339            self.report_call_event("unshare project", cx);
340            room.update(cx, |room, cx| room.unshare_project(project, cx))
341        } else {
342            Err(anyhow!("no active call"))
343        }
344    }
345
346    pub fn set_location(
347        &mut self,
348        project: Option<&ModelHandle<Project>>,
349        cx: &mut ModelContext<Self>,
350    ) -> Task<Result<()>> {
351        self.location = project.map(|project| project.downgrade());
352        if let Some((room, _)) = self.room.as_ref() {
353            room.update(cx, |room, cx| room.set_location(project, cx))
354        } else {
355            Task::ready(Ok(()))
356        }
357    }
358
359    fn set_room(
360        &mut self,
361        room: Option<ModelHandle<Room>>,
362        cx: &mut ModelContext<Self>,
363    ) -> Task<Result<()>> {
364        if room.as_ref() != self.room.as_ref().map(|room| &room.0) {
365            cx.notify();
366            if let Some(room) = room {
367                if room.read(cx).status().is_offline() {
368                    self.room = None;
369                    Task::ready(Ok(()))
370                } else {
371                    let subscriptions = vec![
372                        cx.observe(&room, |this, room, cx| {
373                            if room.read(cx).status().is_offline() {
374                                this.set_room(None, cx).detach_and_log_err(cx);
375                            }
376
377                            cx.notify();
378                        }),
379                        cx.subscribe(&room, |_, _, event, cx| cx.emit(event.clone())),
380                    ];
381                    self.room = Some((room.clone(), subscriptions));
382                    let location = self.location.and_then(|location| location.upgrade(cx));
383                    room.update(cx, |room, cx| room.set_location(location.as_ref(), cx))
384                }
385            } else {
386                self.room = None;
387                Task::ready(Ok(()))
388            }
389        } else {
390            Task::ready(Ok(()))
391        }
392    }
393
394    pub fn room(&self) -> Option<&ModelHandle<Room>> {
395        self.room.as_ref().map(|(room, _)| room)
396    }
397
398    pub fn client(&self) -> Arc<Client> {
399        self.client.clone()
400    }
401
402    pub fn pending_invites(&self) -> &HashSet<u64> {
403        &self.pending_invites
404    }
405
406    pub fn report_call_event(&self, operation: &'static str, cx: &AppContext) {
407        if let Some(room) = self.room() {
408            let room = room.read(cx);
409            Self::report_call_event_for_room(
410                operation,
411                room.id(),
412                room.channel_id(),
413                &self.client,
414                cx,
415            )
416        }
417    }
418
419    pub fn report_call_event_for_room(
420        operation: &'static str,
421        room_id: u64,
422        channel_id: Option<u64>,
423        client: &Arc<Client>,
424        cx: &AppContext,
425    ) {
426        let telemetry = client.telemetry();
427        let telemetry_settings = *settings::get::<TelemetrySettings>(cx);
428        let event = ClickhouseEvent::Call {
429            operation,
430            room_id,
431            channel_id,
432        };
433        telemetry.report_clickhouse_event(event, telemetry_settings);
434    }
435}