9 use actix_web::web::Data;
11 use lemmy_apub::ActorType;
14 comment_view::CommentQueryBuilder,
17 diesel_option_overwrite,
30 use lemmy_structs::{blocking, community::*};
32 apub::{generate_actor_keypair, make_apub_endpoint, EndpointType},
34 utils::{check_slurs, check_slurs_opt, is_valid_community_name, naive_from_unix},
39 use lemmy_websocket::{
40 messages::{GetCommunityUsersOnline, JoinCommunityRoom, JoinModRoom, SendCommunityRoomMessage},
44 use std::str::FromStr;
46 #[async_trait::async_trait(?Send)]
47 impl Perform for GetCommunity {
48 type Response = GetCommunityResponse;
52 context: &Data<LemmyContext>,
53 _websocket_id: Option<ConnectionId>,
54 ) -> Result<GetCommunityResponse, LemmyError> {
55 let data: &GetCommunity = &self;
56 let user = get_user_from_jwt_opt(&data.auth, context.pool()).await?;
57 let user_id = user.map(|u| u.id);
59 let name = data.name.to_owned().unwrap_or_else(|| "main".to_string());
60 let community = match data.id {
61 Some(id) => blocking(context.pool(), move |conn| Community::read(conn, id)).await??,
62 None => match blocking(context.pool(), move |conn| {
63 Community::read_from_name(conn, &name)
67 Ok(community) => community,
68 Err(_e) => return Err(APIError::err("couldnt_find_community").into()),
72 let community_id = community.id;
73 let community_view = match blocking(context.pool(), move |conn| {
74 CommunityView::read(conn, community_id, user_id)
78 Ok(community) => community,
79 Err(_e) => return Err(APIError::err("couldnt_find_community").into()),
82 let community_id = community.id;
83 let moderators: Vec<CommunityModeratorView> = match blocking(context.pool(), move |conn| {
84 CommunityModeratorView::for_community(conn, community_id)
88 Ok(moderators) => moderators,
89 Err(_e) => return Err(APIError::err("couldnt_find_community").into()),
94 .send(GetCommunityUsersOnline { community_id })
98 let res = GetCommunityResponse {
99 community: community_view,
109 #[async_trait::async_trait(?Send)]
110 impl Perform for CreateCommunity {
111 type Response = CommunityResponse;
115 context: &Data<LemmyContext>,
116 _websocket_id: Option<ConnectionId>,
117 ) -> Result<CommunityResponse, LemmyError> {
118 let data: &CreateCommunity = &self;
119 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
121 check_slurs(&data.name)?;
122 check_slurs(&data.title)?;
123 check_slurs_opt(&data.description)?;
125 if !is_valid_community_name(&data.name) {
126 return Err(APIError::err("invalid_community_name").into());
129 // Double check for duplicate community actor_ids
130 let actor_id = make_apub_endpoint(EndpointType::Community, &data.name).to_string();
131 let actor_id_cloned = actor_id.to_owned();
132 let community_dupe = blocking(context.pool(), move |conn| {
133 Community::read_from_apub_id(conn, &actor_id_cloned)
136 if community_dupe.is_ok() {
137 return Err(APIError::err("community_already_exists").into());
140 // Check to make sure the icon and banners are urls
141 let icon = diesel_option_overwrite(&data.icon);
142 let banner = diesel_option_overwrite(&data.banner);
144 check_optional_url(&icon)?;
145 check_optional_url(&banner)?;
147 // When you create a community, make sure the user becomes a moderator and a follower
148 let keypair = generate_actor_keypair()?;
150 let community_form = CommunityForm {
151 name: data.name.to_owned(),
152 title: data.title.to_owned(),
153 description: data.description.to_owned(),
156 category_id: data.category_id,
162 actor_id: Some(actor_id),
164 private_key: Some(keypair.private_key),
165 public_key: Some(keypair.public_key),
166 last_refreshed_at: None,
170 let inserted_community = match blocking(context.pool(), move |conn| {
171 Community::create(conn, &community_form)
175 Ok(community) => community,
176 Err(_e) => return Err(APIError::err("community_already_exists").into()),
179 let community_moderator_form = CommunityModeratorForm {
180 community_id: inserted_community.id,
184 let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
185 if blocking(context.pool(), join).await?.is_err() {
186 return Err(APIError::err("community_moderator_already_exists").into());
189 let community_follower_form = CommunityFollowerForm {
190 community_id: inserted_community.id,
195 let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
196 if blocking(context.pool(), follow).await?.is_err() {
197 return Err(APIError::err("community_follower_already_exists").into());
200 let user_id = user.id;
201 let community_view = blocking(context.pool(), move |conn| {
202 CommunityView::read(conn, inserted_community.id, Some(user_id))
206 Ok(CommunityResponse {
207 community: community_view,
212 #[async_trait::async_trait(?Send)]
213 impl Perform for EditCommunity {
214 type Response = CommunityResponse;
218 context: &Data<LemmyContext>,
219 websocket_id: Option<ConnectionId>,
220 ) -> Result<CommunityResponse, LemmyError> {
221 let data: &EditCommunity = &self;
222 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
224 check_slurs(&data.title)?;
225 check_slurs_opt(&data.description)?;
227 // Verify its a mod (only mods can edit it)
228 let edit_id = data.edit_id;
229 let mods: Vec<i32> = blocking(context.pool(), move |conn| {
230 CommunityModeratorView::for_community(conn, edit_id)
231 .map(|v| v.into_iter().map(|m| m.user_id).collect())
234 if !mods.contains(&user.id) {
235 return Err(APIError::err("not_a_moderator").into());
238 let edit_id = data.edit_id;
240 blocking(context.pool(), move |conn| Community::read(conn, edit_id)).await??;
242 let icon = diesel_option_overwrite(&data.icon);
243 let banner = diesel_option_overwrite(&data.banner);
245 check_optional_url(&icon)?;
246 check_optional_url(&banner)?;
248 let community_form = CommunityForm {
249 name: read_community.name,
250 title: data.title.to_owned(),
251 description: data.description.to_owned(),
254 category_id: data.category_id.to_owned(),
255 creator_id: read_community.creator_id,
256 removed: Some(read_community.removed),
257 deleted: Some(read_community.deleted),
259 updated: Some(naive_now()),
260 actor_id: Some(read_community.actor_id),
261 local: read_community.local,
262 private_key: read_community.private_key,
263 public_key: read_community.public_key,
264 last_refreshed_at: None,
268 let edit_id = data.edit_id;
269 match blocking(context.pool(), move |conn| {
270 Community::update(conn, edit_id, &community_form)
274 Ok(community) => community,
275 Err(_e) => return Err(APIError::err("couldnt_update_community").into()),
278 // TODO there needs to be some kind of an apub update
279 // process for communities and users
281 let edit_id = data.edit_id;
282 let user_id = user.id;
283 let community_view = blocking(context.pool(), move |conn| {
284 CommunityView::read(conn, edit_id, Some(user_id))
288 let res = CommunityResponse {
289 community: community_view,
292 send_community_websocket(&res, context, websocket_id, UserOperation::EditCommunity);
298 #[async_trait::async_trait(?Send)]
299 impl Perform for DeleteCommunity {
300 type Response = CommunityResponse;
304 context: &Data<LemmyContext>,
305 websocket_id: Option<ConnectionId>,
306 ) -> Result<CommunityResponse, LemmyError> {
307 let data: &DeleteCommunity = &self;
308 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
310 // Verify its the creator (only a creator can delete the community)
311 let edit_id = data.edit_id;
313 blocking(context.pool(), move |conn| Community::read(conn, edit_id)).await??;
314 if read_community.creator_id != user.id {
315 return Err(APIError::err("no_community_edit_allowed").into());
319 let edit_id = data.edit_id;
320 let deleted = data.deleted;
321 let updated_community = match blocking(context.pool(), move |conn| {
322 Community::update_deleted(conn, edit_id, deleted)
326 Ok(community) => community,
327 Err(_e) => return Err(APIError::err("couldnt_update_community").into()),
330 // Send apub messages
332 updated_community.send_delete(context).await?;
334 updated_community.send_undo_delete(context).await?;
337 let edit_id = data.edit_id;
338 let user_id = user.id;
339 let community_view = blocking(context.pool(), move |conn| {
340 CommunityView::read(conn, edit_id, Some(user_id))
344 let res = CommunityResponse {
345 community: community_view,
348 send_community_websocket(&res, context, websocket_id, UserOperation::DeleteCommunity);
354 #[async_trait::async_trait(?Send)]
355 impl Perform for RemoveCommunity {
356 type Response = CommunityResponse;
360 context: &Data<LemmyContext>,
361 websocket_id: Option<ConnectionId>,
362 ) -> Result<CommunityResponse, LemmyError> {
363 let data: &RemoveCommunity = &self;
364 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
366 // Verify its an admin (only an admin can remove a community)
367 is_admin(context.pool(), user.id).await?;
370 let edit_id = data.edit_id;
371 let removed = data.removed;
372 let updated_community = match blocking(context.pool(), move |conn| {
373 Community::update_removed(conn, edit_id, removed)
377 Ok(community) => community,
378 Err(_e) => return Err(APIError::err("couldnt_update_community").into()),
382 let expires = match data.expires {
383 Some(time) => Some(naive_from_unix(time)),
386 let form = ModRemoveCommunityForm {
387 mod_user_id: user.id,
388 community_id: data.edit_id,
389 removed: Some(removed),
390 reason: data.reason.to_owned(),
393 blocking(context.pool(), move |conn| {
394 ModRemoveCommunity::create(conn, &form)
400 updated_community.send_remove(context).await?;
402 updated_community.send_undo_remove(context).await?;
405 let edit_id = data.edit_id;
406 let user_id = user.id;
407 let community_view = blocking(context.pool(), move |conn| {
408 CommunityView::read(conn, edit_id, Some(user_id))
412 let res = CommunityResponse {
413 community: community_view,
416 send_community_websocket(&res, context, websocket_id, UserOperation::RemoveCommunity);
422 #[async_trait::async_trait(?Send)]
423 impl Perform for ListCommunities {
424 type Response = ListCommunitiesResponse;
428 context: &Data<LemmyContext>,
429 _websocket_id: Option<ConnectionId>,
430 ) -> Result<ListCommunitiesResponse, LemmyError> {
431 let data: &ListCommunities = &self;
432 let user = get_user_from_jwt_opt(&data.auth, context.pool()).await?;
434 let user_id = match &user {
435 Some(user) => Some(user.id),
439 let show_nsfw = match &user {
440 Some(user) => user.show_nsfw,
444 let sort = SortType::from_str(&data.sort)?;
446 let page = data.page;
447 let limit = data.limit;
448 let communities = blocking(context.pool(), move |conn| {
449 CommunityQueryBuilder::create(conn)
452 .show_nsfw(show_nsfw)
460 Ok(ListCommunitiesResponse { communities })
464 #[async_trait::async_trait(?Send)]
465 impl Perform for FollowCommunity {
466 type Response = CommunityResponse;
470 context: &Data<LemmyContext>,
471 _websocket_id: Option<ConnectionId>,
472 ) -> Result<CommunityResponse, LemmyError> {
473 let data: &FollowCommunity = &self;
474 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
476 let community_id = data.community_id;
477 let community = blocking(context.pool(), move |conn| {
478 Community::read(conn, community_id)
481 let community_follower_form = CommunityFollowerForm {
482 community_id: data.community_id,
489 let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
490 if blocking(context.pool(), follow).await?.is_err() {
491 return Err(APIError::err("community_follower_already_exists").into());
495 move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
496 if blocking(context.pool(), unfollow).await?.is_err() {
497 return Err(APIError::err("community_follower_already_exists").into());
500 } else if data.follow {
501 // Dont actually add to the community followers here, because you need
502 // to wait for the accept
503 user.send_follow(&community.actor_id()?, context).await?;
505 user.send_unfollow(&community.actor_id()?, context).await?;
506 let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
507 if blocking(context.pool(), unfollow).await?.is_err() {
508 return Err(APIError::err("community_follower_already_exists").into());
512 let community_id = data.community_id;
513 let user_id = user.id;
514 let mut community_view = blocking(context.pool(), move |conn| {
515 CommunityView::read(conn, community_id, Some(user_id))
519 // TODO: this needs to return a "pending" state, until Accept is received from the remote server
520 // For now, just assume that remote follows are accepted.
521 // Otherwise, the subscribed will be null
522 if !community.local {
523 community_view.subscribed = Some(data.follow);
526 Ok(CommunityResponse {
527 community: community_view,
532 #[async_trait::async_trait(?Send)]
533 impl Perform for GetFollowedCommunities {
534 type Response = GetFollowedCommunitiesResponse;
538 context: &Data<LemmyContext>,
539 _websocket_id: Option<ConnectionId>,
540 ) -> Result<GetFollowedCommunitiesResponse, LemmyError> {
541 let data: &GetFollowedCommunities = &self;
542 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
544 let user_id = user.id;
545 let communities = match blocking(context.pool(), move |conn| {
546 CommunityFollowerView::for_user(conn, user_id)
550 Ok(communities) => communities,
551 _ => return Err(APIError::err("system_err_login").into()),
555 Ok(GetFollowedCommunitiesResponse { communities })
559 #[async_trait::async_trait(?Send)]
560 impl Perform for BanFromCommunity {
561 type Response = BanFromCommunityResponse;
565 context: &Data<LemmyContext>,
566 websocket_id: Option<ConnectionId>,
567 ) -> Result<BanFromCommunityResponse, LemmyError> {
568 let data: &BanFromCommunity = &self;
569 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
571 let community_id = data.community_id;
572 let banned_user_id = data.user_id;
574 // Verify that only mods or admins can ban
575 is_mod_or_admin(context.pool(), user.id, community_id).await?;
577 let community_user_ban_form = CommunityUserBanForm {
578 community_id: data.community_id,
579 user_id: data.user_id,
583 let ban = move |conn: &'_ _| CommunityUserBan::ban(conn, &community_user_ban_form);
584 if blocking(context.pool(), ban).await?.is_err() {
585 return Err(APIError::err("community_user_already_banned").into());
588 let unban = move |conn: &'_ _| CommunityUserBan::unban(conn, &community_user_ban_form);
589 if blocking(context.pool(), unban).await?.is_err() {
590 return Err(APIError::err("community_user_already_banned").into());
594 // Remove/Restore their data if that's desired
595 if let Some(remove_data) = data.remove_data {
597 blocking(context.pool(), move |conn: &'_ _| {
598 Post::update_removed_for_creator(conn, banned_user_id, Some(community_id), remove_data)
603 // Diesel doesn't allow updates with joins, so this has to be a loop
604 let comments = blocking(context.pool(), move |conn| {
605 CommentQueryBuilder::create(conn)
606 .for_creator_id(banned_user_id)
607 .for_community_id(community_id)
608 .limit(std::i64::MAX)
613 for comment in &comments {
614 let comment_id = comment.id;
615 blocking(context.pool(), move |conn: &'_ _| {
616 Comment::update_removed(conn, comment_id, remove_data)
623 // TODO eventually do correct expires
624 let expires = match data.expires {
625 Some(time) => Some(naive_from_unix(time)),
629 let form = ModBanFromCommunityForm {
630 mod_user_id: user.id,
631 other_user_id: data.user_id,
632 community_id: data.community_id,
633 reason: data.reason.to_owned(),
634 banned: Some(data.ban),
637 blocking(context.pool(), move |conn| {
638 ModBanFromCommunity::create(conn, &form)
642 let user_id = data.user_id;
643 let user_view = blocking(context.pool(), move |conn| {
644 UserView::get_user_secure(conn, user_id)
648 let res = BanFromCommunityResponse {
653 context.chat_server().do_send(SendCommunityRoomMessage {
654 op: UserOperation::BanFromCommunity,
655 response: res.clone(),
664 #[async_trait::async_trait(?Send)]
665 impl Perform for AddModToCommunity {
666 type Response = AddModToCommunityResponse;
670 context: &Data<LemmyContext>,
671 websocket_id: Option<ConnectionId>,
672 ) -> Result<AddModToCommunityResponse, LemmyError> {
673 let data: &AddModToCommunity = &self;
674 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
676 let community_moderator_form = CommunityModeratorForm {
677 community_id: data.community_id,
678 user_id: data.user_id,
681 let community_id = data.community_id;
683 // Verify that only mods or admins can add mod
684 is_mod_or_admin(context.pool(), user.id, community_id).await?;
687 let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
688 if blocking(context.pool(), join).await?.is_err() {
689 return Err(APIError::err("community_moderator_already_exists").into());
692 let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form);
693 if blocking(context.pool(), leave).await?.is_err() {
694 return Err(APIError::err("community_moderator_already_exists").into());
699 let form = ModAddCommunityForm {
700 mod_user_id: user.id,
701 other_user_id: data.user_id,
702 community_id: data.community_id,
703 removed: Some(!data.added),
705 blocking(context.pool(), move |conn| {
706 ModAddCommunity::create(conn, &form)
710 let community_id = data.community_id;
711 let moderators = blocking(context.pool(), move |conn| {
712 CommunityModeratorView::for_community(conn, community_id)
716 let res = AddModToCommunityResponse { moderators };
718 context.chat_server().do_send(SendCommunityRoomMessage {
719 op: UserOperation::AddModToCommunity,
720 response: res.clone(),
729 #[async_trait::async_trait(?Send)]
730 impl Perform for TransferCommunity {
731 type Response = GetCommunityResponse;
735 context: &Data<LemmyContext>,
736 _websocket_id: Option<ConnectionId>,
737 ) -> Result<GetCommunityResponse, LemmyError> {
738 let data: &TransferCommunity = &self;
739 let user = get_user_from_jwt(&data.auth, context.pool()).await?;
741 let community_id = data.community_id;
742 let read_community = blocking(context.pool(), move |conn| {
743 Community::read(conn, community_id)
747 let site_creator_id = blocking(context.pool(), move |conn| {
748 Site::read(conn, 1).map(|s| s.creator_id)
752 let mut admins = blocking(context.pool(), move |conn| UserView::admins(conn)).await??;
754 let creator_index = admins
756 .position(|r| r.id == site_creator_id)
757 .context(location_info!())?;
758 let creator_user = admins.remove(creator_index);
759 admins.insert(0, creator_user);
761 // Make sure user is the creator, or an admin
762 if user.id != read_community.creator_id && !admins.iter().map(|a| a.id).any(|x| x == user.id) {
763 return Err(APIError::err("not_an_admin").into());
766 let community_id = data.community_id;
767 let new_creator = data.user_id;
768 let update = move |conn: &'_ _| Community::update_creator(conn, community_id, new_creator);
769 if blocking(context.pool(), update).await?.is_err() {
770 return Err(APIError::err("couldnt_update_community").into());
773 // You also have to re-do the community_moderator table, reordering it.
774 let community_id = data.community_id;
775 let mut community_mods = blocking(context.pool(), move |conn| {
776 CommunityModeratorView::for_community(conn, community_id)
779 let creator_index = community_mods
781 .position(|r| r.user_id == data.user_id)
782 .context(location_info!())?;
783 let creator_user = community_mods.remove(creator_index);
784 community_mods.insert(0, creator_user);
786 let community_id = data.community_id;
787 blocking(context.pool(), move |conn| {
788 CommunityModerator::delete_for_community(conn, community_id)
792 // TODO: this should probably be a bulk operation
793 for cmod in &community_mods {
794 let community_moderator_form = CommunityModeratorForm {
795 community_id: cmod.community_id,
796 user_id: cmod.user_id,
799 let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
800 if blocking(context.pool(), join).await?.is_err() {
801 return Err(APIError::err("community_moderator_already_exists").into());
806 let form = ModAddCommunityForm {
807 mod_user_id: user.id,
808 other_user_id: data.user_id,
809 community_id: data.community_id,
810 removed: Some(false),
812 blocking(context.pool(), move |conn| {
813 ModAddCommunity::create(conn, &form)
817 let community_id = data.community_id;
818 let user_id = user.id;
819 let community_view = match blocking(context.pool(), move |conn| {
820 CommunityView::read(conn, community_id, Some(user_id))
824 Ok(community) => community,
825 Err(_e) => return Err(APIError::err("couldnt_find_community").into()),
828 let community_id = data.community_id;
829 let moderators = match blocking(context.pool(), move |conn| {
830 CommunityModeratorView::for_community(conn, community_id)
834 Ok(moderators) => moderators,
835 Err(_e) => return Err(APIError::err("couldnt_find_community").into()),
839 Ok(GetCommunityResponse {
840 community: community_view,
847 fn send_community_websocket(
848 res: &CommunityResponse,
849 context: &Data<LemmyContext>,
850 websocket_id: Option<ConnectionId>,
853 // Strip out the user id and subscribed when sending to others
854 let mut res_sent = res.clone();
855 res_sent.community.user_id = None;
856 res_sent.community.subscribed = None;
858 context.chat_server().do_send(SendCommunityRoomMessage {
861 community_id: res.community.id,
866 #[async_trait::async_trait(?Send)]
867 impl Perform for CommunityJoin {
868 type Response = CommunityJoinResponse;
872 context: &Data<LemmyContext>,
873 websocket_id: Option<ConnectionId>,
874 ) -> Result<CommunityJoinResponse, LemmyError> {
875 let data: &CommunityJoin = &self;
877 if let Some(ws_id) = websocket_id {
878 context.chat_server().do_send(JoinCommunityRoom {
879 community_id: data.community_id,
884 Ok(CommunityJoinResponse { joined: true })
888 #[async_trait::async_trait(?Send)]
889 impl Perform for ModJoin {
890 type Response = ModJoinResponse;
894 context: &Data<LemmyContext>,
895 websocket_id: Option<ConnectionId>,
896 ) -> Result<ModJoinResponse, LemmyError> {
897 let data: &ModJoin = &self;
899 if let Some(ws_id) = websocket_id {
900 context.chat_server().do_send(JoinModRoom {
901 community_id: data.community_id,
906 Ok(ModJoinResponse { joined: true })