rooms.rs

   1use super::*;
   2
   3impl Database {
   4    /// Clears all room participants in rooms attached to a stale server.
   5    pub async fn clear_stale_room_participants(
   6        &self,
   7        room_id: RoomId,
   8        new_server_id: ServerId,
   9    ) -> Result<RoomGuard<RefreshedRoom>> {
  10        self.room_transaction(room_id, |tx| async move {
  11            let stale_participant_filter = Condition::all()
  12                .add(room_participant::Column::RoomId.eq(room_id))
  13                .add(room_participant::Column::AnsweringConnectionId.is_not_null())
  14                .add(room_participant::Column::AnsweringConnectionServerId.ne(new_server_id));
  15
  16            let stale_participant_user_ids = room_participant::Entity::find()
  17                .filter(stale_participant_filter.clone())
  18                .all(&*tx)
  19                .await?
  20                .into_iter()
  21                .map(|participant| participant.user_id)
  22                .collect::<Vec<_>>();
  23
  24            // Delete participants who failed to reconnect and cancel their calls.
  25            let mut canceled_calls_to_user_ids = Vec::new();
  26            room_participant::Entity::delete_many()
  27                .filter(stale_participant_filter)
  28                .exec(&*tx)
  29                .await?;
  30            let called_participants = room_participant::Entity::find()
  31                .filter(
  32                    Condition::all()
  33                        .add(
  34                            room_participant::Column::CallingUserId
  35                                .is_in(stale_participant_user_ids.iter().copied()),
  36                        )
  37                        .add(room_participant::Column::AnsweringConnectionId.is_null()),
  38                )
  39                .all(&*tx)
  40                .await?;
  41            room_participant::Entity::delete_many()
  42                .filter(
  43                    room_participant::Column::Id
  44                        .is_in(called_participants.iter().map(|participant| participant.id)),
  45                )
  46                .exec(&*tx)
  47                .await?;
  48            canceled_calls_to_user_ids.extend(
  49                called_participants
  50                    .into_iter()
  51                    .map(|participant| participant.user_id),
  52            );
  53
  54            let (channel, room) = self.get_channel_room(room_id, &tx).await?;
  55            if channel.is_none() {
  56                // Delete the room if it becomes empty.
  57                if room.participants.is_empty() {
  58                    project::Entity::delete_many()
  59                        .filter(project::Column::RoomId.eq(room_id))
  60                        .exec(&*tx)
  61                        .await?;
  62                    room::Entity::delete_by_id(room_id).exec(&*tx).await?;
  63                }
  64            };
  65
  66            Ok(RefreshedRoom {
  67                room,
  68                channel,
  69                stale_participant_user_ids,
  70                canceled_calls_to_user_ids,
  71            })
  72        })
  73        .await
  74    }
  75
  76    /// Returns the incoming calls for user with the given ID.
  77    pub async fn incoming_call_for_user(
  78        &self,
  79        user_id: UserId,
  80    ) -> Result<Option<proto::IncomingCall>> {
  81        self.transaction(|tx| async move {
  82            let pending_participant = room_participant::Entity::find()
  83                .filter(
  84                    room_participant::Column::UserId
  85                        .eq(user_id)
  86                        .and(room_participant::Column::AnsweringConnectionId.is_null()),
  87                )
  88                .one(&*tx)
  89                .await?;
  90
  91            if let Some(pending_participant) = pending_participant {
  92                let room = self.get_room(pending_participant.room_id, &tx).await?;
  93                Ok(Self::build_incoming_call(&room, user_id))
  94            } else {
  95                Ok(None)
  96            }
  97        })
  98        .await
  99    }
 100
 101    /// Creates a new room.
 102    pub async fn create_room(
 103        &self,
 104        user_id: UserId,
 105        connection: ConnectionId,
 106        live_kit_room: &str,
 107    ) -> Result<proto::Room> {
 108        self.transaction(|tx| async move {
 109            let room = room::ActiveModel {
 110                live_kit_room: ActiveValue::set(live_kit_room.into()),
 111                ..Default::default()
 112            }
 113            .insert(&*tx)
 114            .await?;
 115            room_participant::ActiveModel {
 116                room_id: ActiveValue::set(room.id),
 117                user_id: ActiveValue::set(user_id),
 118                answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
 119                answering_connection_server_id: ActiveValue::set(Some(ServerId(
 120                    connection.owner_id as i32,
 121                ))),
 122                answering_connection_lost: ActiveValue::set(false),
 123                calling_user_id: ActiveValue::set(user_id),
 124                calling_connection_id: ActiveValue::set(connection.id as i32),
 125                calling_connection_server_id: ActiveValue::set(Some(ServerId(
 126                    connection.owner_id as i32,
 127                ))),
 128                participant_index: ActiveValue::set(Some(0)),
 129                role: ActiveValue::set(Some(ChannelRole::Admin)),
 130
 131                id: ActiveValue::NotSet,
 132                location_kind: ActiveValue::NotSet,
 133                location_project_id: ActiveValue::NotSet,
 134                initial_project_id: ActiveValue::NotSet,
 135            }
 136            .insert(&*tx)
 137            .await?;
 138
 139            let room = self.get_room(room.id, &tx).await?;
 140            Ok(room)
 141        })
 142        .await
 143    }
 144
 145    pub async fn call(
 146        &self,
 147        room_id: RoomId,
 148        calling_user_id: UserId,
 149        calling_connection: ConnectionId,
 150        called_user_id: UserId,
 151        initial_project_id: Option<ProjectId>,
 152    ) -> Result<RoomGuard<(proto::Room, proto::IncomingCall)>> {
 153        self.room_transaction(room_id, |tx| async move {
 154            let caller = room_participant::Entity::find()
 155                .filter(
 156                    room_participant::Column::UserId
 157                        .eq(calling_user_id)
 158                        .and(room_participant::Column::RoomId.eq(room_id)),
 159                )
 160                .one(&*tx)
 161                .await?
 162                .ok_or_else(|| anyhow!("user is not in the room"))?;
 163
 164            let called_user_role = match caller.role.unwrap_or(ChannelRole::Member) {
 165                ChannelRole::Admin | ChannelRole::Member => ChannelRole::Member,
 166                ChannelRole::Guest | ChannelRole::Talker => ChannelRole::Guest,
 167                ChannelRole::Banned => return Err(anyhow!("banned users cannot invite").into()),
 168            };
 169
 170            room_participant::ActiveModel {
 171                room_id: ActiveValue::set(room_id),
 172                user_id: ActiveValue::set(called_user_id),
 173                answering_connection_lost: ActiveValue::set(false),
 174                participant_index: ActiveValue::NotSet,
 175                calling_user_id: ActiveValue::set(calling_user_id),
 176                calling_connection_id: ActiveValue::set(calling_connection.id as i32),
 177                calling_connection_server_id: ActiveValue::set(Some(ServerId(
 178                    calling_connection.owner_id as i32,
 179                ))),
 180                initial_project_id: ActiveValue::set(initial_project_id),
 181                role: ActiveValue::set(Some(called_user_role)),
 182
 183                id: ActiveValue::NotSet,
 184                answering_connection_id: ActiveValue::NotSet,
 185                answering_connection_server_id: ActiveValue::NotSet,
 186                location_kind: ActiveValue::NotSet,
 187                location_project_id: ActiveValue::NotSet,
 188            }
 189            .insert(&*tx)
 190            .await?;
 191
 192            let room = self.get_room(room_id, &tx).await?;
 193            let incoming_call = Self::build_incoming_call(&room, called_user_id)
 194                .ok_or_else(|| anyhow!("failed to build incoming call"))?;
 195            Ok((room, incoming_call))
 196        })
 197        .await
 198    }
 199
 200    pub async fn call_failed(
 201        &self,
 202        room_id: RoomId,
 203        called_user_id: UserId,
 204    ) -> Result<RoomGuard<proto::Room>> {
 205        self.room_transaction(room_id, |tx| async move {
 206            room_participant::Entity::delete_many()
 207                .filter(
 208                    room_participant::Column::RoomId
 209                        .eq(room_id)
 210                        .and(room_participant::Column::UserId.eq(called_user_id)),
 211                )
 212                .exec(&*tx)
 213                .await?;
 214            let room = self.get_room(room_id, &tx).await?;
 215            Ok(room)
 216        })
 217        .await
 218    }
 219
 220    pub async fn decline_call(
 221        &self,
 222        expected_room_id: Option<RoomId>,
 223        user_id: UserId,
 224    ) -> Result<Option<RoomGuard<proto::Room>>> {
 225        self.optional_room_transaction(|tx| async move {
 226            let mut filter = Condition::all()
 227                .add(room_participant::Column::UserId.eq(user_id))
 228                .add(room_participant::Column::AnsweringConnectionId.is_null());
 229            if let Some(room_id) = expected_room_id {
 230                filter = filter.add(room_participant::Column::RoomId.eq(room_id));
 231            }
 232            let participant = room_participant::Entity::find()
 233                .filter(filter)
 234                .one(&*tx)
 235                .await?;
 236
 237            let participant = if let Some(participant) = participant {
 238                participant
 239            } else if expected_room_id.is_some() {
 240                return Err(anyhow!("could not find call to decline"))?;
 241            } else {
 242                return Ok(None);
 243            };
 244
 245            let room_id = participant.room_id;
 246            room_participant::Entity::delete(participant.into_active_model())
 247                .exec(&*tx)
 248                .await?;
 249
 250            let room = self.get_room(room_id, &tx).await?;
 251            Ok(Some((room_id, room)))
 252        })
 253        .await
 254    }
 255
 256    pub async fn cancel_call(
 257        &self,
 258        room_id: RoomId,
 259        calling_connection: ConnectionId,
 260        called_user_id: UserId,
 261    ) -> Result<RoomGuard<proto::Room>> {
 262        self.room_transaction(room_id, |tx| async move {
 263            let participant = room_participant::Entity::find()
 264                .filter(
 265                    Condition::all()
 266                        .add(room_participant::Column::UserId.eq(called_user_id))
 267                        .add(room_participant::Column::RoomId.eq(room_id))
 268                        .add(
 269                            room_participant::Column::CallingConnectionId
 270                                .eq(calling_connection.id as i32),
 271                        )
 272                        .add(
 273                            room_participant::Column::CallingConnectionServerId
 274                                .eq(calling_connection.owner_id as i32),
 275                        )
 276                        .add(room_participant::Column::AnsweringConnectionId.is_null()),
 277                )
 278                .one(&*tx)
 279                .await?
 280                .ok_or_else(|| anyhow!("no call to cancel"))?;
 281
 282            room_participant::Entity::delete(participant.into_active_model())
 283                .exec(&*tx)
 284                .await?;
 285
 286            let room = self.get_room(room_id, &tx).await?;
 287            Ok(room)
 288        })
 289        .await
 290    }
 291
 292    pub async fn join_room(
 293        &self,
 294        room_id: RoomId,
 295        user_id: UserId,
 296        connection: ConnectionId,
 297    ) -> Result<RoomGuard<JoinRoom>> {
 298        self.room_transaction(room_id, |tx| async move {
 299            #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
 300            enum QueryChannelId {
 301                ChannelId,
 302            }
 303
 304            let channel_id: Option<ChannelId> = room::Entity::find()
 305                .select_only()
 306                .column(room::Column::ChannelId)
 307                .filter(room::Column::Id.eq(room_id))
 308                .into_values::<_, QueryChannelId>()
 309                .one(&*tx)
 310                .await?
 311                .ok_or_else(|| anyhow!("no such room"))?;
 312
 313            if channel_id.is_some() {
 314                Err(anyhow!("tried to join channel call directly"))?
 315            }
 316
 317            let participant_index = self
 318                .get_next_participant_index_internal(room_id, &tx)
 319                .await?;
 320
 321            let result = room_participant::Entity::update_many()
 322                .filter(
 323                    Condition::all()
 324                        .add(room_participant::Column::RoomId.eq(room_id))
 325                        .add(room_participant::Column::UserId.eq(user_id))
 326                        .add(room_participant::Column::AnsweringConnectionId.is_null()),
 327                )
 328                .set(room_participant::ActiveModel {
 329                    participant_index: ActiveValue::Set(Some(participant_index)),
 330                    answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
 331                    answering_connection_server_id: ActiveValue::set(Some(ServerId(
 332                        connection.owner_id as i32,
 333                    ))),
 334                    answering_connection_lost: ActiveValue::set(false),
 335                    ..Default::default()
 336                })
 337                .exec(&*tx)
 338                .await?;
 339            if result.rows_affected == 0 {
 340                Err(anyhow!("room does not exist or was already joined"))?;
 341            }
 342
 343            let room = self.get_room(room_id, &tx).await?;
 344            Ok(JoinRoom {
 345                room,
 346                channel: None,
 347            })
 348        })
 349        .await
 350    }
 351
 352    pub async fn stale_room_connection(&self, user_id: UserId) -> Result<Option<ConnectionId>> {
 353        self.transaction(|tx| async move {
 354            let participant = room_participant::Entity::find()
 355                .filter(room_participant::Column::UserId.eq(user_id))
 356                .one(&*tx)
 357                .await?;
 358            Ok(participant.and_then(|p| p.answering_connection()))
 359        })
 360        .await
 361    }
 362
 363    async fn get_next_participant_index_internal(
 364        &self,
 365        room_id: RoomId,
 366        tx: &DatabaseTransaction,
 367    ) -> Result<i32> {
 368        #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
 369        enum QueryParticipantIndices {
 370            ParticipantIndex,
 371        }
 372        let existing_participant_indices: Vec<i32> = room_participant::Entity::find()
 373            .filter(
 374                room_participant::Column::RoomId
 375                    .eq(room_id)
 376                    .and(room_participant::Column::ParticipantIndex.is_not_null()),
 377            )
 378            .select_only()
 379            .column(room_participant::Column::ParticipantIndex)
 380            .into_values::<_, QueryParticipantIndices>()
 381            .all(tx)
 382            .await?;
 383
 384        let mut participant_index = 0;
 385        while existing_participant_indices.contains(&participant_index) {
 386            participant_index += 1;
 387        }
 388
 389        Ok(participant_index)
 390    }
 391
 392    /// Returns the channel ID for the given room, if it has one.
 393    pub async fn channel_id_for_room(&self, room_id: RoomId) -> Result<Option<ChannelId>> {
 394        self.transaction(|tx| async move {
 395            let room: Option<room::Model> = room::Entity::find()
 396                .filter(room::Column::Id.eq(room_id))
 397                .one(&*tx)
 398                .await?;
 399
 400            Ok(room.and_then(|room| room.channel_id))
 401        })
 402        .await
 403    }
 404
 405    pub(crate) async fn join_channel_room_internal(
 406        &self,
 407        room_id: RoomId,
 408        user_id: UserId,
 409        connection: ConnectionId,
 410        role: ChannelRole,
 411        tx: &DatabaseTransaction,
 412    ) -> Result<JoinRoom> {
 413        let participant_index = self
 414            .get_next_participant_index_internal(room_id, tx)
 415            .await?;
 416
 417        // If someone has been invited into the room, accept the invite instead of inserting
 418        let result = room_participant::Entity::update_many()
 419            .filter(
 420                Condition::all()
 421                    .add(room_participant::Column::RoomId.eq(room_id))
 422                    .add(room_participant::Column::UserId.eq(user_id))
 423                    .add(room_participant::Column::AnsweringConnectionId.is_null()),
 424            )
 425            .set(room_participant::ActiveModel {
 426                participant_index: ActiveValue::Set(Some(participant_index)),
 427                answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
 428                answering_connection_server_id: ActiveValue::set(Some(ServerId(
 429                    connection.owner_id as i32,
 430                ))),
 431                answering_connection_lost: ActiveValue::set(false),
 432                ..Default::default()
 433            })
 434            .exec(tx)
 435            .await?;
 436
 437        if result.rows_affected == 0 {
 438            room_participant::Entity::insert(room_participant::ActiveModel {
 439                room_id: ActiveValue::set(room_id),
 440                user_id: ActiveValue::set(user_id),
 441                answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
 442                answering_connection_server_id: ActiveValue::set(Some(ServerId(
 443                    connection.owner_id as i32,
 444                ))),
 445                answering_connection_lost: ActiveValue::set(false),
 446                calling_user_id: ActiveValue::set(user_id),
 447                calling_connection_id: ActiveValue::set(connection.id as i32),
 448                calling_connection_server_id: ActiveValue::set(Some(ServerId(
 449                    connection.owner_id as i32,
 450                ))),
 451                participant_index: ActiveValue::Set(Some(participant_index)),
 452                role: ActiveValue::set(Some(role)),
 453                id: ActiveValue::NotSet,
 454                location_kind: ActiveValue::NotSet,
 455                location_project_id: ActiveValue::NotSet,
 456                initial_project_id: ActiveValue::NotSet,
 457            })
 458            .exec(tx)
 459            .await?;
 460        }
 461
 462        let (channel, room) = self.get_channel_room(room_id, &tx).await?;
 463        let channel = channel.ok_or_else(|| anyhow!("no channel for room"))?;
 464        Ok(JoinRoom {
 465            room,
 466            channel: Some(channel),
 467        })
 468    }
 469
 470    pub async fn rejoin_room(
 471        &self,
 472        rejoin_room: proto::RejoinRoom,
 473        user_id: UserId,
 474        connection: ConnectionId,
 475    ) -> Result<RoomGuard<RejoinedRoom>> {
 476        let room_id = RoomId::from_proto(rejoin_room.id);
 477        self.room_transaction(room_id, |tx| async {
 478            let tx = tx;
 479            let participant_update = room_participant::Entity::update_many()
 480                .filter(
 481                    Condition::all()
 482                        .add(room_participant::Column::RoomId.eq(room_id))
 483                        .add(room_participant::Column::UserId.eq(user_id))
 484                        .add(room_participant::Column::AnsweringConnectionId.is_not_null()),
 485                )
 486                .set(room_participant::ActiveModel {
 487                    answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
 488                    answering_connection_server_id: ActiveValue::set(Some(ServerId(
 489                        connection.owner_id as i32,
 490                    ))),
 491                    answering_connection_lost: ActiveValue::set(false),
 492                    ..Default::default()
 493                })
 494                .exec(&*tx)
 495                .await?;
 496            if participant_update.rows_affected == 0 {
 497                return Err(anyhow!("room does not exist or was already joined"))?;
 498            }
 499
 500            let mut reshared_projects = Vec::new();
 501            for reshared_project in &rejoin_room.reshared_projects {
 502                let project_id = ProjectId::from_proto(reshared_project.project_id);
 503                let project = project::Entity::find_by_id(project_id)
 504                    .one(&*tx)
 505                    .await?
 506                    .ok_or_else(|| anyhow!("project does not exist"))?;
 507                if project.host_user_id != Some(user_id) {
 508                    return Err(anyhow!("no such project"))?;
 509                }
 510
 511                let mut collaborators = project
 512                    .find_related(project_collaborator::Entity)
 513                    .all(&*tx)
 514                    .await?;
 515                let host_ix = collaborators
 516                    .iter()
 517                    .position(|collaborator| {
 518                        collaborator.user_id == user_id && collaborator.is_host
 519                    })
 520                    .ok_or_else(|| anyhow!("host not found among collaborators"))?;
 521                let host = collaborators.swap_remove(host_ix);
 522                let old_connection_id = host.connection();
 523
 524                project::Entity::update(project::ActiveModel {
 525                    host_connection_id: ActiveValue::set(Some(connection.id as i32)),
 526                    host_connection_server_id: ActiveValue::set(Some(ServerId(
 527                        connection.owner_id as i32,
 528                    ))),
 529                    ..project.into_active_model()
 530                })
 531                .exec(&*tx)
 532                .await?;
 533                project_collaborator::Entity::update(project_collaborator::ActiveModel {
 534                    connection_id: ActiveValue::set(connection.id as i32),
 535                    connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
 536                    ..host.into_active_model()
 537                })
 538                .exec(&*tx)
 539                .await?;
 540
 541                self.update_project_worktrees(project_id, &reshared_project.worktrees, &tx)
 542                    .await?;
 543
 544                reshared_projects.push(ResharedProject {
 545                    id: project_id,
 546                    old_connection_id,
 547                    collaborators: collaborators
 548                        .iter()
 549                        .map(|collaborator| ProjectCollaborator {
 550                            connection_id: collaborator.connection(),
 551                            user_id: collaborator.user_id,
 552                            replica_id: collaborator.replica_id,
 553                            is_host: collaborator.is_host,
 554                        })
 555                        .collect(),
 556                    worktrees: reshared_project.worktrees.clone(),
 557                });
 558            }
 559
 560            project::Entity::delete_many()
 561                .filter(
 562                    Condition::all()
 563                        .add(project::Column::RoomId.eq(room_id))
 564                        .add(project::Column::HostUserId.eq(user_id))
 565                        .add(
 566                            project::Column::Id
 567                                .is_not_in(reshared_projects.iter().map(|project| project.id)),
 568                        ),
 569                )
 570                .exec(&*tx)
 571                .await?;
 572
 573            let mut rejoined_projects = Vec::new();
 574            for rejoined_project in &rejoin_room.rejoined_projects {
 575                let project_id = ProjectId::from_proto(rejoined_project.id);
 576                let Some(project) = project::Entity::find_by_id(project_id).one(&*tx).await? else {
 577                    continue;
 578                };
 579
 580                let mut worktrees = Vec::new();
 581                let db_worktrees = project.find_related(worktree::Entity).all(&*tx).await?;
 582                for db_worktree in db_worktrees {
 583                    let mut worktree = RejoinedWorktree {
 584                        id: db_worktree.id as u64,
 585                        abs_path: db_worktree.abs_path,
 586                        root_name: db_worktree.root_name,
 587                        visible: db_worktree.visible,
 588                        updated_entries: Default::default(),
 589                        removed_entries: Default::default(),
 590                        updated_repositories: Default::default(),
 591                        removed_repositories: Default::default(),
 592                        diagnostic_summaries: Default::default(),
 593                        settings_files: Default::default(),
 594                        scan_id: db_worktree.scan_id as u64,
 595                        completed_scan_id: db_worktree.completed_scan_id as u64,
 596                    };
 597
 598                    let rejoined_worktree = rejoined_project
 599                        .worktrees
 600                        .iter()
 601                        .find(|worktree| worktree.id == db_worktree.id as u64);
 602
 603                    // File entries
 604                    {
 605                        let entry_filter = if let Some(rejoined_worktree) = rejoined_worktree {
 606                            worktree_entry::Column::ScanId.gt(rejoined_worktree.scan_id)
 607                        } else {
 608                            worktree_entry::Column::IsDeleted.eq(false)
 609                        };
 610
 611                        let mut db_entries = worktree_entry::Entity::find()
 612                            .filter(
 613                                Condition::all()
 614                                    .add(worktree_entry::Column::ProjectId.eq(project.id))
 615                                    .add(worktree_entry::Column::WorktreeId.eq(worktree.id))
 616                                    .add(entry_filter),
 617                            )
 618                            .stream(&*tx)
 619                            .await?;
 620
 621                        while let Some(db_entry) = db_entries.next().await {
 622                            let db_entry = db_entry?;
 623                            if db_entry.is_deleted {
 624                                worktree.removed_entries.push(db_entry.id as u64);
 625                            } else {
 626                                worktree.updated_entries.push(proto::Entry {
 627                                    id: db_entry.id as u64,
 628                                    is_dir: db_entry.is_dir,
 629                                    path: db_entry.path,
 630                                    inode: db_entry.inode as u64,
 631                                    mtime: Some(proto::Timestamp {
 632                                        seconds: db_entry.mtime_seconds as u64,
 633                                        nanos: db_entry.mtime_nanos as u32,
 634                                    }),
 635                                    is_symlink: db_entry.is_symlink,
 636                                    is_ignored: db_entry.is_ignored,
 637                                    is_external: db_entry.is_external,
 638                                    git_status: db_entry.git_status.map(|status| status as i32),
 639                                });
 640                            }
 641                        }
 642                    }
 643
 644                    // Repository Entries
 645                    {
 646                        let repository_entry_filter =
 647                            if let Some(rejoined_worktree) = rejoined_worktree {
 648                                worktree_repository::Column::ScanId.gt(rejoined_worktree.scan_id)
 649                            } else {
 650                                worktree_repository::Column::IsDeleted.eq(false)
 651                            };
 652
 653                        let mut db_repositories = worktree_repository::Entity::find()
 654                            .filter(
 655                                Condition::all()
 656                                    .add(worktree_repository::Column::ProjectId.eq(project.id))
 657                                    .add(worktree_repository::Column::WorktreeId.eq(worktree.id))
 658                                    .add(repository_entry_filter),
 659                            )
 660                            .stream(&*tx)
 661                            .await?;
 662
 663                        while let Some(db_repository) = db_repositories.next().await {
 664                            let db_repository = db_repository?;
 665                            if db_repository.is_deleted {
 666                                worktree
 667                                    .removed_repositories
 668                                    .push(db_repository.work_directory_id as u64);
 669                            } else {
 670                                worktree.updated_repositories.push(proto::RepositoryEntry {
 671                                    work_directory_id: db_repository.work_directory_id as u64,
 672                                    branch: db_repository.branch,
 673                                });
 674                            }
 675                        }
 676                    }
 677
 678                    worktrees.push(worktree);
 679                }
 680
 681                let language_servers = project
 682                    .find_related(language_server::Entity)
 683                    .all(&*tx)
 684                    .await?
 685                    .into_iter()
 686                    .map(|language_server| proto::LanguageServer {
 687                        id: language_server.id as u64,
 688                        name: language_server.name,
 689                    })
 690                    .collect::<Vec<_>>();
 691
 692                {
 693                    let mut db_settings_files = worktree_settings_file::Entity::find()
 694                        .filter(worktree_settings_file::Column::ProjectId.eq(project_id))
 695                        .stream(&*tx)
 696                        .await?;
 697                    while let Some(db_settings_file) = db_settings_files.next().await {
 698                        let db_settings_file = db_settings_file?;
 699                        if let Some(worktree) = worktrees
 700                            .iter_mut()
 701                            .find(|w| w.id == db_settings_file.worktree_id as u64)
 702                        {
 703                            worktree.settings_files.push(WorktreeSettingsFile {
 704                                path: db_settings_file.path,
 705                                content: db_settings_file.content,
 706                            });
 707                        }
 708                    }
 709                }
 710
 711                let mut collaborators = project
 712                    .find_related(project_collaborator::Entity)
 713                    .all(&*tx)
 714                    .await?;
 715                let self_collaborator = if let Some(self_collaborator_ix) = collaborators
 716                    .iter()
 717                    .position(|collaborator| collaborator.user_id == user_id)
 718                {
 719                    collaborators.swap_remove(self_collaborator_ix)
 720                } else {
 721                    continue;
 722                };
 723                let old_connection_id = self_collaborator.connection();
 724                project_collaborator::Entity::update(project_collaborator::ActiveModel {
 725                    connection_id: ActiveValue::set(connection.id as i32),
 726                    connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
 727                    ..self_collaborator.into_active_model()
 728                })
 729                .exec(&*tx)
 730                .await?;
 731
 732                let collaborators = collaborators
 733                    .into_iter()
 734                    .map(|collaborator| ProjectCollaborator {
 735                        connection_id: collaborator.connection(),
 736                        user_id: collaborator.user_id,
 737                        replica_id: collaborator.replica_id,
 738                        is_host: collaborator.is_host,
 739                    })
 740                    .collect::<Vec<_>>();
 741
 742                rejoined_projects.push(RejoinedProject {
 743                    id: project_id,
 744                    old_connection_id,
 745                    collaborators,
 746                    worktrees,
 747                    language_servers,
 748                });
 749            }
 750
 751            let (channel, room) = self.get_channel_room(room_id, &tx).await?;
 752
 753            Ok(RejoinedRoom {
 754                room,
 755                channel,
 756                rejoined_projects,
 757                reshared_projects,
 758            })
 759        })
 760        .await
 761    }
 762
 763    pub async fn leave_room(
 764        &self,
 765        connection: ConnectionId,
 766    ) -> Result<Option<RoomGuard<LeftRoom>>> {
 767        self.optional_room_transaction(|tx| async move {
 768            let leaving_participant = room_participant::Entity::find()
 769                .filter(
 770                    Condition::all()
 771                        .add(
 772                            room_participant::Column::AnsweringConnectionId
 773                                .eq(connection.id as i32),
 774                        )
 775                        .add(
 776                            room_participant::Column::AnsweringConnectionServerId
 777                                .eq(connection.owner_id as i32),
 778                        ),
 779                )
 780                .one(&*tx)
 781                .await?;
 782
 783            if let Some(leaving_participant) = leaving_participant {
 784                // Leave room.
 785                let room_id = leaving_participant.room_id;
 786                room_participant::Entity::delete_by_id(leaving_participant.id)
 787                    .exec(&*tx)
 788                    .await?;
 789
 790                // Cancel pending calls initiated by the leaving user.
 791                let called_participants = room_participant::Entity::find()
 792                    .filter(
 793                        Condition::all()
 794                            .add(
 795                                room_participant::Column::CallingUserId
 796                                    .eq(leaving_participant.user_id),
 797                            )
 798                            .add(room_participant::Column::AnsweringConnectionId.is_null()),
 799                    )
 800                    .all(&*tx)
 801                    .await?;
 802                room_participant::Entity::delete_many()
 803                    .filter(
 804                        room_participant::Column::Id
 805                            .is_in(called_participants.iter().map(|participant| participant.id)),
 806                    )
 807                    .exec(&*tx)
 808                    .await?;
 809                let canceled_calls_to_user_ids = called_participants
 810                    .into_iter()
 811                    .map(|participant| participant.user_id)
 812                    .collect();
 813
 814                // Detect left projects.
 815                #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
 816                enum QueryProjectIds {
 817                    ProjectId,
 818                }
 819                let project_ids: Vec<ProjectId> = project_collaborator::Entity::find()
 820                    .select_only()
 821                    .column_as(
 822                        project_collaborator::Column::ProjectId,
 823                        QueryProjectIds::ProjectId,
 824                    )
 825                    .filter(
 826                        Condition::all()
 827                            .add(
 828                                project_collaborator::Column::ConnectionId.eq(connection.id as i32),
 829                            )
 830                            .add(
 831                                project_collaborator::Column::ConnectionServerId
 832                                    .eq(connection.owner_id as i32),
 833                            ),
 834                    )
 835                    .into_values::<_, QueryProjectIds>()
 836                    .all(&*tx)
 837                    .await?;
 838                let mut left_projects = HashMap::default();
 839                let mut collaborators = project_collaborator::Entity::find()
 840                    .filter(project_collaborator::Column::ProjectId.is_in(project_ids))
 841                    .stream(&*tx)
 842                    .await?;
 843                while let Some(collaborator) = collaborators.next().await {
 844                    let collaborator = collaborator?;
 845                    let left_project =
 846                        left_projects
 847                            .entry(collaborator.project_id)
 848                            .or_insert(LeftProject {
 849                                id: collaborator.project_id,
 850                                host_user_id: Default::default(),
 851                                connection_ids: Default::default(),
 852                                host_connection_id: None,
 853                            });
 854
 855                    let collaborator_connection_id = collaborator.connection();
 856                    if collaborator_connection_id != connection {
 857                        left_project.connection_ids.push(collaborator_connection_id);
 858                    }
 859
 860                    if collaborator.is_host {
 861                        left_project.host_user_id = Some(collaborator.user_id);
 862                        left_project.host_connection_id = Some(collaborator_connection_id);
 863                    }
 864                }
 865                drop(collaborators);
 866
 867                // Leave projects.
 868                project_collaborator::Entity::delete_many()
 869                    .filter(
 870                        Condition::all()
 871                            .add(
 872                                project_collaborator::Column::ConnectionId.eq(connection.id as i32),
 873                            )
 874                            .add(
 875                                project_collaborator::Column::ConnectionServerId
 876                                    .eq(connection.owner_id as i32),
 877                            ),
 878                    )
 879                    .exec(&*tx)
 880                    .await?;
 881
 882                follower::Entity::delete_many()
 883                    .filter(
 884                        Condition::all()
 885                            .add(follower::Column::FollowerConnectionId.eq(connection.id as i32)),
 886                    )
 887                    .exec(&*tx)
 888                    .await?;
 889
 890                // Unshare projects.
 891                project::Entity::delete_many()
 892                    .filter(
 893                        Condition::all()
 894                            .add(project::Column::RoomId.eq(room_id))
 895                            .add(project::Column::HostConnectionId.eq(connection.id as i32))
 896                            .add(
 897                                project::Column::HostConnectionServerId
 898                                    .eq(connection.owner_id as i32),
 899                            ),
 900                    )
 901                    .exec(&*tx)
 902                    .await?;
 903
 904                let (channel, room) = self.get_channel_room(room_id, &tx).await?;
 905                let deleted = if room.participants.is_empty() {
 906                    let result = room::Entity::delete_by_id(room_id).exec(&*tx).await?;
 907                    result.rows_affected > 0
 908                } else {
 909                    false
 910                };
 911
 912                let left_room = LeftRoom {
 913                    room,
 914                    channel,
 915                    left_projects,
 916                    canceled_calls_to_user_ids,
 917                    deleted,
 918                };
 919
 920                if left_room.room.participants.is_empty() {
 921                    self.rooms.remove(&room_id);
 922                }
 923
 924                Ok(Some((room_id, left_room)))
 925            } else {
 926                Ok(None)
 927            }
 928        })
 929        .await
 930    }
 931
 932    /// Updates the location of a participant in the given room.
 933    pub async fn update_room_participant_location(
 934        &self,
 935        room_id: RoomId,
 936        connection: ConnectionId,
 937        location: proto::ParticipantLocation,
 938    ) -> Result<RoomGuard<proto::Room>> {
 939        self.room_transaction(room_id, |tx| async {
 940            let tx = tx;
 941            let location_kind;
 942            let location_project_id;
 943            match location
 944                .variant
 945                .as_ref()
 946                .ok_or_else(|| anyhow!("invalid location"))?
 947            {
 948                proto::participant_location::Variant::SharedProject(project) => {
 949                    location_kind = 0;
 950                    location_project_id = Some(ProjectId::from_proto(project.id));
 951                }
 952                proto::participant_location::Variant::UnsharedProject(_) => {
 953                    location_kind = 1;
 954                    location_project_id = None;
 955                }
 956                proto::participant_location::Variant::External(_) => {
 957                    location_kind = 2;
 958                    location_project_id = None;
 959                }
 960            }
 961
 962            let result = room_participant::Entity::update_many()
 963                .filter(
 964                    Condition::all()
 965                        .add(room_participant::Column::RoomId.eq(room_id))
 966                        .add(
 967                            room_participant::Column::AnsweringConnectionId
 968                                .eq(connection.id as i32),
 969                        )
 970                        .add(
 971                            room_participant::Column::AnsweringConnectionServerId
 972                                .eq(connection.owner_id as i32),
 973                        ),
 974                )
 975                .set(room_participant::ActiveModel {
 976                    location_kind: ActiveValue::set(Some(location_kind)),
 977                    location_project_id: ActiveValue::set(location_project_id),
 978                    ..Default::default()
 979                })
 980                .exec(&*tx)
 981                .await?;
 982
 983            if result.rows_affected == 1 {
 984                let room = self.get_room(room_id, &tx).await?;
 985                Ok(room)
 986            } else {
 987                Err(anyhow!("could not update room participant location"))?
 988            }
 989        })
 990        .await
 991    }
 992
 993    /// Sets the role of a participant in the given room.
 994    pub async fn set_room_participant_role(
 995        &self,
 996        admin_id: UserId,
 997        room_id: RoomId,
 998        user_id: UserId,
 999        role: ChannelRole,
1000    ) -> Result<RoomGuard<proto::Room>> {
1001        self.room_transaction(room_id, |tx| async move {
1002            room_participant::Entity::find()
1003                .filter(
1004                    Condition::all()
1005                        .add(room_participant::Column::RoomId.eq(room_id))
1006                        .add(room_participant::Column::UserId.eq(admin_id))
1007                        .add(room_participant::Column::Role.eq(ChannelRole::Admin)),
1008                )
1009                .one(&*tx)
1010                .await?
1011                .ok_or_else(|| anyhow!("only admins can set participant role"))?;
1012
1013            if role.requires_cla() {
1014                self.check_user_has_signed_cla(user_id, room_id, &tx)
1015                    .await?;
1016            }
1017
1018            let result = room_participant::Entity::update_many()
1019                .filter(
1020                    Condition::all()
1021                        .add(room_participant::Column::RoomId.eq(room_id))
1022                        .add(room_participant::Column::UserId.eq(user_id)),
1023                )
1024                .set(room_participant::ActiveModel {
1025                    role: ActiveValue::set(Some(role)),
1026                    ..Default::default()
1027                })
1028                .exec(&*tx)
1029                .await?;
1030
1031            if result.rows_affected != 1 {
1032                Err(anyhow!("could not update room participant role"))?;
1033            }
1034            self.get_room(room_id, &tx).await
1035        })
1036        .await
1037    }
1038
1039    async fn check_user_has_signed_cla(
1040        &self,
1041        user_id: UserId,
1042        room_id: RoomId,
1043        tx: &DatabaseTransaction,
1044    ) -> Result<()> {
1045        let channel = room::Entity::find_by_id(room_id)
1046            .one(tx)
1047            .await?
1048            .ok_or_else(|| anyhow!("could not find room"))?
1049            .find_related(channel::Entity)
1050            .one(tx)
1051            .await?;
1052
1053        if let Some(channel) = channel {
1054            let requires_zed_cla = channel.requires_zed_cla
1055                || channel::Entity::find()
1056                    .filter(
1057                        channel::Column::Id
1058                            .is_in(channel.ancestors())
1059                            .and(channel::Column::RequiresZedCla.eq(true)),
1060                    )
1061                    .count(tx)
1062                    .await?
1063                    > 0;
1064            if requires_zed_cla {
1065                if contributor::Entity::find()
1066                    .filter(contributor::Column::UserId.eq(user_id))
1067                    .one(tx)
1068                    .await?
1069                    .is_none()
1070                {
1071                    Err(anyhow!("user has not signed the Zed CLA"))?;
1072                }
1073            }
1074        }
1075        Ok(())
1076    }
1077
1078    pub async fn connection_lost(&self, connection: ConnectionId) -> Result<()> {
1079        self.transaction(|tx| async move {
1080            self.room_connection_lost(connection, &tx).await?;
1081            self.channel_buffer_connection_lost(connection, &tx).await?;
1082            self.channel_chat_connection_lost(connection, &tx).await?;
1083            Ok(())
1084        })
1085        .await
1086    }
1087
1088    pub async fn room_connection_lost(
1089        &self,
1090        connection: ConnectionId,
1091        tx: &DatabaseTransaction,
1092    ) -> Result<()> {
1093        let participant = room_participant::Entity::find()
1094            .filter(
1095                Condition::all()
1096                    .add(room_participant::Column::AnsweringConnectionId.eq(connection.id as i32))
1097                    .add(
1098                        room_participant::Column::AnsweringConnectionServerId
1099                            .eq(connection.owner_id as i32),
1100                    ),
1101            )
1102            .one(tx)
1103            .await?;
1104
1105        if let Some(participant) = participant {
1106            room_participant::Entity::update(room_participant::ActiveModel {
1107                answering_connection_lost: ActiveValue::set(true),
1108                ..participant.into_active_model()
1109            })
1110            .exec(tx)
1111            .await?;
1112        }
1113        Ok(())
1114    }
1115
1116    fn build_incoming_call(
1117        room: &proto::Room,
1118        called_user_id: UserId,
1119    ) -> Option<proto::IncomingCall> {
1120        let pending_participant = room
1121            .pending_participants
1122            .iter()
1123            .find(|participant| participant.user_id == called_user_id.to_proto())?;
1124
1125        Some(proto::IncomingCall {
1126            room_id: room.id,
1127            calling_user_id: pending_participant.calling_user_id,
1128            participant_user_ids: room
1129                .participants
1130                .iter()
1131                .map(|participant| participant.user_id)
1132                .collect(),
1133            initial_project: room.participants.iter().find_map(|participant| {
1134                let initial_project_id = pending_participant.initial_project_id?;
1135                participant
1136                    .projects
1137                    .iter()
1138                    .find(|project| project.id == initial_project_id)
1139                    .cloned()
1140            }),
1141        })
1142    }
1143
1144    pub async fn get_room(&self, room_id: RoomId, tx: &DatabaseTransaction) -> Result<proto::Room> {
1145        let (_, room) = self.get_channel_room(room_id, tx).await?;
1146        Ok(room)
1147    }
1148
1149    pub async fn room_connection_ids(
1150        &self,
1151        room_id: RoomId,
1152        connection_id: ConnectionId,
1153    ) -> Result<RoomGuard<HashSet<ConnectionId>>> {
1154        self.room_transaction(room_id, |tx| async move {
1155            let mut participants = room_participant::Entity::find()
1156                .filter(room_participant::Column::RoomId.eq(room_id))
1157                .stream(&*tx)
1158                .await?;
1159
1160            let mut is_participant = false;
1161            let mut connection_ids = HashSet::default();
1162            while let Some(participant) = participants.next().await {
1163                let participant = participant?;
1164                if let Some(answering_connection) = participant.answering_connection() {
1165                    if answering_connection == connection_id {
1166                        is_participant = true;
1167                    } else {
1168                        connection_ids.insert(answering_connection);
1169                    }
1170                }
1171            }
1172
1173            if !is_participant {
1174                Err(anyhow!("not a room participant"))?;
1175            }
1176
1177            Ok(connection_ids)
1178        })
1179        .await
1180    }
1181
1182    async fn get_channel_room(
1183        &self,
1184        room_id: RoomId,
1185        tx: &DatabaseTransaction,
1186    ) -> Result<(Option<channel::Model>, proto::Room)> {
1187        let db_room = room::Entity::find_by_id(room_id)
1188            .one(tx)
1189            .await?
1190            .ok_or_else(|| anyhow!("could not find room"))?;
1191
1192        let mut db_participants = db_room
1193            .find_related(room_participant::Entity)
1194            .stream(tx)
1195            .await?;
1196        let mut participants = HashMap::default();
1197        let mut pending_participants = Vec::new();
1198        while let Some(db_participant) = db_participants.next().await {
1199            let db_participant = db_participant?;
1200            if let (
1201                Some(answering_connection_id),
1202                Some(answering_connection_server_id),
1203                Some(participant_index),
1204            ) = (
1205                db_participant.answering_connection_id,
1206                db_participant.answering_connection_server_id,
1207                db_participant.participant_index,
1208            ) {
1209                let location = match (
1210                    db_participant.location_kind,
1211                    db_participant.location_project_id,
1212                ) {
1213                    (Some(0), Some(project_id)) => {
1214                        Some(proto::participant_location::Variant::SharedProject(
1215                            proto::participant_location::SharedProject {
1216                                id: project_id.to_proto(),
1217                            },
1218                        ))
1219                    }
1220                    (Some(1), _) => Some(proto::participant_location::Variant::UnsharedProject(
1221                        Default::default(),
1222                    )),
1223                    _ => Some(proto::participant_location::Variant::External(
1224                        Default::default(),
1225                    )),
1226                };
1227
1228                let answering_connection = ConnectionId {
1229                    owner_id: answering_connection_server_id.0 as u32,
1230                    id: answering_connection_id as u32,
1231                };
1232                participants.insert(
1233                    answering_connection,
1234                    proto::Participant {
1235                        user_id: db_participant.user_id.to_proto(),
1236                        peer_id: Some(answering_connection.into()),
1237                        projects: Default::default(),
1238                        location: Some(proto::ParticipantLocation { variant: location }),
1239                        participant_index: participant_index as u32,
1240                        role: db_participant.role.unwrap_or(ChannelRole::Member).into(),
1241                    },
1242                );
1243            } else {
1244                pending_participants.push(proto::PendingParticipant {
1245                    user_id: db_participant.user_id.to_proto(),
1246                    calling_user_id: db_participant.calling_user_id.to_proto(),
1247                    initial_project_id: db_participant.initial_project_id.map(|id| id.to_proto()),
1248                });
1249            }
1250        }
1251        drop(db_participants);
1252
1253        let mut db_projects = db_room
1254            .find_related(project::Entity)
1255            .find_with_related(worktree::Entity)
1256            .stream(tx)
1257            .await?;
1258
1259        while let Some(row) = db_projects.next().await {
1260            let (db_project, db_worktree) = row?;
1261            let host_connection = db_project.host_connection()?;
1262            if let Some(participant) = participants.get_mut(&host_connection) {
1263                let project = if let Some(project) = participant
1264                    .projects
1265                    .iter_mut()
1266                    .find(|project| project.id == db_project.id.to_proto())
1267                {
1268                    project
1269                } else {
1270                    participant.projects.push(proto::ParticipantProject {
1271                        id: db_project.id.to_proto(),
1272                        worktree_root_names: Default::default(),
1273                    });
1274                    participant.projects.last_mut().unwrap()
1275                };
1276
1277                if let Some(db_worktree) = db_worktree {
1278                    if db_worktree.visible {
1279                        project.worktree_root_names.push(db_worktree.root_name);
1280                    }
1281                }
1282            }
1283        }
1284        drop(db_projects);
1285
1286        let mut db_followers = db_room.find_related(follower::Entity).stream(tx).await?;
1287        let mut followers = Vec::new();
1288        while let Some(db_follower) = db_followers.next().await {
1289            let db_follower = db_follower?;
1290            followers.push(proto::Follower {
1291                leader_id: Some(db_follower.leader_connection().into()),
1292                follower_id: Some(db_follower.follower_connection().into()),
1293                project_id: db_follower.project_id.to_proto(),
1294            });
1295        }
1296        drop(db_followers);
1297
1298        let channel = if let Some(channel_id) = db_room.channel_id {
1299            Some(self.get_channel_internal(channel_id, tx).await?)
1300        } else {
1301            None
1302        };
1303
1304        Ok((
1305            channel,
1306            proto::Room {
1307                id: db_room.id.to_proto(),
1308                live_kit_room: db_room.live_kit_room,
1309                participants: participants.into_values().collect(),
1310                pending_participants,
1311                followers,
1312            },
1313        ))
1314    }
1315}