channels.rs

   1use super::*;
   2use rpc::{
   3    proto::{channel_member::Kind, ChannelBufferVersion, VectorClockEntry},
   4    ErrorCode, ErrorCodeExt,
   5};
   6use sea_orm::TryGetableMany;
   7
   8impl Database {
   9    #[cfg(test)]
  10    pub async fn all_channels(&self) -> Result<Vec<(ChannelId, String)>> {
  11        self.transaction(move |tx| async move {
  12            let mut channels = Vec::new();
  13            let mut rows = channel::Entity::find().stream(&*tx).await?;
  14            while let Some(row) = rows.next().await {
  15                let row = row?;
  16                channels.push((row.id, row.name));
  17            }
  18            Ok(channels)
  19        })
  20        .await
  21    }
  22
  23    #[cfg(test)]
  24    pub async fn create_root_channel(&self, name: &str, creator_id: UserId) -> Result<ChannelId> {
  25        Ok(self.create_channel(name, None, creator_id).await?.0.id)
  26    }
  27
  28    #[cfg(test)]
  29    pub async fn create_sub_channel(
  30        &self,
  31        name: &str,
  32        parent: ChannelId,
  33        creator_id: UserId,
  34    ) -> Result<ChannelId> {
  35        Ok(self
  36            .create_channel(name, Some(parent), creator_id)
  37            .await?
  38            .0
  39            .id)
  40    }
  41
  42    /// Creates a new channel.
  43    pub async fn create_channel(
  44        &self,
  45        name: &str,
  46        parent_channel_id: Option<ChannelId>,
  47        admin_id: UserId,
  48    ) -> Result<(channel::Model, Option<channel_member::Model>)> {
  49        let name = Self::sanitize_channel_name(name)?;
  50        self.transaction(move |tx| async move {
  51            let mut parent = None;
  52            let mut membership = None;
  53
  54            if let Some(parent_channel_id) = parent_channel_id {
  55                let parent_channel = self.get_channel_internal(parent_channel_id, &tx).await?;
  56                self.check_user_is_channel_admin(&parent_channel, admin_id, &tx)
  57                    .await?;
  58                parent = Some(parent_channel);
  59            }
  60
  61            let channel = channel::ActiveModel {
  62                id: ActiveValue::NotSet,
  63                name: ActiveValue::Set(name.to_string()),
  64                visibility: ActiveValue::Set(ChannelVisibility::Members),
  65                parent_path: ActiveValue::Set(
  66                    parent
  67                        .as_ref()
  68                        .map_or(String::new(), |parent| parent.path()),
  69                ),
  70                requires_zed_cla: ActiveValue::NotSet,
  71            }
  72            .insert(&*tx)
  73            .await?;
  74
  75            if parent.is_none() {
  76                membership = Some(
  77                    channel_member::ActiveModel {
  78                        id: ActiveValue::NotSet,
  79                        channel_id: ActiveValue::Set(channel.id),
  80                        user_id: ActiveValue::Set(admin_id),
  81                        accepted: ActiveValue::Set(true),
  82                        role: ActiveValue::Set(ChannelRole::Admin),
  83                    }
  84                    .insert(&*tx)
  85                    .await?,
  86                );
  87            }
  88
  89            Ok((channel, membership))
  90        })
  91        .await
  92    }
  93
  94    /// Adds a user to the specified channel.
  95    pub async fn join_channel(
  96        &self,
  97        channel_id: ChannelId,
  98        user_id: UserId,
  99        connection: ConnectionId,
 100    ) -> Result<(JoinRoom, Option<MembershipUpdated>, ChannelRole)> {
 101        self.transaction(move |tx| async move {
 102            let channel = self.get_channel_internal(channel_id, &tx).await?;
 103            let mut role = self.channel_role_for_user(&channel, user_id, &tx).await?;
 104
 105            let mut accept_invite_result = None;
 106
 107            if role.is_none() {
 108                if let Some(invitation) = self
 109                    .pending_invite_for_channel(&channel, user_id, &tx)
 110                    .await?
 111                {
 112                    // note, this may be a parent channel
 113                    role = Some(invitation.role);
 114                    channel_member::Entity::update(channel_member::ActiveModel {
 115                        accepted: ActiveValue::Set(true),
 116                        ..invitation.into_active_model()
 117                    })
 118                    .exec(&*tx)
 119                    .await?;
 120
 121                    accept_invite_result = Some(
 122                        self.calculate_membership_updated(&channel, user_id, &tx)
 123                            .await?,
 124                    );
 125
 126                    debug_assert!(
 127                        self.channel_role_for_user(&channel, user_id, &tx).await? == role
 128                    );
 129                } else if channel.visibility == ChannelVisibility::Public {
 130                    role = Some(ChannelRole::Guest);
 131                    channel_member::Entity::insert(channel_member::ActiveModel {
 132                        id: ActiveValue::NotSet,
 133                        channel_id: ActiveValue::Set(channel.root_id()),
 134                        user_id: ActiveValue::Set(user_id),
 135                        accepted: ActiveValue::Set(true),
 136                        role: ActiveValue::Set(ChannelRole::Guest),
 137                    })
 138                    .exec(&*tx)
 139                    .await?;
 140
 141                    accept_invite_result = Some(
 142                        self.calculate_membership_updated(&channel, user_id, &tx)
 143                            .await?,
 144                    );
 145
 146                    debug_assert!(
 147                        self.channel_role_for_user(&channel, user_id, &tx).await? == role
 148                    );
 149                }
 150            }
 151
 152            if role.is_none() || role == Some(ChannelRole::Banned) {
 153                Err(ErrorCode::Forbidden.anyhow())?
 154            }
 155            let role = role.unwrap();
 156
 157            let live_kit_room = format!("channel-{}", nanoid::nanoid!(30));
 158            let room_id = self
 159                .get_or_create_channel_room(channel_id, &live_kit_room, &tx)
 160                .await?;
 161
 162            self.join_channel_room_internal(room_id, user_id, connection, role, &tx)
 163                .await
 164                .map(|jr| (jr, accept_invite_result, role))
 165        })
 166        .await
 167    }
 168
 169    /// Sets the visibility of the given channel.
 170    pub async fn set_channel_visibility(
 171        &self,
 172        channel_id: ChannelId,
 173        visibility: ChannelVisibility,
 174        admin_id: UserId,
 175    ) -> Result<channel::Model> {
 176        self.transaction(move |tx| async move {
 177            let channel = self.get_channel_internal(channel_id, &tx).await?;
 178            self.check_user_is_channel_admin(&channel, admin_id, &tx)
 179                .await?;
 180
 181            if visibility == ChannelVisibility::Public {
 182                if let Some(parent_id) = channel.parent_id() {
 183                    let parent = self.get_channel_internal(parent_id, &tx).await?;
 184
 185                    if parent.visibility != ChannelVisibility::Public {
 186                        Err(ErrorCode::BadPublicNesting
 187                            .with_tag("direction", "parent")
 188                            .anyhow())?;
 189                    }
 190                }
 191            } else if visibility == ChannelVisibility::Members {
 192                if self
 193                    .get_channel_descendants_excluding_self([&channel], &tx)
 194                    .await?
 195                    .into_iter()
 196                    .any(|channel| channel.visibility == ChannelVisibility::Public)
 197                {
 198                    Err(ErrorCode::BadPublicNesting
 199                        .with_tag("direction", "children")
 200                        .anyhow())?;
 201                }
 202            }
 203
 204            let mut model = channel.into_active_model();
 205            model.visibility = ActiveValue::Set(visibility);
 206            let channel = model.update(&*tx).await?;
 207
 208            Ok(channel)
 209        })
 210        .await
 211    }
 212
 213    #[cfg(test)]
 214    pub async fn set_channel_requires_zed_cla(
 215        &self,
 216        channel_id: ChannelId,
 217        requires_zed_cla: bool,
 218    ) -> Result<()> {
 219        self.transaction(move |tx| async move {
 220            let channel = self.get_channel_internal(channel_id, &tx).await?;
 221            let mut model = channel.into_active_model();
 222            model.requires_zed_cla = ActiveValue::Set(requires_zed_cla);
 223            model.update(&*tx).await?;
 224            Ok(())
 225        })
 226        .await
 227    }
 228
 229    /// Deletes the channel with the specified ID.
 230    pub async fn delete_channel(
 231        &self,
 232        channel_id: ChannelId,
 233        user_id: UserId,
 234    ) -> Result<(ChannelId, Vec<ChannelId>)> {
 235        self.transaction(move |tx| async move {
 236            let channel = self.get_channel_internal(channel_id, &tx).await?;
 237            self.check_user_is_channel_admin(&channel, user_id, &tx)
 238                .await?;
 239
 240            let channels_to_remove = self
 241                .get_channel_descendants_excluding_self([&channel], &tx)
 242                .await?
 243                .into_iter()
 244                .map(|channel| channel.id)
 245                .chain(Some(channel_id))
 246                .collect::<Vec<_>>();
 247
 248            channel::Entity::delete_many()
 249                .filter(channel::Column::Id.is_in(channels_to_remove.iter().copied()))
 250                .exec(&*tx)
 251                .await?;
 252
 253            Ok((channel.root_id(), channels_to_remove))
 254        })
 255        .await
 256    }
 257
 258    /// Invites a user to a channel as a member.
 259    pub async fn invite_channel_member(
 260        &self,
 261        channel_id: ChannelId,
 262        invitee_id: UserId,
 263        inviter_id: UserId,
 264        role: ChannelRole,
 265    ) -> Result<InviteMemberResult> {
 266        self.transaction(move |tx| async move {
 267            let channel = self.get_channel_internal(channel_id, &tx).await?;
 268            self.check_user_is_channel_admin(&channel, inviter_id, &tx)
 269                .await?;
 270            if !channel.is_root() {
 271                Err(ErrorCode::NotARootChannel.anyhow())?
 272            }
 273
 274            channel_member::ActiveModel {
 275                id: ActiveValue::NotSet,
 276                channel_id: ActiveValue::Set(channel_id),
 277                user_id: ActiveValue::Set(invitee_id),
 278                accepted: ActiveValue::Set(false),
 279                role: ActiveValue::Set(role),
 280            }
 281            .insert(&*tx)
 282            .await?;
 283
 284            let channel = Channel::from_model(channel);
 285
 286            let notifications = self
 287                .create_notification(
 288                    invitee_id,
 289                    rpc::Notification::ChannelInvitation {
 290                        channel_id: channel_id.to_proto(),
 291                        channel_name: channel.name.clone(),
 292                        inviter_id: inviter_id.to_proto(),
 293                    },
 294                    true,
 295                    &tx,
 296                )
 297                .await?
 298                .into_iter()
 299                .collect();
 300
 301            Ok(InviteMemberResult {
 302                channel,
 303                notifications,
 304            })
 305        })
 306        .await
 307    }
 308
 309    fn sanitize_channel_name(name: &str) -> Result<&str> {
 310        let new_name = name.trim().trim_start_matches('#');
 311        if new_name == "" {
 312            Err(anyhow!("channel name can't be blank"))?;
 313        }
 314        Ok(new_name)
 315    }
 316
 317    /// Renames the specified channel.
 318    pub async fn rename_channel(
 319        &self,
 320        channel_id: ChannelId,
 321        admin_id: UserId,
 322        new_name: &str,
 323    ) -> Result<channel::Model> {
 324        self.transaction(move |tx| async move {
 325            let new_name = Self::sanitize_channel_name(new_name)?.to_string();
 326
 327            let channel = self.get_channel_internal(channel_id, &tx).await?;
 328            self.check_user_is_channel_admin(&channel, admin_id, &tx)
 329                .await?;
 330
 331            let mut model = channel.into_active_model();
 332            model.name = ActiveValue::Set(new_name.clone());
 333            let channel = model.update(&*tx).await?;
 334
 335            Ok(channel)
 336        })
 337        .await
 338    }
 339
 340    /// accept or decline an invite to join a channel
 341    pub async fn respond_to_channel_invite(
 342        &self,
 343        channel_id: ChannelId,
 344        user_id: UserId,
 345        accept: bool,
 346    ) -> Result<RespondToChannelInvite> {
 347        self.transaction(move |tx| async move {
 348            let channel = self.get_channel_internal(channel_id, &tx).await?;
 349
 350            let membership_update = if accept {
 351                let rows_affected = channel_member::Entity::update_many()
 352                    .set(channel_member::ActiveModel {
 353                        accepted: ActiveValue::Set(accept),
 354                        ..Default::default()
 355                    })
 356                    .filter(
 357                        channel_member::Column::ChannelId
 358                            .eq(channel_id)
 359                            .and(channel_member::Column::UserId.eq(user_id))
 360                            .and(channel_member::Column::Accepted.eq(false)),
 361                    )
 362                    .exec(&*tx)
 363                    .await?
 364                    .rows_affected;
 365
 366                if rows_affected == 0 {
 367                    Err(anyhow!("no such invitation"))?;
 368                }
 369
 370                Some(
 371                    self.calculate_membership_updated(&channel, user_id, &tx)
 372                        .await?,
 373                )
 374            } else {
 375                let rows_affected = channel_member::Entity::delete_many()
 376                    .filter(
 377                        channel_member::Column::ChannelId
 378                            .eq(channel_id)
 379                            .and(channel_member::Column::UserId.eq(user_id))
 380                            .and(channel_member::Column::Accepted.eq(false)),
 381                    )
 382                    .exec(&*tx)
 383                    .await?
 384                    .rows_affected;
 385                if rows_affected == 0 {
 386                    Err(anyhow!("no such invitation"))?;
 387                }
 388
 389                None
 390            };
 391
 392            Ok(RespondToChannelInvite {
 393                membership_update,
 394                notifications: self
 395                    .mark_notification_as_read_with_response(
 396                        user_id,
 397                        &rpc::Notification::ChannelInvitation {
 398                            channel_id: channel_id.to_proto(),
 399                            channel_name: Default::default(),
 400                            inviter_id: Default::default(),
 401                        },
 402                        accept,
 403                        &tx,
 404                    )
 405                    .await?
 406                    .into_iter()
 407                    .collect(),
 408            })
 409        })
 410        .await
 411    }
 412
 413    async fn calculate_membership_updated(
 414        &self,
 415        channel: &channel::Model,
 416        user_id: UserId,
 417        tx: &DatabaseTransaction,
 418    ) -> Result<MembershipUpdated> {
 419        let new_channels = self.get_user_channels(user_id, Some(channel), tx).await?;
 420        let removed_channels = self
 421            .get_channel_descendants_excluding_self([channel], tx)
 422            .await?
 423            .into_iter()
 424            .map(|channel| channel.id)
 425            .chain([channel.id])
 426            .filter(|channel_id| !new_channels.channels.iter().any(|c| c.id == *channel_id))
 427            .collect::<Vec<_>>();
 428
 429        Ok(MembershipUpdated {
 430            channel_id: channel.id,
 431            new_channels,
 432            removed_channels,
 433        })
 434    }
 435
 436    /// Removes a channel member.
 437    pub async fn remove_channel_member(
 438        &self,
 439        channel_id: ChannelId,
 440        member_id: UserId,
 441        admin_id: UserId,
 442    ) -> Result<RemoveChannelMemberResult> {
 443        self.transaction(|tx| async move {
 444            let channel = self.get_channel_internal(channel_id, &tx).await?;
 445
 446            if member_id != admin_id {
 447                self.check_user_is_channel_admin(&channel, admin_id, &tx)
 448                    .await?;
 449            }
 450
 451            let result = channel_member::Entity::delete_many()
 452                .filter(
 453                    channel_member::Column::ChannelId
 454                        .eq(channel_id)
 455                        .and(channel_member::Column::UserId.eq(member_id)),
 456                )
 457                .exec(&*tx)
 458                .await?;
 459
 460            if result.rows_affected == 0 {
 461                Err(anyhow!("no such member"))?;
 462            }
 463
 464            Ok(RemoveChannelMemberResult {
 465                membership_update: self
 466                    .calculate_membership_updated(&channel, member_id, &tx)
 467                    .await?,
 468                notification_id: self
 469                    .remove_notification(
 470                        member_id,
 471                        rpc::Notification::ChannelInvitation {
 472                            channel_id: channel_id.to_proto(),
 473                            channel_name: Default::default(),
 474                            inviter_id: Default::default(),
 475                        },
 476                        &tx,
 477                    )
 478                    .await?,
 479            })
 480        })
 481        .await
 482    }
 483
 484    /// Returns all channel invites for the user with the given ID.
 485    pub async fn get_channel_invites_for_user(&self, user_id: UserId) -> Result<Vec<Channel>> {
 486        self.transaction(|tx| async move {
 487            let mut role_for_channel: HashMap<ChannelId, ChannelRole> = HashMap::default();
 488
 489            let channel_invites = channel_member::Entity::find()
 490                .filter(
 491                    channel_member::Column::UserId
 492                        .eq(user_id)
 493                        .and(channel_member::Column::Accepted.eq(false)),
 494                )
 495                .all(&*tx)
 496                .await?;
 497
 498            for invite in channel_invites {
 499                role_for_channel.insert(invite.channel_id, invite.role);
 500            }
 501
 502            let channels = channel::Entity::find()
 503                .filter(channel::Column::Id.is_in(role_for_channel.keys().copied()))
 504                .all(&*tx)
 505                .await?;
 506
 507            let channels = channels.into_iter().map(Channel::from_model).collect();
 508
 509            Ok(channels)
 510        })
 511        .await
 512    }
 513
 514    /// Returns all channels for the user with the given ID.
 515    pub async fn get_channels_for_user(&self, user_id: UserId) -> Result<ChannelsForUser> {
 516        self.transaction(|tx| async move {
 517            let tx = tx;
 518
 519            self.get_user_channels(user_id, None, &tx).await
 520        })
 521        .await
 522    }
 523
 524    /// Returns all channels for the user with the given ID that are descendants
 525    /// of the specified ancestor channel.
 526    pub async fn get_user_channels(
 527        &self,
 528        user_id: UserId,
 529        ancestor_channel: Option<&channel::Model>,
 530        tx: &DatabaseTransaction,
 531    ) -> Result<ChannelsForUser> {
 532        let mut filter = channel_member::Column::UserId
 533            .eq(user_id)
 534            .and(channel_member::Column::Accepted.eq(true));
 535
 536        if let Some(ancestor) = ancestor_channel {
 537            filter = filter.and(channel_member::Column::ChannelId.eq(ancestor.root_id()));
 538        }
 539
 540        let channel_memberships = channel_member::Entity::find()
 541            .filter(filter)
 542            .all(tx)
 543            .await?;
 544
 545        let channels = channel::Entity::find()
 546            .filter(channel::Column::Id.is_in(channel_memberships.iter().map(|m| m.channel_id)))
 547            .all(tx)
 548            .await?;
 549
 550        let mut descendants = self
 551            .get_channel_descendants_excluding_self(channels.iter(), tx)
 552            .await?;
 553
 554        for channel in channels {
 555            if let Err(ix) = descendants.binary_search_by_key(&channel.path(), |c| c.path()) {
 556                descendants.insert(ix, channel);
 557            }
 558        }
 559
 560        let roles_by_channel_id = channel_memberships
 561            .iter()
 562            .map(|membership| (membership.channel_id, membership.role))
 563            .collect::<HashMap<_, _>>();
 564
 565        let channels: Vec<Channel> = descendants
 566            .into_iter()
 567            .filter_map(|channel| {
 568                let parent_role = roles_by_channel_id.get(&channel.root_id())?;
 569                if parent_role.can_see_channel(channel.visibility) {
 570                    Some(Channel::from_model(channel))
 571                } else {
 572                    None
 573                }
 574            })
 575            .collect();
 576
 577        #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
 578        enum QueryUserIdsAndChannelIds {
 579            ChannelId,
 580            UserId,
 581        }
 582
 583        let mut channel_participants: HashMap<ChannelId, Vec<UserId>> = HashMap::default();
 584        {
 585            let mut rows = room_participant::Entity::find()
 586                .inner_join(room::Entity)
 587                .filter(room::Column::ChannelId.is_in(channels.iter().map(|c| c.id)))
 588                .select_only()
 589                .column(room::Column::ChannelId)
 590                .column(room_participant::Column::UserId)
 591                .into_values::<_, QueryUserIdsAndChannelIds>()
 592                .stream(tx)
 593                .await?;
 594            while let Some(row) = rows.next().await {
 595                let row: (ChannelId, UserId) = row?;
 596                channel_participants.entry(row.0).or_default().push(row.1)
 597            }
 598        }
 599
 600        let channel_ids = channels.iter().map(|c| c.id).collect::<Vec<_>>();
 601
 602        let mut channel_ids_by_buffer_id = HashMap::default();
 603        let mut latest_buffer_versions: Vec<ChannelBufferVersion> = vec![];
 604        let mut rows = buffer::Entity::find()
 605            .filter(buffer::Column::ChannelId.is_in(channel_ids.iter().copied()))
 606            .stream(tx)
 607            .await?;
 608        while let Some(row) = rows.next().await {
 609            let row = row?;
 610            channel_ids_by_buffer_id.insert(row.id, row.channel_id);
 611            latest_buffer_versions.push(ChannelBufferVersion {
 612                channel_id: row.channel_id.0 as u64,
 613                epoch: row.latest_operation_epoch.unwrap_or_default() as u64,
 614                version: if let Some((latest_lamport_timestamp, latest_replica_id)) = row
 615                    .latest_operation_lamport_timestamp
 616                    .zip(row.latest_operation_replica_id)
 617                {
 618                    vec![VectorClockEntry {
 619                        timestamp: latest_lamport_timestamp as u32,
 620                        replica_id: latest_replica_id as u32,
 621                    }]
 622                } else {
 623                    vec![]
 624                },
 625            });
 626        }
 627        drop(rows);
 628
 629        let latest_channel_messages = self.latest_channel_messages(&channel_ids, tx).await?;
 630
 631        let observed_buffer_versions = self
 632            .observed_channel_buffer_changes(&channel_ids_by_buffer_id, user_id, tx)
 633            .await?;
 634
 635        let observed_channel_messages = self
 636            .observed_channel_messages(&channel_ids, user_id, tx)
 637            .await?;
 638
 639        let hosted_projects = self
 640            .get_hosted_projects(&channel_ids, &roles_by_channel_id, tx)
 641            .await?;
 642
 643        Ok(ChannelsForUser {
 644            channel_memberships,
 645            channels,
 646            hosted_projects,
 647            channel_participants,
 648            latest_buffer_versions,
 649            latest_channel_messages,
 650            observed_buffer_versions,
 651            observed_channel_messages,
 652        })
 653    }
 654
 655    /// Sets the role for the specified channel member.
 656    pub async fn set_channel_member_role(
 657        &self,
 658        channel_id: ChannelId,
 659        admin_id: UserId,
 660        for_user: UserId,
 661        role: ChannelRole,
 662    ) -> Result<SetMemberRoleResult> {
 663        self.transaction(|tx| async move {
 664            let channel = self.get_channel_internal(channel_id, &tx).await?;
 665            self.check_user_is_channel_admin(&channel, admin_id, &tx)
 666                .await?;
 667
 668            let membership = channel_member::Entity::find()
 669                .filter(
 670                    channel_member::Column::ChannelId
 671                        .eq(channel_id)
 672                        .and(channel_member::Column::UserId.eq(for_user)),
 673                )
 674                .one(&*tx)
 675                .await?;
 676
 677            let Some(membership) = membership else {
 678                Err(anyhow!("no such member"))?
 679            };
 680
 681            let mut update = membership.into_active_model();
 682            update.role = ActiveValue::Set(role);
 683            let updated = channel_member::Entity::update(update).exec(&*tx).await?;
 684
 685            if updated.accepted {
 686                Ok(SetMemberRoleResult::MembershipUpdated(
 687                    self.calculate_membership_updated(&channel, for_user, &tx)
 688                        .await?,
 689                ))
 690            } else {
 691                Ok(SetMemberRoleResult::InviteUpdated(Channel::from_model(
 692                    channel,
 693                )))
 694            }
 695        })
 696        .await
 697    }
 698
 699    /// Returns the details for the specified channel member.
 700    pub async fn get_channel_participant_details(
 701        &self,
 702        channel_id: ChannelId,
 703        user_id: UserId,
 704    ) -> Result<Vec<proto::ChannelMember>> {
 705        let (role, members) = self
 706            .transaction(move |tx| async move {
 707                let channel = self.get_channel_internal(channel_id, &tx).await?;
 708                let role = self
 709                    .check_user_is_channel_participant(&channel, user_id, &tx)
 710                    .await?;
 711                Ok((
 712                    role,
 713                    self.get_channel_participant_details_internal(&channel, &tx)
 714                        .await?,
 715                ))
 716            })
 717            .await?;
 718
 719        if role == ChannelRole::Admin {
 720            Ok(members
 721                .into_iter()
 722                .map(|channel_member| proto::ChannelMember {
 723                    role: channel_member.role.into(),
 724                    user_id: channel_member.user_id.to_proto(),
 725                    kind: if channel_member.accepted {
 726                        Kind::Member
 727                    } else {
 728                        Kind::Invitee
 729                    }
 730                    .into(),
 731                })
 732                .collect())
 733        } else {
 734            return Ok(members
 735                .into_iter()
 736                .filter_map(|member| {
 737                    if !member.accepted {
 738                        return None;
 739                    }
 740                    Some(proto::ChannelMember {
 741                        role: member.role.into(),
 742                        user_id: member.user_id.to_proto(),
 743                        kind: Kind::Member.into(),
 744                    })
 745                })
 746                .collect());
 747        }
 748    }
 749
 750    async fn get_channel_participant_details_internal(
 751        &self,
 752        channel: &channel::Model,
 753        tx: &DatabaseTransaction,
 754    ) -> Result<Vec<channel_member::Model>> {
 755        Ok(channel_member::Entity::find()
 756            .filter(channel_member::Column::ChannelId.eq(channel.root_id()))
 757            .all(tx)
 758            .await?)
 759    }
 760
 761    /// Returns the participants in the given channel.
 762    pub async fn get_channel_participants(
 763        &self,
 764        channel: &channel::Model,
 765        tx: &DatabaseTransaction,
 766    ) -> Result<Vec<UserId>> {
 767        let participants = self
 768            .get_channel_participant_details_internal(channel, tx)
 769            .await?;
 770        Ok(participants
 771            .into_iter()
 772            .map(|member| member.user_id)
 773            .collect())
 774    }
 775
 776    /// Returns whether the given user is an admin in the specified channel.
 777    pub async fn check_user_is_channel_admin(
 778        &self,
 779        channel: &channel::Model,
 780        user_id: UserId,
 781        tx: &DatabaseTransaction,
 782    ) -> Result<ChannelRole> {
 783        let role = self.channel_role_for_user(channel, user_id, tx).await?;
 784        match role {
 785            Some(ChannelRole::Admin) => Ok(role.unwrap()),
 786            Some(ChannelRole::Member)
 787            | Some(ChannelRole::Talker)
 788            | Some(ChannelRole::Banned)
 789            | Some(ChannelRole::Guest)
 790            | None => Err(anyhow!(
 791                "user is not a channel admin or channel does not exist"
 792            ))?,
 793        }
 794    }
 795
 796    /// Returns whether the given user is a member of the specified channel.
 797    pub async fn check_user_is_channel_member(
 798        &self,
 799        channel: &channel::Model,
 800        user_id: UserId,
 801        tx: &DatabaseTransaction,
 802    ) -> Result<ChannelRole> {
 803        let channel_role = self.channel_role_for_user(channel, user_id, tx).await?;
 804        match channel_role {
 805            Some(ChannelRole::Admin) | Some(ChannelRole::Member) => Ok(channel_role.unwrap()),
 806            Some(ChannelRole::Banned)
 807            | Some(ChannelRole::Guest)
 808            | Some(ChannelRole::Talker)
 809            | None => Err(anyhow!(
 810                "user is not a channel member or channel does not exist"
 811            ))?,
 812        }
 813    }
 814
 815    /// Returns whether the given user is a participant in the specified channel.
 816    pub async fn check_user_is_channel_participant(
 817        &self,
 818        channel: &channel::Model,
 819        user_id: UserId,
 820        tx: &DatabaseTransaction,
 821    ) -> Result<ChannelRole> {
 822        let role = self.channel_role_for_user(channel, user_id, tx).await?;
 823        match role {
 824            Some(ChannelRole::Admin)
 825            | Some(ChannelRole::Member)
 826            | Some(ChannelRole::Guest)
 827            | Some(ChannelRole::Talker) => Ok(role.unwrap()),
 828            Some(ChannelRole::Banned) | None => Err(anyhow!(
 829                "user is not a channel participant or channel does not exist"
 830            ))?,
 831        }
 832    }
 833
 834    /// Returns a user's pending invite for the given channel, if one exists.
 835    pub async fn pending_invite_for_channel(
 836        &self,
 837        channel: &channel::Model,
 838        user_id: UserId,
 839        tx: &DatabaseTransaction,
 840    ) -> Result<Option<channel_member::Model>> {
 841        let row = channel_member::Entity::find()
 842            .filter(channel_member::Column::ChannelId.eq(channel.root_id()))
 843            .filter(channel_member::Column::UserId.eq(user_id))
 844            .filter(channel_member::Column::Accepted.eq(false))
 845            .one(tx)
 846            .await?;
 847
 848        Ok(row)
 849    }
 850
 851    /// Returns the role for a user in the given channel.
 852    pub async fn channel_role_for_user(
 853        &self,
 854        channel: &channel::Model,
 855        user_id: UserId,
 856        tx: &DatabaseTransaction,
 857    ) -> Result<Option<ChannelRole>> {
 858        let membership = channel_member::Entity::find()
 859            .filter(
 860                channel_member::Column::ChannelId
 861                    .eq(channel.root_id())
 862                    .and(channel_member::Column::UserId.eq(user_id))
 863                    .and(channel_member::Column::Accepted.eq(true)),
 864            )
 865            .one(tx)
 866            .await?;
 867
 868        let Some(membership) = membership else {
 869            return Ok(None);
 870        };
 871
 872        if !membership.role.can_see_channel(channel.visibility) {
 873            return Ok(None);
 874        }
 875
 876        Ok(Some(membership.role))
 877    }
 878
 879    // Get the descendants of the given set if channels, ordered by their
 880    // path.
 881    pub(crate) async fn get_channel_descendants_excluding_self(
 882        &self,
 883        channels: impl IntoIterator<Item = &channel::Model>,
 884        tx: &DatabaseTransaction,
 885    ) -> Result<Vec<channel::Model>> {
 886        let mut filter = Condition::any();
 887        for channel in channels.into_iter() {
 888            filter = filter.add(channel::Column::ParentPath.like(channel.descendant_path_filter()));
 889        }
 890
 891        if filter.is_empty() {
 892            return Ok(vec![]);
 893        }
 894
 895        Ok(channel::Entity::find()
 896            .filter(filter)
 897            .order_by_asc(Expr::cust("parent_path || id || '/'"))
 898            .all(tx)
 899            .await?)
 900    }
 901
 902    /// Returns the channel with the given ID.
 903    pub async fn get_channel(&self, channel_id: ChannelId, user_id: UserId) -> Result<Channel> {
 904        self.transaction(|tx| async move {
 905            let channel = self.get_channel_internal(channel_id, &tx).await?;
 906            self.check_user_is_channel_participant(&channel, user_id, &tx)
 907                .await?;
 908
 909            Ok(Channel::from_model(channel))
 910        })
 911        .await
 912    }
 913
 914    pub(crate) async fn get_channel_internal(
 915        &self,
 916        channel_id: ChannelId,
 917        tx: &DatabaseTransaction,
 918    ) -> Result<channel::Model> {
 919        Ok(channel::Entity::find_by_id(channel_id)
 920            .one(tx)
 921            .await?
 922            .ok_or_else(|| proto::ErrorCode::NoSuchChannel.anyhow())?)
 923    }
 924
 925    pub(crate) async fn get_or_create_channel_room(
 926        &self,
 927        channel_id: ChannelId,
 928        live_kit_room: &str,
 929        tx: &DatabaseTransaction,
 930    ) -> Result<RoomId> {
 931        let room = room::Entity::find()
 932            .filter(room::Column::ChannelId.eq(channel_id))
 933            .one(tx)
 934            .await?;
 935
 936        let room_id = if let Some(room) = room {
 937            room.id
 938        } else {
 939            let result = room::Entity::insert(room::ActiveModel {
 940                channel_id: ActiveValue::Set(Some(channel_id)),
 941                live_kit_room: ActiveValue::Set(live_kit_room.to_string()),
 942                ..Default::default()
 943            })
 944            .exec(tx)
 945            .await?;
 946
 947            result.last_insert_id
 948        };
 949
 950        Ok(room_id)
 951    }
 952
 953    /// Move a channel from one parent to another
 954    pub async fn move_channel(
 955        &self,
 956        channel_id: ChannelId,
 957        new_parent_id: ChannelId,
 958        admin_id: UserId,
 959    ) -> Result<(ChannelId, Vec<Channel>)> {
 960        self.transaction(|tx| async move {
 961            let channel = self.get_channel_internal(channel_id, &tx).await?;
 962            self.check_user_is_channel_admin(&channel, admin_id, &tx)
 963                .await?;
 964            let new_parent = self.get_channel_internal(new_parent_id, &tx).await?;
 965
 966            if new_parent.root_id() != channel.root_id() {
 967                Err(anyhow!(ErrorCode::WrongMoveTarget))?;
 968            }
 969
 970            if new_parent
 971                .ancestors_including_self()
 972                .any(|id| id == channel.id)
 973            {
 974                Err(anyhow!(ErrorCode::CircularNesting))?;
 975            }
 976
 977            if channel.visibility == ChannelVisibility::Public
 978                && new_parent.visibility != ChannelVisibility::Public
 979            {
 980                Err(anyhow!(ErrorCode::BadPublicNesting))?;
 981            }
 982
 983            let root_id = channel.root_id();
 984            let old_path = format!("{}{}/", channel.parent_path, channel.id);
 985            let new_path = format!("{}{}/", new_parent.path(), channel.id);
 986
 987            let mut model = channel.into_active_model();
 988            model.parent_path = ActiveValue::Set(new_parent.path());
 989            let channel = model.update(&*tx).await?;
 990
 991            let descendent_ids =
 992                ChannelId::find_by_statement::<QueryIds>(Statement::from_sql_and_values(
 993                    self.pool.get_database_backend(),
 994                    "
 995                    UPDATE channels SET parent_path = REPLACE(parent_path, $1, $2)
 996                    WHERE parent_path LIKE $3 || '%'
 997                    RETURNING id
 998                ",
 999                    [old_path.clone().into(), new_path.into(), old_path.into()],
1000                ))
1001                .all(&*tx)
1002                .await?;
1003
1004            let all_moved_ids = Some(channel.id).into_iter().chain(descendent_ids);
1005
1006            let channels = channel::Entity::find()
1007                .filter(channel::Column::Id.is_in(all_moved_ids))
1008                .all(&*tx)
1009                .await?
1010                .into_iter()
1011                .map(|c| Channel::from_model(c))
1012                .collect::<Vec<_>>();
1013
1014            Ok((root_id, channels))
1015        })
1016        .await
1017    }
1018}
1019
1020#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
1021enum QueryIds {
1022    Id,
1023}
1024
1025#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
1026enum QueryUserIds {
1027    UserId,
1028}