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