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.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 filter: &str,
704 limit: u64,
705 user_id: UserId,
706 ) -> Result<(Vec<proto::ChannelMember>, Vec<proto::User>)> {
707 let members = self
708 .transaction(move |tx| async move {
709 let channel = self.get_channel_internal(channel_id, &tx).await?;
710 self.check_user_is_channel_participant(&channel, user_id, &tx)
711 .await?;
712 let mut query = channel_member::Entity::find()
713 .find_also_related(user::Entity)
714 .filter(channel_member::Column::ChannelId.eq(channel.root_id()));
715
716 if cfg!(any(test, feature = "sqlite")) && self.pool.get_database_backend() == DbBackend::Sqlite {
717 query = query.filter(Expr::cust_with_values(
718 "UPPER(github_login) LIKE ?",
719 [Self::fuzzy_like_string(&filter.to_uppercase())],
720 ))
721 } else {
722 query = query.filter(Expr::cust_with_values(
723 "github_login ILIKE $1",
724 [Self::fuzzy_like_string(filter)],
725 ))
726 }
727 let members = query.order_by(
728 Expr::cust(
729 "not role = 'admin', not role = 'member', not role = 'guest', not accepted, github_login",
730 ),
731 sea_orm::Order::Asc,
732 )
733 .limit(limit)
734 .all(&*tx)
735 .await?;
736
737 Ok(members)
738 })
739 .await?;
740
741 let mut users: Vec<proto::User> = Vec::with_capacity(members.len());
742
743 let members = members
744 .into_iter()
745 .map(|(member, user)| {
746 if let Some(user) = user {
747 users.push(proto::User {
748 id: user.id.to_proto(),
749 avatar_url: format!(
750 "https://github.com/{}.png?size=128",
751 user.github_login
752 ),
753 github_login: user.github_login,
754 })
755 }
756 proto::ChannelMember {
757 role: member.role.into(),
758 user_id: member.user_id.to_proto(),
759 kind: if member.accepted {
760 Kind::Member
761 } else {
762 Kind::Invitee
763 }
764 .into(),
765 }
766 })
767 .collect();
768
769 Ok((members, users))
770 }
771
772 /// Returns whether the given user is an admin in the specified channel.
773 pub async fn check_user_is_channel_admin(
774 &self,
775 channel: &channel::Model,
776 user_id: UserId,
777 tx: &DatabaseTransaction,
778 ) -> Result<ChannelRole> {
779 let role = self.channel_role_for_user(channel, user_id, tx).await?;
780 match role {
781 Some(ChannelRole::Admin) => Ok(role.unwrap()),
782 Some(ChannelRole::Member)
783 | Some(ChannelRole::Talker)
784 | Some(ChannelRole::Banned)
785 | Some(ChannelRole::Guest)
786 | None => Err(anyhow!(
787 "user is not a channel admin or channel does not exist"
788 ))?,
789 }
790 }
791
792 /// Returns whether the given user is a member of the specified channel.
793 pub async fn check_user_is_channel_member(
794 &self,
795 channel: &channel::Model,
796 user_id: UserId,
797 tx: &DatabaseTransaction,
798 ) -> Result<ChannelRole> {
799 let channel_role = self.channel_role_for_user(channel, user_id, tx).await?;
800 match channel_role {
801 Some(ChannelRole::Admin) | Some(ChannelRole::Member) => Ok(channel_role.unwrap()),
802 Some(ChannelRole::Banned)
803 | Some(ChannelRole::Guest)
804 | Some(ChannelRole::Talker)
805 | None => Err(anyhow!(
806 "user is not a channel member or channel does not exist"
807 ))?,
808 }
809 }
810
811 /// Returns whether the given user is a participant in the specified channel.
812 pub async fn check_user_is_channel_participant(
813 &self,
814 channel: &channel::Model,
815 user_id: UserId,
816 tx: &DatabaseTransaction,
817 ) -> Result<ChannelRole> {
818 let role = self.channel_role_for_user(channel, user_id, tx).await?;
819 match role {
820 Some(ChannelRole::Admin)
821 | Some(ChannelRole::Member)
822 | Some(ChannelRole::Guest)
823 | Some(ChannelRole::Talker) => Ok(role.unwrap()),
824 Some(ChannelRole::Banned) | None => Err(anyhow!(
825 "user is not a channel participant or channel does not exist"
826 ))?,
827 }
828 }
829
830 /// Returns a user's pending invite for the given channel, if one exists.
831 pub async fn pending_invite_for_channel(
832 &self,
833 channel: &channel::Model,
834 user_id: UserId,
835 tx: &DatabaseTransaction,
836 ) -> Result<Option<channel_member::Model>> {
837 let row = channel_member::Entity::find()
838 .filter(channel_member::Column::ChannelId.eq(channel.root_id()))
839 .filter(channel_member::Column::UserId.eq(user_id))
840 .filter(channel_member::Column::Accepted.eq(false))
841 .one(tx)
842 .await?;
843
844 Ok(row)
845 }
846
847 /// Returns the role for a user in the given channel.
848 pub async fn channel_role_for_user(
849 &self,
850 channel: &channel::Model,
851 user_id: UserId,
852 tx: &DatabaseTransaction,
853 ) -> Result<Option<ChannelRole>> {
854 let membership = channel_member::Entity::find()
855 .filter(
856 channel_member::Column::ChannelId
857 .eq(channel.root_id())
858 .and(channel_member::Column::UserId.eq(user_id))
859 .and(channel_member::Column::Accepted.eq(true)),
860 )
861 .one(tx)
862 .await?;
863
864 let Some(membership) = membership else {
865 return Ok(None);
866 };
867
868 if !membership.role.can_see_channel(channel.visibility) {
869 return Ok(None);
870 }
871
872 Ok(Some(membership.role))
873 }
874
875 // Get the descendants of the given set if channels, ordered by their
876 // path.
877 pub(crate) async fn get_channel_descendants_excluding_self(
878 &self,
879 channels: impl IntoIterator<Item = &channel::Model>,
880 tx: &DatabaseTransaction,
881 ) -> Result<Vec<channel::Model>> {
882 let mut filter = Condition::any();
883 for channel in channels.into_iter() {
884 filter = filter.add(channel::Column::ParentPath.like(channel.descendant_path_filter()));
885 }
886
887 if filter.is_empty() {
888 return Ok(vec![]);
889 }
890
891 Ok(channel::Entity::find()
892 .filter(filter)
893 .order_by_asc(Expr::cust("parent_path || id || '/'"))
894 .all(tx)
895 .await?)
896 }
897
898 /// Returns the channel with the given ID.
899 pub async fn get_channel(&self, channel_id: ChannelId, user_id: UserId) -> Result<Channel> {
900 self.transaction(|tx| async move {
901 let channel = self.get_channel_internal(channel_id, &tx).await?;
902 self.check_user_is_channel_participant(&channel, user_id, &tx)
903 .await?;
904
905 Ok(Channel::from_model(channel))
906 })
907 .await
908 }
909
910 pub(crate) async fn get_channel_internal(
911 &self,
912 channel_id: ChannelId,
913 tx: &DatabaseTransaction,
914 ) -> Result<channel::Model> {
915 Ok(channel::Entity::find_by_id(channel_id)
916 .one(tx)
917 .await?
918 .ok_or_else(|| proto::ErrorCode::NoSuchChannel.anyhow())?)
919 }
920
921 pub(crate) async fn get_or_create_channel_room(
922 &self,
923 channel_id: ChannelId,
924 live_kit_room: &str,
925 tx: &DatabaseTransaction,
926 ) -> Result<RoomId> {
927 let room = room::Entity::find()
928 .filter(room::Column::ChannelId.eq(channel_id))
929 .one(tx)
930 .await?;
931
932 let room_id = if let Some(room) = room {
933 room.id
934 } else {
935 let result = room::Entity::insert(room::ActiveModel {
936 channel_id: ActiveValue::Set(Some(channel_id)),
937 live_kit_room: ActiveValue::Set(live_kit_room.to_string()),
938 ..Default::default()
939 })
940 .exec(tx)
941 .await?;
942
943 result.last_insert_id
944 };
945
946 Ok(room_id)
947 }
948
949 /// Move a channel from one parent to another
950 pub async fn move_channel(
951 &self,
952 channel_id: ChannelId,
953 new_parent_id: ChannelId,
954 admin_id: UserId,
955 ) -> Result<(ChannelId, Vec<Channel>)> {
956 self.transaction(|tx| async move {
957 let channel = self.get_channel_internal(channel_id, &tx).await?;
958 self.check_user_is_channel_admin(&channel, admin_id, &tx)
959 .await?;
960 let new_parent = self.get_channel_internal(new_parent_id, &tx).await?;
961
962 if new_parent.root_id() != channel.root_id() {
963 Err(anyhow!(ErrorCode::WrongMoveTarget))?;
964 }
965
966 if new_parent
967 .ancestors_including_self()
968 .any(|id| id == channel.id)
969 {
970 Err(anyhow!(ErrorCode::CircularNesting))?;
971 }
972
973 if channel.visibility == ChannelVisibility::Public
974 && new_parent.visibility != ChannelVisibility::Public
975 {
976 Err(anyhow!(ErrorCode::BadPublicNesting))?;
977 }
978
979 let root_id = channel.root_id();
980 let old_path = format!("{}{}/", channel.parent_path, channel.id);
981 let new_path = format!("{}{}/", new_parent.path(), channel.id);
982
983 let mut model = channel.into_active_model();
984 model.parent_path = ActiveValue::Set(new_parent.path());
985 let channel = model.update(&*tx).await?;
986
987 let descendent_ids =
988 ChannelId::find_by_statement::<QueryIds>(Statement::from_sql_and_values(
989 self.pool.get_database_backend(),
990 "
991 UPDATE channels SET parent_path = REPLACE(parent_path, $1, $2)
992 WHERE parent_path LIKE $3 || '%'
993 RETURNING id
994 ",
995 [old_path.clone().into(), new_path.into(), old_path.into()],
996 ))
997 .all(&*tx)
998 .await?;
999
1000 let all_moved_ids = Some(channel.id).into_iter().chain(descendent_ids);
1001
1002 let channels = channel::Entity::find()
1003 .filter(channel::Column::Id.is_in(all_moved_ids))
1004 .all(&*tx)
1005 .await?
1006 .into_iter()
1007 .map(|c| Channel::from_model(c))
1008 .collect::<Vec<_>>();
1009
1010 Ok((root_id, channels))
1011 })
1012 .await
1013 }
1014}
1015
1016#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
1017enum QueryIds {
1018 Id,
1019}
1020
1021#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
1022enum QueryUserIds {
1023 UserId,
1024}