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::*},
40 use lemmy_db_views::comment_view::CommentQueryBuilder;
41 use lemmy_db_views_actor::{
42 community_follower_view::CommunityFollowerView,
43 community_moderator_view::CommunityModeratorView,
44 community_view::{CommunityQueryBuilder, CommunityView},
45 person_view::PersonViewSafe,
48 apub::generate_actor_keypair,
50 utils::{check_slurs, check_slurs_opt, is_valid_community_name, naive_from_unix},
55 use lemmy_websocket::{
56 messages::{GetCommunityUsersOnline, SendCommunityRoomMessage},
60 use std::str::FromStr;
62 #[async_trait::async_trait(?Send)]
63 impl Perform for GetCommunity {
64 type Response = GetCommunityResponse;
68 context: &Data<LemmyContext>,
69 _websocket_id: Option<ConnectionId>,
70 ) -> Result<GetCommunityResponse, LemmyError> {
71 let data: &GetCommunity = &self;
72 let local_user_view = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?;
73 let person_id = local_user_view.map(|u| u.person.id);
75 let community_id = match data.id {
78 let name = data.name.to_owned().unwrap_or_else(|| "main".to_string());
79 match blocking(context.pool(), move |conn| {
80 Community::read_from_name(conn, &name)
84 Ok(community) => community,
85 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
91 let community_view = match blocking(context.pool(), move |conn| {
92 CommunityView::read(conn, community_id, person_id)
96 Ok(community) => community,
97 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
100 let moderators: Vec<CommunityModeratorView> = match blocking(context.pool(), move |conn| {
101 CommunityModeratorView::for_community(conn, community_id)
105 Ok(moderators) => moderators,
106 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
111 .send(GetCommunityUsersOnline { community_id })
115 let res = GetCommunityResponse {
126 #[async_trait::async_trait(?Send)]
127 impl Perform for CreateCommunity {
128 type Response = CommunityResponse;
132 context: &Data<LemmyContext>,
133 _websocket_id: Option<ConnectionId>,
134 ) -> Result<CommunityResponse, LemmyError> {
135 let data: &CreateCommunity = &self;
136 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
138 check_slurs(&data.name)?;
139 check_slurs(&data.title)?;
140 check_slurs_opt(&data.description)?;
142 if !is_valid_community_name(&data.name) {
143 return Err(ApiError::err("invalid_community_name").into());
146 // Double check for duplicate community actor_ids
147 let community_actor_id = generate_apub_endpoint(EndpointType::Community, &data.name)?;
148 let actor_id_cloned = community_actor_id.to_owned();
149 let community_dupe = blocking(context.pool(), move |conn| {
150 Community::read_from_apub_id(conn, &actor_id_cloned)
153 if community_dupe.is_ok() {
154 return Err(ApiError::err("community_already_exists").into());
157 // Check to make sure the icon and banners are urls
158 let icon = diesel_option_overwrite_to_url(&data.icon)?;
159 let banner = diesel_option_overwrite_to_url(&data.banner)?;
161 // When you create a community, make sure the user becomes a moderator and a follower
162 let keypair = generate_actor_keypair()?;
164 let community_form = CommunityForm {
165 name: data.name.to_owned(),
166 title: data.title.to_owned(),
167 description: data.description.to_owned(),
170 creator_id: local_user_view.person.id,
175 actor_id: Some(community_actor_id.to_owned()),
177 private_key: Some(keypair.private_key),
178 public_key: Some(keypair.public_key),
179 last_refreshed_at: None,
181 followers_url: Some(generate_followers_url(&community_actor_id)?),
182 inbox_url: Some(generate_inbox_url(&community_actor_id)?),
183 shared_inbox_url: Some(Some(generate_shared_inbox_url(&community_actor_id)?)),
186 let inserted_community = match blocking(context.pool(), move |conn| {
187 Community::create(conn, &community_form)
191 Ok(community) => community,
192 Err(_e) => return Err(ApiError::err("community_already_exists").into()),
195 // The community creator becomes a moderator
196 let community_moderator_form = CommunityModeratorForm {
197 community_id: inserted_community.id,
198 person_id: local_user_view.person.id,
201 let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
202 if blocking(context.pool(), join).await?.is_err() {
203 return Err(ApiError::err("community_moderator_already_exists").into());
206 // Follow your own community
207 let community_follower_form = CommunityFollowerForm {
208 community_id: inserted_community.id,
209 person_id: local_user_view.person.id,
213 let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
214 if blocking(context.pool(), follow).await?.is_err() {
215 return Err(ApiError::err("community_follower_already_exists").into());
218 let person_id = local_user_view.person.id;
219 let community_view = blocking(context.pool(), move |conn| {
220 CommunityView::read(conn, inserted_community.id, Some(person_id))
224 Ok(CommunityResponse { community_view })
228 #[async_trait::async_trait(?Send)]
229 impl Perform for EditCommunity {
230 type Response = CommunityResponse;
234 context: &Data<LemmyContext>,
235 websocket_id: Option<ConnectionId>,
236 ) -> Result<CommunityResponse, LemmyError> {
237 let data: &EditCommunity = &self;
238 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
240 check_slurs(&data.title)?;
241 check_slurs_opt(&data.description)?;
243 // Verify its a mod (only mods can edit it)
244 let community_id = data.community_id;
245 let mods: Vec<PersonId> = blocking(context.pool(), move |conn| {
246 CommunityModeratorView::for_community(conn, community_id)
247 .map(|v| v.into_iter().map(|m| m.moderator.id).collect())
250 if !mods.contains(&local_user_view.person.id) {
251 return Err(ApiError::err("not_a_moderator").into());
254 let community_id = data.community_id;
255 let read_community = blocking(context.pool(), move |conn| {
256 Community::read(conn, community_id)
260 let icon = diesel_option_overwrite_to_url(&data.icon)?;
261 let banner = diesel_option_overwrite_to_url(&data.banner)?;
263 let community_form = CommunityForm {
264 name: read_community.name,
265 title: data.title.to_owned(),
266 description: data.description.to_owned(),
269 creator_id: read_community.creator_id,
270 removed: Some(read_community.removed),
271 deleted: Some(read_community.deleted),
273 updated: Some(naive_now()),
274 actor_id: Some(read_community.actor_id),
275 local: read_community.local,
276 private_key: read_community.private_key,
277 public_key: read_community.public_key,
278 last_refreshed_at: None,
282 shared_inbox_url: None,
285 let community_id = data.community_id;
286 match blocking(context.pool(), move |conn| {
287 Community::update(conn, community_id, &community_form)
291 Ok(community) => community,
292 Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
295 // TODO there needs to be some kind of an apub update
296 // process for communities and users
298 let community_id = data.community_id;
299 let person_id = local_user_view.person.id;
300 let community_view = blocking(context.pool(), move |conn| {
301 CommunityView::read(conn, community_id, Some(person_id))
305 let res = CommunityResponse { community_view };
307 send_community_websocket(&res, context, websocket_id, UserOperation::EditCommunity);
313 #[async_trait::async_trait(?Send)]
314 impl Perform for DeleteCommunity {
315 type Response = CommunityResponse;
319 context: &Data<LemmyContext>,
320 websocket_id: Option<ConnectionId>,
321 ) -> Result<CommunityResponse, LemmyError> {
322 let data: &DeleteCommunity = &self;
323 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
325 // Verify its the creator (only a creator can delete the community)
326 let community_id = data.community_id;
327 let read_community = blocking(context.pool(), move |conn| {
328 Community::read(conn, community_id)
331 if read_community.creator_id != local_user_view.person.id {
332 return Err(ApiError::err("no_community_edit_allowed").into());
336 let community_id = data.community_id;
337 let deleted = data.deleted;
338 let updated_community = match blocking(context.pool(), move |conn| {
339 Community::update_deleted(conn, community_id, deleted)
343 Ok(community) => community,
344 Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
347 // Send apub messages
349 updated_community.send_delete(context).await?;
351 updated_community.send_undo_delete(context).await?;
354 let community_id = data.community_id;
355 let person_id = local_user_view.person.id;
356 let community_view = blocking(context.pool(), move |conn| {
357 CommunityView::read(conn, community_id, Some(person_id))
361 let res = CommunityResponse { community_view };
363 send_community_websocket(&res, context, websocket_id, UserOperation::DeleteCommunity);
369 #[async_trait::async_trait(?Send)]
370 impl Perform for RemoveCommunity {
371 type Response = CommunityResponse;
375 context: &Data<LemmyContext>,
376 websocket_id: Option<ConnectionId>,
377 ) -> Result<CommunityResponse, LemmyError> {
378 let data: &RemoveCommunity = &self;
379 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
381 // Verify its an admin (only an admin can remove a community)
382 is_admin(&local_user_view)?;
385 let community_id = data.community_id;
386 let removed = data.removed;
387 let updated_community = match blocking(context.pool(), move |conn| {
388 Community::update_removed(conn, community_id, removed)
392 Ok(community) => community,
393 Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
397 let expires = match data.expires {
398 Some(time) => Some(naive_from_unix(time)),
401 let form = ModRemoveCommunityForm {
402 mod_person_id: local_user_view.person.id,
403 community_id: data.community_id,
404 removed: Some(removed),
405 reason: data.reason.to_owned(),
408 blocking(context.pool(), move |conn| {
409 ModRemoveCommunity::create(conn, &form)
415 updated_community.send_remove(context).await?;
417 updated_community.send_undo_remove(context).await?;
420 let community_id = data.community_id;
421 let person_id = local_user_view.person.id;
422 let community_view = blocking(context.pool(), move |conn| {
423 CommunityView::read(conn, community_id, Some(person_id))
427 let res = CommunityResponse { community_view };
429 send_community_websocket(&res, context, websocket_id, UserOperation::RemoveCommunity);
435 #[async_trait::async_trait(?Send)]
436 impl Perform for ListCommunities {
437 type Response = ListCommunitiesResponse;
441 context: &Data<LemmyContext>,
442 _websocket_id: Option<ConnectionId>,
443 ) -> Result<ListCommunitiesResponse, LemmyError> {
444 let data: &ListCommunities = &self;
445 let local_user_view = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?;
447 let person_id = match &local_user_view {
448 Some(uv) => Some(uv.person.id),
452 // Don't show NSFW by default
453 let show_nsfw = match &local_user_view {
454 Some(uv) => uv.local_user.show_nsfw,
458 let type_ = ListingType::from_str(&data.type_)?;
459 let sort = SortType::from_str(&data.sort)?;
461 let page = data.page;
462 let limit = data.limit;
463 let communities = blocking(context.pool(), move |conn| {
464 CommunityQueryBuilder::create(conn)
465 .listing_type(&type_)
467 .show_nsfw(show_nsfw)
468 .my_person_id(person_id)
476 Ok(ListCommunitiesResponse { communities })
480 #[async_trait::async_trait(?Send)]
481 impl Perform for FollowCommunity {
482 type Response = CommunityResponse;
486 context: &Data<LemmyContext>,
487 _websocket_id: Option<ConnectionId>,
488 ) -> Result<CommunityResponse, LemmyError> {
489 let data: &FollowCommunity = &self;
490 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
492 let community_id = data.community_id;
493 let community = blocking(context.pool(), move |conn| {
494 Community::read(conn, community_id)
497 let community_follower_form = CommunityFollowerForm {
498 community_id: data.community_id,
499 person_id: local_user_view.person.id,
505 check_community_ban(local_user_view.person.id, community_id, context.pool()).await?;
507 let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
508 if blocking(context.pool(), follow).await?.is_err() {
509 return Err(ApiError::err("community_follower_already_exists").into());
513 move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
514 if blocking(context.pool(), unfollow).await?.is_err() {
515 return Err(ApiError::err("community_follower_already_exists").into());
518 } else if data.follow {
519 // Dont actually add to the community followers here, because you need
520 // to wait for the accept
523 .send_follow(&community.actor_id(), context)
528 .send_unfollow(&community.actor_id(), context)
530 let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
531 if blocking(context.pool(), unfollow).await?.is_err() {
532 return Err(ApiError::err("community_follower_already_exists").into());
536 let community_id = data.community_id;
537 let person_id = local_user_view.person.id;
538 let mut community_view = blocking(context.pool(), move |conn| {
539 CommunityView::read(conn, community_id, Some(person_id))
543 // TODO: this needs to return a "pending" state, until Accept is received from the remote server
544 // For now, just assume that remote follows are accepted.
545 // Otherwise, the subscribed will be null
546 if !community.local {
547 community_view.subscribed = data.follow;
550 Ok(CommunityResponse { community_view })
554 #[async_trait::async_trait(?Send)]
555 impl Perform for GetFollowedCommunities {
556 type Response = GetFollowedCommunitiesResponse;
560 context: &Data<LemmyContext>,
561 _websocket_id: Option<ConnectionId>,
562 ) -> Result<GetFollowedCommunitiesResponse, LemmyError> {
563 let data: &GetFollowedCommunities = &self;
564 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
566 let person_id = local_user_view.person.id;
567 let communities = match blocking(context.pool(), move |conn| {
568 CommunityFollowerView::for_person(conn, person_id)
572 Ok(communities) => communities,
573 _ => return Err(ApiError::err("system_err_login").into()),
577 Ok(GetFollowedCommunitiesResponse { communities })
581 #[async_trait::async_trait(?Send)]
582 impl Perform for BanFromCommunity {
583 type Response = BanFromCommunityResponse;
587 context: &Data<LemmyContext>,
588 websocket_id: Option<ConnectionId>,
589 ) -> Result<BanFromCommunityResponse, LemmyError> {
590 let data: &BanFromCommunity = &self;
591 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
593 let community_id = data.community_id;
594 let banned_person_id = data.person_id;
596 // Verify that only mods or admins can ban
597 is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
599 let community_user_ban_form = CommunityPersonBanForm {
600 community_id: data.community_id,
601 person_id: data.person_id,
605 let ban = move |conn: &'_ _| CommunityPersonBan::ban(conn, &community_user_ban_form);
606 if blocking(context.pool(), ban).await?.is_err() {
607 return Err(ApiError::err("community_user_already_banned").into());
610 // Also unsubscribe them from the community, if they are subscribed
611 let community_follower_form = CommunityFollowerForm {
612 community_id: data.community_id,
613 person_id: banned_person_id,
616 blocking(context.pool(), move |conn: &'_ _| {
617 CommunityFollower::unfollow(conn, &community_follower_form)
622 let unban = move |conn: &'_ _| CommunityPersonBan::unban(conn, &community_user_ban_form);
623 if blocking(context.pool(), unban).await?.is_err() {
624 return Err(ApiError::err("community_user_already_banned").into());
628 // Remove/Restore their data if that's desired
629 if data.remove_data {
631 blocking(context.pool(), move |conn: &'_ _| {
632 Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
637 // TODO Diesel doesn't allow updates with joins, so this has to be a loop
638 let comments = blocking(context.pool(), move |conn| {
639 CommentQueryBuilder::create(conn)
640 .creator_id(banned_person_id)
641 .community_id(community_id)
642 .limit(std::i64::MAX)
647 for comment_view in &comments {
648 let comment_id = comment_view.comment.id;
649 blocking(context.pool(), move |conn: &'_ _| {
650 Comment::update_removed(conn, comment_id, true)
657 // TODO eventually do correct expires
658 let expires = match data.expires {
659 Some(time) => Some(naive_from_unix(time)),
663 let form = ModBanFromCommunityForm {
664 mod_person_id: local_user_view.person.id,
665 other_person_id: data.person_id,
666 community_id: data.community_id,
667 reason: data.reason.to_owned(),
668 banned: Some(data.ban),
671 blocking(context.pool(), move |conn| {
672 ModBanFromCommunity::create(conn, &form)
676 let person_id = data.person_id;
677 let person_view = blocking(context.pool(), move |conn| {
678 PersonViewSafe::read(conn, person_id)
682 let res = BanFromCommunityResponse {
687 context.chat_server().do_send(SendCommunityRoomMessage {
688 op: UserOperation::BanFromCommunity,
689 response: res.clone(),
698 #[async_trait::async_trait(?Send)]
699 impl Perform for AddModToCommunity {
700 type Response = AddModToCommunityResponse;
704 context: &Data<LemmyContext>,
705 websocket_id: Option<ConnectionId>,
706 ) -> Result<AddModToCommunityResponse, LemmyError> {
707 let data: &AddModToCommunity = &self;
708 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
710 let community_moderator_form = CommunityModeratorForm {
711 community_id: data.community_id,
712 person_id: data.person_id,
715 let community_id = data.community_id;
717 // Verify that only mods or admins can add mod
718 is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
721 let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
722 if blocking(context.pool(), join).await?.is_err() {
723 return Err(ApiError::err("community_moderator_already_exists").into());
726 let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form);
727 if blocking(context.pool(), leave).await?.is_err() {
728 return Err(ApiError::err("community_moderator_already_exists").into());
733 let form = ModAddCommunityForm {
734 mod_person_id: local_user_view.person.id,
735 other_person_id: data.person_id,
736 community_id: data.community_id,
737 removed: Some(!data.added),
739 blocking(context.pool(), move |conn| {
740 ModAddCommunity::create(conn, &form)
744 let community_id = data.community_id;
745 let moderators = blocking(context.pool(), move |conn| {
746 CommunityModeratorView::for_community(conn, community_id)
750 let res = AddModToCommunityResponse { moderators };
752 context.chat_server().do_send(SendCommunityRoomMessage {
753 op: UserOperation::AddModToCommunity,
754 response: res.clone(),
763 #[async_trait::async_trait(?Send)]
764 impl Perform for TransferCommunity {
765 type Response = GetCommunityResponse;
769 context: &Data<LemmyContext>,
770 _websocket_id: Option<ConnectionId>,
771 ) -> Result<GetCommunityResponse, LemmyError> {
772 let data: &TransferCommunity = &self;
773 let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
775 let community_id = data.community_id;
776 let read_community = blocking(context.pool(), move |conn| {
777 Community::read(conn, community_id)
781 let site_creator_id = blocking(context.pool(), move |conn| {
782 Site::read(conn, 1).map(|s| s.creator_id)
786 let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
788 // Making sure the creator, if an admin, is at the top
789 let creator_index = admins
791 .position(|r| r.person.id == site_creator_id)
792 .context(location_info!())?;
793 let creator_person = admins.remove(creator_index);
794 admins.insert(0, creator_person);
796 // Make sure user is the creator, or an admin
797 if local_user_view.person.id != read_community.creator_id
800 .map(|a| a.person.id)
801 .any(|x| x == local_user_view.person.id)
803 return Err(ApiError::err("not_an_admin").into());
806 let community_id = data.community_id;
807 let new_creator = data.person_id;
808 let update = move |conn: &'_ _| Community::update_creator(conn, community_id, new_creator);
809 if blocking(context.pool(), update).await?.is_err() {
810 return Err(ApiError::err("couldnt_update_community").into());
813 // You also have to re-do the community_moderator table, reordering it.
814 let community_id = data.community_id;
815 let mut community_mods = blocking(context.pool(), move |conn| {
816 CommunityModeratorView::for_community(conn, community_id)
819 let creator_index = community_mods
821 .position(|r| r.moderator.id == data.person_id)
822 .context(location_info!())?;
823 let creator_person = community_mods.remove(creator_index);
824 community_mods.insert(0, creator_person);
826 let community_id = data.community_id;
827 blocking(context.pool(), move |conn| {
828 CommunityModerator::delete_for_community(conn, community_id)
832 // TODO: this should probably be a bulk operation
833 for cmod in &community_mods {
834 let community_moderator_form = CommunityModeratorForm {
835 community_id: cmod.community.id,
836 person_id: cmod.moderator.id,
839 let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
840 if blocking(context.pool(), join).await?.is_err() {
841 return Err(ApiError::err("community_moderator_already_exists").into());
846 let form = ModAddCommunityForm {
847 mod_person_id: local_user_view.person.id,
848 other_person_id: data.person_id,
849 community_id: data.community_id,
850 removed: Some(false),
852 blocking(context.pool(), move |conn| {
853 ModAddCommunity::create(conn, &form)
857 let community_id = data.community_id;
858 let person_id = local_user_view.person.id;
859 let community_view = match blocking(context.pool(), move |conn| {
860 CommunityView::read(conn, community_id, Some(person_id))
864 Ok(community) => community,
865 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
868 let community_id = data.community_id;
869 let moderators = match blocking(context.pool(), move |conn| {
870 CommunityModeratorView::for_community(conn, community_id)
874 Ok(moderators) => moderators,
875 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
879 Ok(GetCommunityResponse {
887 fn send_community_websocket(
888 res: &CommunityResponse,
889 context: &Data<LemmyContext>,
890 websocket_id: Option<ConnectionId>,
893 // Strip out the person id and subscribed when sending to others
894 let mut res_sent = res.clone();
895 res_sent.community_view.subscribed = false;
897 context.chat_server().do_send(SendCommunityRoomMessage {
900 community_id: res.community_view.community.id,