3 get_local_user_view_from_jwt,
4 get_local_user_view_from_jwt_opt,
9 use actix_web::web::Data;
11 use lemmy_api_structs::{blocking, community::*};
13 generate_apub_endpoint,
14 generate_followers_url,
16 generate_shared_inbox_url,
20 use lemmy_db_queries::{
21 diesel_option_overwrite_to_url,
24 community::{CommunityModerator_, Community_},
35 use lemmy_db_schema::{
37 source::{comment::Comment, community::*, moderator::*, post::Post, site::*},
39 use lemmy_db_views::comment_view::CommentQueryBuilder;
40 use lemmy_db_views_actor::{
41 community_follower_view::CommunityFollowerView,
42 community_moderator_view::CommunityModeratorView,
43 community_view::{CommunityQueryBuilder, CommunityView},
44 person_view::PersonViewSafe,
47 apub::generate_actor_keypair,
49 utils::{check_slurs, check_slurs_opt, is_valid_community_name, naive_from_unix},
54 use lemmy_websocket::{
55 messages::{GetCommunityUsersOnline, SendCommunityRoomMessage},
59 use std::str::FromStr;
61 #[async_trait::async_trait(?Send)]
62 impl Perform for GetCommunity {
63 type Response = GetCommunityResponse;
67 context: &Data<LemmyContext>,
68 _websocket_id: Option<ConnectionId>,
69 ) -> Result<GetCommunityResponse, LemmyError> {
70 let data: &GetCommunity = &self;
71 let local_user_view = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?;
72 let person_id = local_user_view.map(|u| u.person.id);
74 let community_id = match data.id {
77 let name = data.name.to_owned().unwrap_or_else(|| "main".to_string());
78 match blocking(context.pool(), move |conn| {
79 Community::read_from_name(conn, &name)
83 Ok(community) => community,
84 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
90 let community_view = match blocking(context.pool(), move |conn| {
91 CommunityView::read(conn, community_id, person_id)
95 Ok(community) => community,
96 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
99 let moderators: Vec<CommunityModeratorView> = match blocking(context.pool(), move |conn| {
100 CommunityModeratorView::for_community(conn, community_id)
104 Ok(moderators) => moderators,
105 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
110 .send(GetCommunityUsersOnline { community_id })
114 let res = GetCommunityResponse {
125 #[async_trait::async_trait(?Send)]
126 impl Perform for CreateCommunity {
127 type Response = CommunityResponse;
131 context: &Data<LemmyContext>,
132 _websocket_id: Option<ConnectionId>,
133 ) -> Result<CommunityResponse, LemmyError> {
134 let data: &CreateCommunity = &self;
135 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
137 check_slurs(&data.name)?;
138 check_slurs(&data.title)?;
139 check_slurs_opt(&data.description)?;
141 if !is_valid_community_name(&data.name) {
142 return Err(ApiError::err("invalid_community_name").into());
145 // Double check for duplicate community actor_ids
146 let community_actor_id = generate_apub_endpoint(EndpointType::Community, &data.name)?;
147 let actor_id_cloned = community_actor_id.to_owned();
148 let community_dupe = blocking(context.pool(), move |conn| {
149 Community::read_from_apub_id(conn, &actor_id_cloned)
152 if community_dupe.is_ok() {
153 return Err(ApiError::err("community_already_exists").into());
156 // Check to make sure the icon and banners are urls
157 let icon = diesel_option_overwrite_to_url(&data.icon)?;
158 let banner = diesel_option_overwrite_to_url(&data.banner)?;
160 // When you create a community, make sure the user becomes a moderator and a follower
161 let keypair = generate_actor_keypair()?;
163 let community_form = CommunityForm {
164 name: data.name.to_owned(),
165 title: data.title.to_owned(),
166 description: data.description.to_owned(),
169 creator_id: local_user_view.person.id,
174 actor_id: Some(community_actor_id.to_owned()),
176 private_key: Some(keypair.private_key),
177 public_key: Some(keypair.public_key),
178 last_refreshed_at: None,
180 followers_url: Some(generate_followers_url(&community_actor_id)?),
181 inbox_url: Some(generate_inbox_url(&community_actor_id)?),
182 shared_inbox_url: Some(Some(generate_shared_inbox_url(&community_actor_id)?)),
185 let inserted_community = match blocking(context.pool(), move |conn| {
186 Community::create(conn, &community_form)
190 Ok(community) => community,
191 Err(_e) => return Err(ApiError::err("community_already_exists").into()),
194 // The community creator becomes a moderator
195 let community_moderator_form = CommunityModeratorForm {
196 community_id: inserted_community.id,
197 person_id: local_user_view.person.id,
200 let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
201 if blocking(context.pool(), join).await?.is_err() {
202 return Err(ApiError::err("community_moderator_already_exists").into());
205 // Follow your own community
206 let community_follower_form = CommunityFollowerForm {
207 community_id: inserted_community.id,
208 person_id: local_user_view.person.id,
212 let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
213 if blocking(context.pool(), follow).await?.is_err() {
214 return Err(ApiError::err("community_follower_already_exists").into());
217 let person_id = local_user_view.person.id;
218 let community_view = blocking(context.pool(), move |conn| {
219 CommunityView::read(conn, inserted_community.id, Some(person_id))
223 Ok(CommunityResponse { community_view })
227 #[async_trait::async_trait(?Send)]
228 impl Perform for EditCommunity {
229 type Response = CommunityResponse;
233 context: &Data<LemmyContext>,
234 websocket_id: Option<ConnectionId>,
235 ) -> Result<CommunityResponse, LemmyError> {
236 let data: &EditCommunity = &self;
237 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
239 check_slurs(&data.title)?;
240 check_slurs_opt(&data.description)?;
242 // Verify its a mod (only mods can edit it)
243 let community_id = data.community_id;
244 let mods: Vec<i32> = blocking(context.pool(), move |conn| {
245 CommunityModeratorView::for_community(conn, community_id)
246 .map(|v| v.into_iter().map(|m| m.moderator.id).collect())
249 if !mods.contains(&local_user_view.person.id) {
250 return Err(ApiError::err("not_a_moderator").into());
253 let community_id = data.community_id;
254 let read_community = blocking(context.pool(), move |conn| {
255 Community::read(conn, community_id)
259 let icon = diesel_option_overwrite_to_url(&data.icon)?;
260 let banner = diesel_option_overwrite_to_url(&data.banner)?;
262 let community_form = CommunityForm {
263 name: read_community.name,
264 title: data.title.to_owned(),
265 description: data.description.to_owned(),
268 creator_id: read_community.creator_id,
269 removed: Some(read_community.removed),
270 deleted: Some(read_community.deleted),
272 updated: Some(naive_now()),
273 actor_id: Some(read_community.actor_id),
274 local: read_community.local,
275 private_key: read_community.private_key,
276 public_key: read_community.public_key,
277 last_refreshed_at: None,
281 shared_inbox_url: None,
284 let community_id = data.community_id;
285 match blocking(context.pool(), move |conn| {
286 Community::update(conn, community_id, &community_form)
290 Ok(community) => community,
291 Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
294 // TODO there needs to be some kind of an apub update
295 // process for communities and users
297 let community_id = data.community_id;
298 let person_id = local_user_view.person.id;
299 let community_view = blocking(context.pool(), move |conn| {
300 CommunityView::read(conn, community_id, Some(person_id))
304 let res = CommunityResponse { community_view };
306 send_community_websocket(&res, context, websocket_id, UserOperation::EditCommunity);
312 #[async_trait::async_trait(?Send)]
313 impl Perform for DeleteCommunity {
314 type Response = CommunityResponse;
318 context: &Data<LemmyContext>,
319 websocket_id: Option<ConnectionId>,
320 ) -> Result<CommunityResponse, LemmyError> {
321 let data: &DeleteCommunity = &self;
322 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
324 // Verify its the creator (only a creator can delete the community)
325 let community_id = data.community_id;
326 let read_community = blocking(context.pool(), move |conn| {
327 Community::read(conn, community_id)
330 if read_community.creator_id != local_user_view.person.id {
331 return Err(ApiError::err("no_community_edit_allowed").into());
335 let community_id = data.community_id;
336 let deleted = data.deleted;
337 let updated_community = match blocking(context.pool(), move |conn| {
338 Community::update_deleted(conn, community_id, deleted)
342 Ok(community) => community,
343 Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
346 // Send apub messages
348 updated_community.send_delete(context).await?;
350 updated_community.send_undo_delete(context).await?;
353 let community_id = data.community_id;
354 let person_id = local_user_view.person.id;
355 let community_view = blocking(context.pool(), move |conn| {
356 CommunityView::read(conn, community_id, Some(person_id))
360 let res = CommunityResponse { community_view };
362 send_community_websocket(&res, context, websocket_id, UserOperation::DeleteCommunity);
368 #[async_trait::async_trait(?Send)]
369 impl Perform for RemoveCommunity {
370 type Response = CommunityResponse;
374 context: &Data<LemmyContext>,
375 websocket_id: Option<ConnectionId>,
376 ) -> Result<CommunityResponse, LemmyError> {
377 let data: &RemoveCommunity = &self;
378 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
380 // Verify its an admin (only an admin can remove a community)
381 is_admin(&local_user_view)?;
384 let community_id = data.community_id;
385 let removed = data.removed;
386 let updated_community = match blocking(context.pool(), move |conn| {
387 Community::update_removed(conn, community_id, removed)
391 Ok(community) => community,
392 Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
396 let expires = match data.expires {
397 Some(time) => Some(naive_from_unix(time)),
400 let form = ModRemoveCommunityForm {
401 mod_person_id: local_user_view.person.id,
402 community_id: data.community_id,
403 removed: Some(removed),
404 reason: data.reason.to_owned(),
407 blocking(context.pool(), move |conn| {
408 ModRemoveCommunity::create(conn, &form)
414 updated_community.send_remove(context).await?;
416 updated_community.send_undo_remove(context).await?;
419 let community_id = data.community_id;
420 let person_id = local_user_view.person.id;
421 let community_view = blocking(context.pool(), move |conn| {
422 CommunityView::read(conn, community_id, Some(person_id))
426 let res = CommunityResponse { community_view };
428 send_community_websocket(&res, context, websocket_id, UserOperation::RemoveCommunity);
434 #[async_trait::async_trait(?Send)]
435 impl Perform for ListCommunities {
436 type Response = ListCommunitiesResponse;
440 context: &Data<LemmyContext>,
441 _websocket_id: Option<ConnectionId>,
442 ) -> Result<ListCommunitiesResponse, LemmyError> {
443 let data: &ListCommunities = &self;
444 let local_user_view = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?;
446 let person_id = match &local_user_view {
447 Some(uv) => Some(uv.person.id),
451 // Don't show NSFW by default
452 let show_nsfw = match &local_user_view {
453 Some(uv) => uv.local_user.show_nsfw,
457 let type_ = ListingType::from_str(&data.type_)?;
458 let sort = SortType::from_str(&data.sort)?;
460 let page = data.page;
461 let limit = data.limit;
462 let communities = blocking(context.pool(), move |conn| {
463 CommunityQueryBuilder::create(conn)
464 .listing_type(&type_)
466 .show_nsfw(show_nsfw)
467 .my_person_id(person_id)
475 Ok(ListCommunitiesResponse { communities })
479 #[async_trait::async_trait(?Send)]
480 impl Perform for FollowCommunity {
481 type Response = CommunityResponse;
485 context: &Data<LemmyContext>,
486 _websocket_id: Option<ConnectionId>,
487 ) -> Result<CommunityResponse, LemmyError> {
488 let data: &FollowCommunity = &self;
489 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
491 let community_id = data.community_id;
492 let community = blocking(context.pool(), move |conn| {
493 Community::read(conn, community_id)
496 let community_follower_form = CommunityFollowerForm {
497 community_id: data.community_id,
498 person_id: local_user_view.person.id,
504 check_community_ban(local_user_view.person.id, community_id, context.pool()).await?;
506 let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
507 if blocking(context.pool(), follow).await?.is_err() {
508 return Err(ApiError::err("community_follower_already_exists").into());
512 move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
513 if blocking(context.pool(), unfollow).await?.is_err() {
514 return Err(ApiError::err("community_follower_already_exists").into());
517 } else if data.follow {
518 // Dont actually add to the community followers here, because you need
519 // to wait for the accept
520 local_user_view.person.send_follow(&community.actor_id(), context).await?;
522 local_user_view.person.send_unfollow(&community.actor_id(), context).await?;
523 let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
524 if blocking(context.pool(), unfollow).await?.is_err() {
525 return Err(ApiError::err("community_follower_already_exists").into());
529 let community_id = data.community_id;
530 let person_id = local_user_view.person.id;
531 let mut community_view = blocking(context.pool(), move |conn| {
532 CommunityView::read(conn, community_id, Some(person_id))
536 // TODO: this needs to return a "pending" state, until Accept is received from the remote server
537 // For now, just assume that remote follows are accepted.
538 // Otherwise, the subscribed will be null
539 if !community.local {
540 community_view.subscribed = data.follow;
543 Ok(CommunityResponse { community_view })
547 #[async_trait::async_trait(?Send)]
548 impl Perform for GetFollowedCommunities {
549 type Response = GetFollowedCommunitiesResponse;
553 context: &Data<LemmyContext>,
554 _websocket_id: Option<ConnectionId>,
555 ) -> Result<GetFollowedCommunitiesResponse, LemmyError> {
556 let data: &GetFollowedCommunities = &self;
557 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
559 let person_id = local_user_view.person.id;
560 let communities = match blocking(context.pool(), move |conn| {
561 CommunityFollowerView::for_person(conn, person_id)
565 Ok(communities) => communities,
566 _ => return Err(ApiError::err("system_err_login").into()),
570 Ok(GetFollowedCommunitiesResponse { communities })
574 #[async_trait::async_trait(?Send)]
575 impl Perform for BanFromCommunity {
576 type Response = BanFromCommunityResponse;
580 context: &Data<LemmyContext>,
581 websocket_id: Option<ConnectionId>,
582 ) -> Result<BanFromCommunityResponse, LemmyError> {
583 let data: &BanFromCommunity = &self;
584 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
586 let community_id = data.community_id;
587 let banned_person_id = data.person_id;
589 // Verify that only mods or admins can ban
590 is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
592 let community_user_ban_form = CommunityPersonBanForm {
593 community_id: data.community_id,
594 person_id: data.person_id,
598 let ban = move |conn: &'_ _| CommunityPersonBan::ban(conn, &community_user_ban_form);
599 if blocking(context.pool(), ban).await?.is_err() {
600 return Err(ApiError::err("community_user_already_banned").into());
603 // Also unsubscribe them from the community, if they are subscribed
604 let community_follower_form = CommunityFollowerForm {
605 community_id: data.community_id,
606 person_id: banned_person_id,
609 blocking(context.pool(), move |conn: &'_ _| {
610 CommunityFollower::unfollow(conn, &community_follower_form)
615 let unban = move |conn: &'_ _| CommunityPersonBan::unban(conn, &community_user_ban_form);
616 if blocking(context.pool(), unban).await?.is_err() {
617 return Err(ApiError::err("community_user_already_banned").into());
621 // Remove/Restore their data if that's desired
622 if data.remove_data {
624 blocking(context.pool(), move |conn: &'_ _| {
625 Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
630 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
631 let comments = blocking(context.pool(), move |conn| {
632 CommentQueryBuilder::create(conn)
633 .creator_id(banned_person_id)
634 .community_id(community_id)
635 .limit(std::i64::MAX)
640 for comment_view in &comments {
641 let comment_id = comment_view.comment.id;
642 blocking(context.pool(), move |conn: &'_ _| {
643 Comment::update_removed(conn, comment_id, true)
650 // TODO eventually do correct expires
651 let expires = match data.expires {
652 Some(time) => Some(naive_from_unix(time)),
656 let form = ModBanFromCommunityForm {
657 mod_person_id: local_user_view.person.id,
658 other_person_id: data.person_id,
659 community_id: data.community_id,
660 reason: data.reason.to_owned(),
661 banned: Some(data.ban),
664 blocking(context.pool(), move |conn| {
665 ModBanFromCommunity::create(conn, &form)
669 let person_id = data.person_id;
670 let person_view = blocking(context.pool(), move |conn| {
671 PersonViewSafe::read(conn, person_id)
675 let res = BanFromCommunityResponse {
680 context.chat_server().do_send(SendCommunityRoomMessage {
681 op: UserOperation::BanFromCommunity,
682 response: res.clone(),
691 #[async_trait::async_trait(?Send)]
692 impl Perform for AddModToCommunity {
693 type Response = AddModToCommunityResponse;
697 context: &Data<LemmyContext>,
698 websocket_id: Option<ConnectionId>,
699 ) -> Result<AddModToCommunityResponse, LemmyError> {
700 let data: &AddModToCommunity = &self;
701 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
703 let community_moderator_form = CommunityModeratorForm {
704 community_id: data.community_id,
705 person_id: data.person_id,
708 let community_id = data.community_id;
710 // Verify that only mods or admins can add mod
711 is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
714 let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
715 if blocking(context.pool(), join).await?.is_err() {
716 return Err(ApiError::err("community_moderator_already_exists").into());
719 let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form);
720 if blocking(context.pool(), leave).await?.is_err() {
721 return Err(ApiError::err("community_moderator_already_exists").into());
726 let form = ModAddCommunityForm {
727 mod_person_id: local_user_view.person.id,
728 other_person_id: data.person_id,
729 community_id: data.community_id,
730 removed: Some(!data.added),
732 blocking(context.pool(), move |conn| {
733 ModAddCommunity::create(conn, &form)
737 let community_id = data.community_id;
738 let moderators = blocking(context.pool(), move |conn| {
739 CommunityModeratorView::for_community(conn, community_id)
743 let res = AddModToCommunityResponse { moderators };
745 context.chat_server().do_send(SendCommunityRoomMessage {
746 op: UserOperation::AddModToCommunity,
747 response: res.clone(),
756 #[async_trait::async_trait(?Send)]
757 impl Perform for TransferCommunity {
758 type Response = GetCommunityResponse;
762 context: &Data<LemmyContext>,
763 _websocket_id: Option<ConnectionId>,
764 ) -> Result<GetCommunityResponse, LemmyError> {
765 let data: &TransferCommunity = &self;
766 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
768 let community_id = data.community_id;
769 let read_community = blocking(context.pool(), move |conn| {
770 Community::read(conn, community_id)
774 let site_creator_id = blocking(context.pool(), move |conn| {
775 Site::read(conn, 1).map(|s| s.creator_id)
779 let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
781 // Making sure the creator, if an admin, is at the top
782 let creator_index = admins
784 .position(|r| r.person.id == site_creator_id)
785 .context(location_info!())?;
786 let creator_person = admins.remove(creator_index);
787 admins.insert(0, creator_person);
789 // Make sure user is the creator, or an admin
790 if local_user_view.person.id != read_community.creator_id
791 && !admins.iter().map(|a| a.person.id).any(|x| x == local_user_view.person.id)
793 return Err(ApiError::err("not_an_admin").into());
796 let community_id = data.community_id;
797 let new_creator = data.person_id;
798 let update = move |conn: &'_ _| Community::update_creator(conn, community_id, new_creator);
799 if blocking(context.pool(), update).await?.is_err() {
800 return Err(ApiError::err("couldnt_update_community").into());
803 // You also have to re-do the community_moderator table, reordering it.
804 let community_id = data.community_id;
805 let mut community_mods = blocking(context.pool(), move |conn| {
806 CommunityModeratorView::for_community(conn, community_id)
809 let creator_index = community_mods
811 .position(|r| r.moderator.id == data.person_id)
812 .context(location_info!())?;
813 let creator_person = community_mods.remove(creator_index);
814 community_mods.insert(0, creator_person);
816 let community_id = data.community_id;
817 blocking(context.pool(), move |conn| {
818 CommunityModerator::delete_for_community(conn, community_id)
822 // TODO: this should probably be a bulk operation
823 for cmod in &community_mods {
824 let community_moderator_form = CommunityModeratorForm {
825 community_id: cmod.community.id,
826 person_id: cmod.moderator.id,
829 let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
830 if blocking(context.pool(), join).await?.is_err() {
831 return Err(ApiError::err("community_moderator_already_exists").into());
836 let form = ModAddCommunityForm {
837 mod_person_id: local_user_view.person.id,
838 other_person_id: data.person_id,
839 community_id: data.community_id,
840 removed: Some(false),
842 blocking(context.pool(), move |conn| {
843 ModAddCommunity::create(conn, &form)
847 let community_id = data.community_id;
848 let person_id = local_user_view.person.id;
849 let community_view = match blocking(context.pool(), move |conn| {
850 CommunityView::read(conn, community_id, Some(person_id))
854 Ok(community) => community,
855 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
858 let community_id = data.community_id;
859 let moderators = match blocking(context.pool(), move |conn| {
860 CommunityModeratorView::for_community(conn, community_id)
864 Ok(moderators) => moderators,
865 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
869 Ok(GetCommunityResponse {
877 fn send_community_websocket(
878 res: &CommunityResponse,
879 context: &Data<LemmyContext>,
880 websocket_id: Option<ConnectionId>,
883 // Strip out the person id and subscribed when sending to others
884 let mut res_sent = res.clone();
885 res_sent.community_view.subscribed = false;
887 context.chat_server().do_send(SendCommunityRoomMessage {
890 community_id: res.community_view.community.id,