]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/update.rs
Rewrite delete activities (#1699)
[lemmy.git] / crates / api_crud / src / community / update.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   blocking,
5   community::{CommunityResponse, EditCommunity},
6   get_local_user_view_from_jwt,
7 };
8 use lemmy_apub::CommunityType;
9 use lemmy_db_queries::{diesel_option_overwrite_to_url, Crud};
10 use lemmy_db_schema::{
11   naive_now,
12   source::community::{Community, CommunityForm},
13   PersonId,
14 };
15 use lemmy_db_views_actor::community_moderator_view::CommunityModeratorView;
16 use lemmy_utils::{utils::check_slurs_opt, ApiError, ConnectionId, LemmyError};
17 use lemmy_websocket::{send::send_community_ws_message, LemmyContext, UserOperationCrud};
18
19 #[async_trait::async_trait(?Send)]
20 impl PerformCrud for EditCommunity {
21   type Response = CommunityResponse;
22
23   async fn perform(
24     &self,
25     context: &Data<LemmyContext>,
26     websocket_id: Option<ConnectionId>,
27   ) -> Result<CommunityResponse, LemmyError> {
28     let data: &EditCommunity = self;
29     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
30
31     check_slurs_opt(&data.title)?;
32     check_slurs_opt(&data.description)?;
33
34     // Verify its a mod (only mods can edit it)
35     let community_id = data.community_id;
36     let mods: Vec<PersonId> = blocking(context.pool(), move |conn| {
37       CommunityModeratorView::for_community(conn, community_id)
38         .map(|v| v.into_iter().map(|m| m.moderator.id).collect())
39     })
40     .await??;
41     if !mods.contains(&local_user_view.person.id) {
42       return Err(ApiError::err("not_a_moderator").into());
43     }
44
45     let community_id = data.community_id;
46     let read_community = blocking(context.pool(), move |conn| {
47       Community::read(conn, community_id)
48     })
49     .await??;
50
51     let icon = diesel_option_overwrite_to_url(&data.icon)?;
52     let banner = diesel_option_overwrite_to_url(&data.banner)?;
53
54     let community_form = CommunityForm {
55       name: read_community.name,
56       title: data.title.to_owned().unwrap_or(read_community.title),
57       description: data.description.to_owned(),
58       icon,
59       banner,
60       nsfw: data.nsfw,
61       updated: Some(naive_now()),
62       ..CommunityForm::default()
63     };
64
65     let community_id = data.community_id;
66     let updated_community = blocking(context.pool(), move |conn| {
67       Community::update(conn, community_id, &community_form)
68     })
69     .await?
70     .map_err(|_| ApiError::err("couldnt_update_community"))?;
71
72     updated_community
73       .send_update(local_user_view.person.to_owned(), context)
74       .await?;
75
76     let op = UserOperationCrud::EditCommunity;
77     send_community_ws_message(data.community_id, op, websocket_id, None, context).await
78   }
79 }