1use super::*;
2use rpc::{
3 proto::{channel_member::Kind, ChannelBufferVersion, VectorClockEntry},
4 ErrorCode, ErrorCodeExt,
5};
6use sea_orm::{DbBackend, 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
420 .get_user_channels(user_id, Some(channel), false, tx)
421 .await?;
422 let removed_channels = self
423 .get_channel_descendants_excluding_self([channel], tx)
424 .await?
425 .into_iter()
426 .map(|channel| channel.id)
427 .chain([channel.id])
428 .filter(|channel_id| !new_channels.channels.iter().any(|c| c.id == *channel_id))
429 .collect::<Vec<_>>();
430
431 Ok(MembershipUpdated {
432 channel_id: channel.id,
433 new_channels,
434 removed_channels,
435 })
436 }
437
438 /// Removes a channel member.
439 pub async fn remove_channel_member(
440 &self,
441 channel_id: ChannelId,
442 member_id: UserId,
443 admin_id: UserId,
444 ) -> Result<RemoveChannelMemberResult> {
445 self.transaction(|tx| async move {
446 let channel = self.get_channel_internal(channel_id, &tx).await?;
447
448 if member_id != admin_id {
449 self.check_user_is_channel_admin(&channel, admin_id, &tx)
450 .await?;
451 }
452
453 let result = channel_member::Entity::delete_many()
454 .filter(
455 channel_member::Column::ChannelId
456 .eq(channel_id)
457 .and(channel_member::Column::UserId.eq(member_id)),
458 )
459 .exec(&*tx)
460 .await?;
461
462 if result.rows_affected == 0 {
463 Err(anyhow!("no such member"))?;
464 }
465
466 Ok(RemoveChannelMemberResult {
467 membership_update: self
468 .calculate_membership_updated(&channel, member_id, &tx)
469 .await?,
470 notification_id: self
471 .remove_notification(
472 member_id,
473 rpc::Notification::ChannelInvitation {
474 channel_id: channel_id.to_proto(),
475 channel_name: Default::default(),
476 inviter_id: Default::default(),
477 },
478 &tx,
479 )
480 .await?,
481 })
482 })
483 .await
484 }
485
486 /// Returns all channels for the user with the given ID.
487 pub async fn get_channels_for_user(&self, user_id: UserId) -> Result<ChannelsForUser> {
488 self.transaction(|tx| async move { self.get_user_channels(user_id, None, true, &tx).await })
489 .await
490 }
491
492 /// Returns all channels for the user with the given ID that are descendants
493 /// of the specified ancestor channel.
494 pub async fn get_user_channels(
495 &self,
496 user_id: UserId,
497 ancestor_channel: Option<&channel::Model>,
498 include_invites: bool,
499 tx: &DatabaseTransaction,
500 ) -> Result<ChannelsForUser> {
501 let mut filter = channel_member::Column::UserId.eq(user_id);
502 if !include_invites {
503 filter = filter.and(channel_member::Column::Accepted.eq(true))
504 }
505 if let Some(ancestor) = ancestor_channel {
506 filter = filter.and(channel_member::Column::ChannelId.eq(ancestor.root_id()));
507 }
508
509 let mut channels = Vec::<channel::Model>::new();
510 let mut invited_channels = Vec::<Channel>::new();
511 let mut channel_memberships = Vec::<channel_member::Model>::new();
512 let mut rows = channel_member::Entity::find()
513 .filter(filter)
514 .inner_join(channel::Entity)
515 .select_also(channel::Entity)
516 .stream(tx)
517 .await?;
518 while let Some(row) = rows.next().await {
519 if let (membership, Some(channel)) = row? {
520 if membership.accepted {
521 channel_memberships.push(membership);
522 channels.push(channel);
523 } else {
524 invited_channels.push(Channel::from_model(channel));
525 }
526 }
527 }
528 drop(rows);
529
530 let mut descendants = self
531 .get_channel_descendants_excluding_self(channels.iter(), tx)
532 .await?;
533
534 for channel in channels {
535 if let Err(ix) = descendants.binary_search_by_key(&channel.path(), |c| c.path()) {
536 descendants.insert(ix, channel);
537 }
538 }
539
540 let roles_by_channel_id = channel_memberships
541 .iter()
542 .map(|membership| (membership.channel_id, membership.role))
543 .collect::<HashMap<_, _>>();
544
545 let channels: Vec<Channel> = descendants
546 .into_iter()
547 .filter_map(|channel| {
548 let parent_role = roles_by_channel_id.get(&channel.root_id())?;
549 if parent_role.can_see_channel(channel.visibility) {
550 Some(Channel::from_model(channel))
551 } else {
552 None
553 }
554 })
555 .collect();
556
557 #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
558 enum QueryUserIdsAndChannelIds {
559 ChannelId,
560 UserId,
561 }
562
563 let mut channel_participants: HashMap<ChannelId, Vec<UserId>> = HashMap::default();
564 {
565 let mut rows = room_participant::Entity::find()
566 .inner_join(room::Entity)
567 .filter(room::Column::ChannelId.is_in(channels.iter().map(|c| c.id)))
568 .select_only()
569 .column(room::Column::ChannelId)
570 .column(room_participant::Column::UserId)
571 .into_values::<_, QueryUserIdsAndChannelIds>()
572 .stream(tx)
573 .await?;
574 while let Some(row) = rows.next().await {
575 let row: (ChannelId, UserId) = row?;
576 channel_participants.entry(row.0).or_default().push(row.1)
577 }
578 }
579
580 let channel_ids = channels.iter().map(|c| c.id).collect::<Vec<_>>();
581
582 let mut channel_ids_by_buffer_id = HashMap::default();
583 let mut latest_buffer_versions: Vec<ChannelBufferVersion> = vec![];
584 let mut rows = buffer::Entity::find()
585 .filter(buffer::Column::ChannelId.is_in(channel_ids.iter().copied()))
586 .stream(tx)
587 .await?;
588 while let Some(row) = rows.next().await {
589 let row = row?;
590 channel_ids_by_buffer_id.insert(row.id, row.channel_id);
591 latest_buffer_versions.push(ChannelBufferVersion {
592 channel_id: row.channel_id.0 as u64,
593 epoch: row.latest_operation_epoch.unwrap_or_default() as u64,
594 version: if let Some((latest_lamport_timestamp, latest_replica_id)) = row
595 .latest_operation_lamport_timestamp
596 .zip(row.latest_operation_replica_id)
597 {
598 vec![VectorClockEntry {
599 timestamp: latest_lamport_timestamp as u32,
600 replica_id: latest_replica_id as u32,
601 }]
602 } else {
603 vec![]
604 },
605 });
606 }
607 drop(rows);
608
609 let latest_channel_messages = self.latest_channel_messages(&channel_ids, tx).await?;
610
611 let observed_buffer_versions = self
612 .observed_channel_buffer_changes(&channel_ids_by_buffer_id, user_id, tx)
613 .await?;
614
615 let observed_channel_messages = self
616 .observed_channel_messages(&channel_ids, user_id, tx)
617 .await?;
618
619 let hosted_projects = self
620 .get_hosted_projects(&channel_ids, &roles_by_channel_id, tx)
621 .await?;
622
623 Ok(ChannelsForUser {
624 channel_memberships,
625 channels,
626 invited_channels,
627 hosted_projects,
628 channel_participants,
629 latest_buffer_versions,
630 latest_channel_messages,
631 observed_buffer_versions,
632 observed_channel_messages,
633 })
634 }
635
636 /// Sets the role for the specified channel member.
637 pub async fn set_channel_member_role(
638 &self,
639 channel_id: ChannelId,
640 admin_id: UserId,
641 for_user: UserId,
642 role: ChannelRole,
643 ) -> Result<SetMemberRoleResult> {
644 self.transaction(|tx| async move {
645 let channel = self.get_channel_internal(channel_id, &tx).await?;
646 self.check_user_is_channel_admin(&channel, admin_id, &tx)
647 .await?;
648
649 let membership = channel_member::Entity::find()
650 .filter(
651 channel_member::Column::ChannelId
652 .eq(channel_id)
653 .and(channel_member::Column::UserId.eq(for_user)),
654 )
655 .one(&*tx)
656 .await?;
657
658 let Some(membership) = membership else {
659 Err(anyhow!("no such member"))?
660 };
661
662 let mut update = membership.into_active_model();
663 update.role = ActiveValue::Set(role);
664 let updated = channel_member::Entity::update(update).exec(&*tx).await?;
665
666 if updated.accepted {
667 Ok(SetMemberRoleResult::MembershipUpdated(
668 self.calculate_membership_updated(&channel, for_user, &tx)
669 .await?,
670 ))
671 } else {
672 Ok(SetMemberRoleResult::InviteUpdated(Channel::from_model(
673 channel,
674 )))
675 }
676 })
677 .await
678 }
679
680 /// Returns the details for the specified channel member.
681 pub async fn get_channel_participant_details(
682 &self,
683 channel_id: ChannelId,
684 filter: &str,
685 limit: u64,
686 user_id: UserId,
687 ) -> Result<(Vec<proto::ChannelMember>, Vec<proto::User>)> {
688 let members = self
689 .transaction(move |tx| async move {
690 let channel = self.get_channel_internal(channel_id, &tx).await?;
691 self.check_user_is_channel_participant(&channel, user_id, &tx)
692 .await?;
693 let mut query = channel_member::Entity::find()
694 .find_also_related(user::Entity)
695 .filter(channel_member::Column::ChannelId.eq(channel.root_id()));
696
697 if cfg!(any(test, feature = "sqlite")) && self.pool.get_database_backend() == DbBackend::Sqlite {
698 query = query.filter(Expr::cust_with_values(
699 "UPPER(github_login) LIKE ?",
700 [Self::fuzzy_like_string(&filter.to_uppercase())],
701 ))
702 } else {
703 query = query.filter(Expr::cust_with_values(
704 "github_login ILIKE $1",
705 [Self::fuzzy_like_string(filter)],
706 ))
707 }
708 let members = query.order_by(
709 Expr::cust(
710 "not role = 'admin', not role = 'member', not role = 'guest', not accepted, github_login",
711 ),
712 sea_orm::Order::Asc,
713 )
714 .limit(limit)
715 .all(&*tx)
716 .await?;
717
718 Ok(members)
719 })
720 .await?;
721
722 let mut users: Vec<proto::User> = Vec::with_capacity(members.len());
723
724 let members = members
725 .into_iter()
726 .map(|(member, user)| {
727 if let Some(user) = user {
728 users.push(proto::User {
729 id: user.id.to_proto(),
730 avatar_url: format!(
731 "https://github.com/{}.png?size=128",
732 user.github_login
733 ),
734 github_login: user.github_login,
735 })
736 }
737 proto::ChannelMember {
738 role: member.role.into(),
739 user_id: member.user_id.to_proto(),
740 kind: if member.accepted {
741 Kind::Member
742 } else {
743 Kind::Invitee
744 }
745 .into(),
746 }
747 })
748 .collect();
749
750 Ok((members, users))
751 }
752
753 /// Returns whether the given user is an admin in the specified channel.
754 pub async fn check_user_is_channel_admin(
755 &self,
756 channel: &channel::Model,
757 user_id: UserId,
758 tx: &DatabaseTransaction,
759 ) -> Result<ChannelRole> {
760 let role = self.channel_role_for_user(channel, user_id, tx).await?;
761 match role {
762 Some(ChannelRole::Admin) => Ok(role.unwrap()),
763 Some(ChannelRole::Member)
764 | Some(ChannelRole::Talker)
765 | Some(ChannelRole::Banned)
766 | Some(ChannelRole::Guest)
767 | None => Err(anyhow!(
768 "user is not a channel admin or channel does not exist"
769 ))?,
770 }
771 }
772
773 /// Returns whether the given user is a member of the specified channel.
774 pub async fn check_user_is_channel_member(
775 &self,
776 channel: &channel::Model,
777 user_id: UserId,
778 tx: &DatabaseTransaction,
779 ) -> Result<ChannelRole> {
780 let channel_role = self.channel_role_for_user(channel, user_id, tx).await?;
781 match channel_role {
782 Some(ChannelRole::Admin) | Some(ChannelRole::Member) => Ok(channel_role.unwrap()),
783 Some(ChannelRole::Banned)
784 | Some(ChannelRole::Guest)
785 | Some(ChannelRole::Talker)
786 | None => Err(anyhow!(
787 "user is not a channel member or channel does not exist"
788 ))?,
789 }
790 }
791
792 /// Returns whether the given user is a participant in the specified channel.
793 pub async fn check_user_is_channel_participant(
794 &self,
795 channel: &channel::Model,
796 user_id: UserId,
797 tx: &DatabaseTransaction,
798 ) -> Result<ChannelRole> {
799 let role = self.channel_role_for_user(channel, user_id, tx).await?;
800 match role {
801 Some(ChannelRole::Admin)
802 | Some(ChannelRole::Member)
803 | Some(ChannelRole::Guest)
804 | Some(ChannelRole::Talker) => Ok(role.unwrap()),
805 Some(ChannelRole::Banned) | None => Err(anyhow!(
806 "user is not a channel participant or channel does not exist"
807 ))?,
808 }
809 }
810
811 /// Returns a user's pending invite for the given channel, if one exists.
812 pub async fn pending_invite_for_channel(
813 &self,
814 channel: &channel::Model,
815 user_id: UserId,
816 tx: &DatabaseTransaction,
817 ) -> Result<Option<channel_member::Model>> {
818 let row = channel_member::Entity::find()
819 .filter(channel_member::Column::ChannelId.eq(channel.root_id()))
820 .filter(channel_member::Column::UserId.eq(user_id))
821 .filter(channel_member::Column::Accepted.eq(false))
822 .one(tx)
823 .await?;
824
825 Ok(row)
826 }
827
828 /// Returns the role for a user in the given channel.
829 pub async fn channel_role_for_user(
830 &self,
831 channel: &channel::Model,
832 user_id: UserId,
833 tx: &DatabaseTransaction,
834 ) -> Result<Option<ChannelRole>> {
835 let membership = channel_member::Entity::find()
836 .filter(
837 channel_member::Column::ChannelId
838 .eq(channel.root_id())
839 .and(channel_member::Column::UserId.eq(user_id))
840 .and(channel_member::Column::Accepted.eq(true)),
841 )
842 .one(tx)
843 .await?;
844
845 let Some(membership) = membership else {
846 return Ok(None);
847 };
848
849 if !membership.role.can_see_channel(channel.visibility) {
850 return Ok(None);
851 }
852
853 Ok(Some(membership.role))
854 }
855
856 // Get the descendants of the given set if channels, ordered by their
857 // path.
858 pub(crate) async fn get_channel_descendants_excluding_self(
859 &self,
860 channels: impl IntoIterator<Item = &channel::Model>,
861 tx: &DatabaseTransaction,
862 ) -> Result<Vec<channel::Model>> {
863 let mut filter = Condition::any();
864 for channel in channels.into_iter() {
865 filter = filter.add(channel::Column::ParentPath.like(channel.descendant_path_filter()));
866 }
867
868 if filter.is_empty() {
869 return Ok(vec![]);
870 }
871
872 Ok(channel::Entity::find()
873 .filter(filter)
874 .order_by_asc(Expr::cust("parent_path || id || '/'"))
875 .all(tx)
876 .await?)
877 }
878
879 /// Returns the channel with the given ID.
880 pub async fn get_channel(&self, channel_id: ChannelId, user_id: UserId) -> Result<Channel> {
881 self.transaction(|tx| async move {
882 let channel = self.get_channel_internal(channel_id, &tx).await?;
883 self.check_user_is_channel_participant(&channel, user_id, &tx)
884 .await?;
885
886 Ok(Channel::from_model(channel))
887 })
888 .await
889 }
890
891 pub(crate) async fn get_channel_internal(
892 &self,
893 channel_id: ChannelId,
894 tx: &DatabaseTransaction,
895 ) -> Result<channel::Model> {
896 Ok(channel::Entity::find_by_id(channel_id)
897 .one(tx)
898 .await?
899 .ok_or_else(|| proto::ErrorCode::NoSuchChannel.anyhow())?)
900 }
901
902 pub(crate) async fn get_or_create_channel_room(
903 &self,
904 channel_id: ChannelId,
905 live_kit_room: &str,
906 tx: &DatabaseTransaction,
907 ) -> Result<RoomId> {
908 let room = room::Entity::find()
909 .filter(room::Column::ChannelId.eq(channel_id))
910 .one(tx)
911 .await?;
912
913 let room_id = if let Some(room) = room {
914 room.id
915 } else {
916 let result = room::Entity::insert(room::ActiveModel {
917 channel_id: ActiveValue::Set(Some(channel_id)),
918 live_kit_room: ActiveValue::Set(live_kit_room.to_string()),
919 ..Default::default()
920 })
921 .exec(tx)
922 .await?;
923
924 result.last_insert_id
925 };
926
927 Ok(room_id)
928 }
929
930 /// Move a channel from one parent to another
931 pub async fn move_channel(
932 &self,
933 channel_id: ChannelId,
934 new_parent_id: ChannelId,
935 admin_id: UserId,
936 ) -> Result<(ChannelId, Vec<Channel>)> {
937 self.transaction(|tx| async move {
938 let channel = self.get_channel_internal(channel_id, &tx).await?;
939 self.check_user_is_channel_admin(&channel, admin_id, &tx)
940 .await?;
941 let new_parent = self.get_channel_internal(new_parent_id, &tx).await?;
942
943 if new_parent.root_id() != channel.root_id() {
944 Err(anyhow!(ErrorCode::WrongMoveTarget))?;
945 }
946
947 if new_parent
948 .ancestors_including_self()
949 .any(|id| id == channel.id)
950 {
951 Err(anyhow!(ErrorCode::CircularNesting))?;
952 }
953
954 if channel.visibility == ChannelVisibility::Public
955 && new_parent.visibility != ChannelVisibility::Public
956 {
957 Err(anyhow!(ErrorCode::BadPublicNesting))?;
958 }
959
960 let root_id = channel.root_id();
961 let old_path = format!("{}{}/", channel.parent_path, channel.id);
962 let new_path = format!("{}{}/", new_parent.path(), channel.id);
963
964 let mut model = channel.into_active_model();
965 model.parent_path = ActiveValue::Set(new_parent.path());
966 let channel = model.update(&*tx).await?;
967
968 let descendent_ids =
969 ChannelId::find_by_statement::<QueryIds>(Statement::from_sql_and_values(
970 self.pool.get_database_backend(),
971 "
972 UPDATE channels SET parent_path = REPLACE(parent_path, $1, $2)
973 WHERE parent_path LIKE $3 || '%'
974 RETURNING id
975 ",
976 [old_path.clone().into(), new_path.into(), old_path.into()],
977 ))
978 .all(&*tx)
979 .await?;
980
981 let all_moved_ids = Some(channel.id).into_iter().chain(descendent_ids);
982
983 let channels = channel::Entity::find()
984 .filter(channel::Column::Id.is_in(all_moved_ids))
985 .all(&*tx)
986 .await?
987 .into_iter()
988 .map(|c| Channel::from_model(c))
989 .collect::<Vec<_>>();
990
991 Ok((root_id, channels))
992 })
993 .await
994 }
995}
996
997#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
998enum QueryIds {
999 Id,
1000}
1001
1002#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
1003enum QueryUserIds {
1004 UserId,
1005}