]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/create.rs
Don't drop error context when adding a message to errors (#1958)
[lemmy.git] / crates / api_crud / src / community / create.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   blocking,
5   community::{CommunityResponse, CreateCommunity},
6   get_local_user_view_from_jwt,
7   is_admin,
8 };
9 use lemmy_apub::{
10   generate_followers_url,
11   generate_inbox_url,
12   generate_local_apub_endpoint,
13   generate_shared_inbox_url,
14   objects::community::ApubCommunity,
15   EndpointType,
16 };
17 use lemmy_apub_lib::object_id::ObjectId;
18 use lemmy_db_schema::{
19   diesel_option_overwrite_to_url,
20   source::{
21     community::{
22       Community,
23       CommunityFollower,
24       CommunityFollowerForm,
25       CommunityForm,
26       CommunityModerator,
27       CommunityModeratorForm,
28     },
29     site::Site,
30   },
31   traits::{Crud, Followable, Joinable},
32 };
33 use lemmy_db_views_actor::community_view::CommunityView;
34 use lemmy_utils::{
35   apub::generate_actor_keypair,
36   utils::{check_slurs, check_slurs_opt, is_valid_actor_name},
37   ConnectionId,
38   LemmyError,
39 };
40 use lemmy_websocket::LemmyContext;
41
42 #[async_trait::async_trait(?Send)]
43 impl PerformCrud for CreateCommunity {
44   type Response = CommunityResponse;
45
46   #[tracing::instrument(skip(context, _websocket_id))]
47   async fn perform(
48     &self,
49     context: &Data<LemmyContext>,
50     _websocket_id: Option<ConnectionId>,
51   ) -> Result<CommunityResponse, LemmyError> {
52     let data: &CreateCommunity = self;
53     let local_user_view =
54       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
55
56     let site = blocking(context.pool(), move |conn| Site::read(conn, 0)).await??;
57     if site.community_creation_admin_only && is_admin(&local_user_view).is_err() {
58       return Err(LemmyError::from_message(
59         "only_admins_can_create_communities",
60       ));
61     }
62
63     check_slurs(&data.name, &context.settings().slur_regex())?;
64     check_slurs(&data.title, &context.settings().slur_regex())?;
65     check_slurs_opt(&data.description, &context.settings().slur_regex())?;
66
67     if !is_valid_actor_name(&data.name, context.settings().actor_name_max_length) {
68       return Err(LemmyError::from_message("invalid_community_name"));
69     }
70
71     // Double check for duplicate community actor_ids
72     let community_actor_id = generate_local_apub_endpoint(
73       EndpointType::Community,
74       &data.name,
75       &context.settings().get_protocol_and_hostname(),
76     )?;
77     let community_actor_id_wrapped = ObjectId::<ApubCommunity>::new(community_actor_id.clone());
78     let community_dupe = community_actor_id_wrapped.dereference_local(context).await;
79     if community_dupe.is_ok() {
80       return Err(LemmyError::from_message("community_already_exists"));
81     }
82
83     // Check to make sure the icon and banners are urls
84     let icon = diesel_option_overwrite_to_url(&data.icon)?;
85     let banner = diesel_option_overwrite_to_url(&data.banner)?;
86
87     // When you create a community, make sure the user becomes a moderator and a follower
88     let keypair = generate_actor_keypair()?;
89
90     let community_form = CommunityForm {
91       name: data.name.to_owned(),
92       title: data.title.to_owned(),
93       description: data.description.to_owned(),
94       icon,
95       banner,
96       nsfw: data.nsfw,
97       actor_id: Some(community_actor_id.to_owned()),
98       private_key: Some(Some(keypair.private_key)),
99       public_key: keypair.public_key,
100       followers_url: Some(generate_followers_url(&community_actor_id)?),
101       inbox_url: Some(generate_inbox_url(&community_actor_id)?),
102       shared_inbox_url: Some(Some(generate_shared_inbox_url(&community_actor_id)?)),
103       ..CommunityForm::default()
104     };
105
106     let inserted_community = blocking(context.pool(), move |conn| {
107       Community::create(conn, &community_form)
108     })
109     .await?
110     .map_err(LemmyError::from)
111     .map_err(|e| e.with_message("community_already_exists"))?;
112
113     // The community creator becomes a moderator
114     let community_moderator_form = CommunityModeratorForm {
115       community_id: inserted_community.id,
116       person_id: local_user_view.person.id,
117     };
118
119     let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
120     if blocking(context.pool(), join).await?.is_err() {
121       return Err(LemmyError::from_message(
122         "community_moderator_already_exists",
123       ));
124     }
125
126     // Follow your own community
127     let community_follower_form = CommunityFollowerForm {
128       community_id: inserted_community.id,
129       person_id: local_user_view.person.id,
130       pending: false,
131     };
132
133     let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
134     if blocking(context.pool(), follow).await?.is_err() {
135       return Err(LemmyError::from_message(
136         "community_follower_already_exists",
137       ));
138     }
139
140     let person_id = local_user_view.person.id;
141     let community_view = blocking(context.pool(), move |conn| {
142       CommunityView::read(conn, inserted_community.id, Some(person_id))
143     })
144     .await??;
145
146     Ok(CommunityResponse { community_view })
147   }
148 }