1pub mod call_settings;
2pub mod participant;
3pub mod room;
4
5use std::sync::Arc;
6
7use anyhow::{anyhow, Result};
8use call_settings::CallSettings;
9use client::{
10 proto, ChannelId, ClickhouseEvent, Client, TelemetrySettings, TypedEnvelope, User, UserStore,
11};
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, &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 if let Some((room, _)) = self.room.take() {
313 room.update(cx, |room, cx| room.leave(cx))
314 } else {
315 Task::ready(Ok(()))
316 }
317 }
318
319 pub fn share_project(
320 &mut self,
321 project: ModelHandle<Project>,
322 cx: &mut ModelContext<Self>,
323 ) -> Task<Result<u64>> {
324 if let Some((room, _)) = self.room.as_ref() {
325 self.report_call_event("share project", cx);
326 room.update(cx, |room, cx| room.share_project(project, cx))
327 } else {
328 Task::ready(Err(anyhow!("no active call")))
329 }
330 }
331
332 pub fn unshare_project(
333 &mut self,
334 project: ModelHandle<Project>,
335 cx: &mut ModelContext<Self>,
336 ) -> Result<()> {
337 if let Some((room, _)) = self.room.as_ref() {
338 self.report_call_event("unshare project", cx);
339 room.update(cx, |room, cx| room.unshare_project(project, cx))
340 } else {
341 Err(anyhow!("no active call"))
342 }
343 }
344
345 pub fn set_location(
346 &mut self,
347 project: Option<&ModelHandle<Project>>,
348 cx: &mut ModelContext<Self>,
349 ) -> Task<Result<()>> {
350 self.location = project.map(|project| project.downgrade());
351 if let Some((room, _)) = self.room.as_ref() {
352 room.update(cx, |room, cx| room.set_location(project, cx))
353 } else {
354 Task::ready(Ok(()))
355 }
356 }
357
358 fn set_room(
359 &mut self,
360 room: Option<ModelHandle<Room>>,
361 cx: &mut ModelContext<Self>,
362 ) -> Task<Result<()>> {
363 if room.as_ref() != self.room.as_ref().map(|room| &room.0) {
364 cx.notify();
365 if let Some(room) = room {
366 if room.read(cx).status().is_offline() {
367 self.room = None;
368 Task::ready(Ok(()))
369 } else {
370 let subscriptions = vec![
371 cx.observe(&room, |this, room, cx| {
372 if room.read(cx).status().is_offline() {
373 this.set_room(None, cx).detach_and_log_err(cx);
374 }
375
376 cx.notify();
377 }),
378 cx.subscribe(&room, |_, _, event, cx| cx.emit(event.clone())),
379 ];
380 self.room = Some((room.clone(), subscriptions));
381 let location = self.location.and_then(|location| location.upgrade(cx));
382 room.update(cx, |room, cx| room.set_location(location.as_ref(), cx))
383 }
384 } else {
385 self.room = None;
386 Task::ready(Ok(()))
387 }
388 } else {
389 Task::ready(Ok(()))
390 }
391 }
392
393 pub fn room(&self) -> Option<&ModelHandle<Room>> {
394 self.room.as_ref().map(|(room, _)| room)
395 }
396
397 pub fn client(&self) -> Arc<Client> {
398 self.client.clone()
399 }
400
401 pub fn pending_invites(&self) -> &HashSet<u64> {
402 &self.pending_invites
403 }
404
405 fn report_call_event(&self, operation: &'static str, cx: &AppContext) {
406 if let Some(room) = self.room() {
407 Self::report_call_event_for_room(operation, room.read(cx).id(), &self.client, cx)
408 }
409 }
410
411 pub fn report_call_event_for_room(
412 operation: &'static str,
413 room_id: u64,
414 client: &Arc<Client>,
415 cx: &AppContext,
416 ) {
417 let telemetry = client.telemetry();
418 let telemetry_settings = *settings::get::<TelemetrySettings>(cx);
419 let event = ClickhouseEvent::Call { operation, room_id };
420 telemetry.report_clickhouse_event(event, telemetry_settings);
421 }
422}