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