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(
277            "decline incoming",
278            Some(call.room_id),
279            None,
280            &self.client,
281            cx,
282        );
283        self.client.send(proto::DeclineCall {
284            room_id: call.room_id,
285        })?;
286        Ok(())
287    }
288
289    pub fn join_channel(
290        &mut self,
291        channel_id: u64,
292        cx: &mut ModelContext<Self>,
293    ) -> Task<Result<()>> {
294        if let Some(room) = self.room().cloned() {
295            if room.read(cx).channel_id() == Some(channel_id) {
296                return Task::ready(Ok(()));
297            } else {
298                room.update(cx, |room, cx| room.clear_state(cx));
299            }
300        }
301
302        let join = Room::join_channel(channel_id, self.client.clone(), self.user_store.clone(), cx);
303
304        cx.spawn(|this, mut cx| async move {
305            let room = join.await?;
306            this.update(&mut cx, |this, cx| this.set_room(Some(room.clone()), cx))
307                .await?;
308            this.update(&mut cx, |this, cx| {
309                this.report_call_event("join channel", cx)
310            });
311            Ok(())
312        })
313    }
314
315    pub fn hang_up(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
316        cx.notify();
317        self.report_call_event("hang up", cx);
318        Audio::end_call(cx);
319        if let Some((room, _)) = self.room.take() {
320            room.update(cx, |room, cx| room.leave(cx))
321        } else {
322            Task::ready(Ok(()))
323        }
324    }
325
326    pub fn share_project(
327        &mut self,
328        project: ModelHandle<Project>,
329        cx: &mut ModelContext<Self>,
330    ) -> Task<Result<u64>> {
331        if let Some((room, _)) = self.room.as_ref() {
332            self.report_call_event("share project", cx);
333            room.update(cx, |room, cx| room.share_project(project, cx))
334        } else {
335            Task::ready(Err(anyhow!("no active call")))
336        }
337    }
338
339    pub fn unshare_project(
340        &mut self,
341        project: ModelHandle<Project>,
342        cx: &mut ModelContext<Self>,
343    ) -> Result<()> {
344        if let Some((room, _)) = self.room.as_ref() {
345            self.report_call_event("unshare project", cx);
346            room.update(cx, |room, cx| room.unshare_project(project, cx))
347        } else {
348            Err(anyhow!("no active call"))
349        }
350    }
351
352    pub fn set_location(
353        &mut self,
354        project: Option<&ModelHandle<Project>>,
355        cx: &mut ModelContext<Self>,
356    ) -> Task<Result<()>> {
357        self.location = project.map(|project| project.downgrade());
358        if let Some((room, _)) = self.room.as_ref() {
359            room.update(cx, |room, cx| room.set_location(project, cx))
360        } else {
361            Task::ready(Ok(()))
362        }
363    }
364
365    fn set_room(
366        &mut self,
367        room: Option<ModelHandle<Room>>,
368        cx: &mut ModelContext<Self>,
369    ) -> Task<Result<()>> {
370        if room.as_ref() != self.room.as_ref().map(|room| &room.0) {
371            cx.notify();
372            if let Some(room) = room {
373                if room.read(cx).status().is_offline() {
374                    self.room = None;
375                    Task::ready(Ok(()))
376                } else {
377                    let subscriptions = vec![
378                        cx.observe(&room, |this, room, cx| {
379                            if room.read(cx).status().is_offline() {
380                                this.set_room(None, cx).detach_and_log_err(cx);
381                            }
382
383                            cx.notify();
384                        }),
385                        cx.subscribe(&room, |_, _, event, cx| cx.emit(event.clone())),
386                    ];
387                    self.room = Some((room.clone(), subscriptions));
388                    let location = self.location.and_then(|location| location.upgrade(cx));
389                    room.update(cx, |room, cx| room.set_location(location.as_ref(), cx))
390                }
391            } else {
392                self.room = None;
393                Task::ready(Ok(()))
394            }
395        } else {
396            Task::ready(Ok(()))
397        }
398    }
399
400    pub fn room(&self) -> Option<&ModelHandle<Room>> {
401        self.room.as_ref().map(|(room, _)| room)
402    }
403
404    pub fn client(&self) -> Arc<Client> {
405        self.client.clone()
406    }
407
408    pub fn pending_invites(&self) -> &HashSet<u64> {
409        &self.pending_invites
410    }
411
412    fn report_call_event(&self, operation: &'static str, cx: &AppContext) {
413        let (room_id, channel_id) = match self.room() {
414            Some(room) => {
415                let room = room.read(cx);
416                (Some(room.id()), room.channel_id())
417            }
418            None => (None, None),
419        };
420        Self::report_call_event_for_room(operation, room_id, channel_id, &self.client, cx)
421    }
422
423    pub fn report_call_event_for_room(
424        operation: &'static str,
425        room_id: Option<u64>,
426        channel_id: Option<u64>,
427        client: &Arc<Client>,
428        cx: &AppContext,
429    ) {
430        let telemetry = client.telemetry();
431        let telemetry_settings = *settings::get::<TelemetrySettings>(cx);
432        let event = ClickhouseEvent::Call {
433            operation,
434            room_id,
435            channel_id,
436        };
437        telemetry.report_clickhouse_event(event, telemetry_settings);
438    }
439}