]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/create.rs
6838216ffab8af2c1114290f9d6542f0f97ab72d
[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   community::{CommunityResponse, CreateCommunity},
5   utils::{blocking, check_image_has_local_domain, get_local_user_view_from_jwt, is_admin},
6 };
7 use lemmy_apub::{
8   generate_followers_url,
9   generate_inbox_url,
10   generate_local_apub_endpoint,
11   generate_shared_inbox_url,
12   objects::community::ApubCommunity,
13   EndpointType,
14 };
15 use lemmy_apub_lib::object_id::ObjectId;
16 use lemmy_db_schema::{
17   source::{
18     community::{
19       Community,
20       CommunityFollower,
21       CommunityFollowerForm,
22       CommunityForm,
23       CommunityModerator,
24       CommunityModeratorForm,
25     },
26     site::Site,
27   },
28   traits::{Crud, Followable, Joinable},
29   utils::diesel_option_overwrite_to_url,
30 };
31 use lemmy_db_views_actor::structs::CommunityView;
32 use lemmy_utils::{
33   apub::generate_actor_keypair,
34   utils::{check_slurs, check_slurs_opt, is_valid_actor_name},
35   ConnectionId,
36   LemmyError,
37 };
38 use lemmy_websocket::LemmyContext;
39
40 #[async_trait::async_trait(?Send)]
41 impl PerformCrud for CreateCommunity {
42   type Response = CommunityResponse;
43
44   #[tracing::instrument(skip(context, _websocket_id))]
45   async fn perform(
46     &self,
47     context: &Data<LemmyContext>,
48     _websocket_id: Option<ConnectionId>,
49   ) -> Result<CommunityResponse, LemmyError> {
50     let data: &CreateCommunity = self;
51     let local_user_view =
52       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
53
54     let site = blocking(context.pool(), Site::read_local_site).await??;
55     if site.community_creation_admin_only && is_admin(&local_user_view).is_err() {
56       return Err(LemmyError::from_message(
57         "only_admins_can_create_communities",
58       ));
59     }
60
61     // Check to make sure the icon and banners are urls
62     let icon = diesel_option_overwrite_to_url(&data.icon)?;
63     let banner = diesel_option_overwrite_to_url(&data.banner)?;
64
65     check_slurs(&data.name, &context.settings().slur_regex())?;
66     check_slurs(&data.title, &context.settings().slur_regex())?;
67     check_slurs_opt(&data.description, &context.settings().slur_regex())?;
68     check_image_has_local_domain(icon.as_ref().unwrap_or(&None))?;
69     check_image_has_local_domain(banner.as_ref().unwrap_or(&None))?;
70
71     if !is_valid_actor_name(&data.name, context.settings().actor_name_max_length) {
72       return Err(LemmyError::from_message("invalid_community_name"));
73     }
74
75     // Double check for duplicate community actor_ids
76     let community_actor_id = generate_local_apub_endpoint(
77       EndpointType::Community,
78       &data.name,
79       &context.settings().get_protocol_and_hostname(),
80     )?;
81     let community_actor_id_wrapped = ObjectId::<ApubCommunity>::new(community_actor_id.clone());
82     let community_dupe = community_actor_id_wrapped.dereference_local(context).await;
83     if community_dupe.is_ok() {
84       return Err(LemmyError::from_message("community_already_exists"));
85     }
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       posting_restricted_to_mods: data.posting_restricted_to_mods,
104       ..CommunityForm::default()
105     };
106
107     let inserted_community = blocking(context.pool(), move |conn| {
108       Community::create(conn, &community_form)
109     })
110     .await?
111     .map_err(|e| LemmyError::from_error_message(e, "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     blocking(context.pool(), join)
121       .await?
122       .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
123
124     // Follow your own community
125     let community_follower_form = CommunityFollowerForm {
126       community_id: inserted_community.id,
127       person_id: local_user_view.person.id,
128       pending: false,
129     };
130
131     let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
132     blocking(context.pool(), follow)
133       .await?
134       .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?;
135
136     let person_id = local_user_view.person.id;
137     let community_view = blocking(context.pool(), move |conn| {
138       CommunityView::read(conn, inserted_community.id, Some(person_id))
139     })
140     .await??;
141
142     Ok(CommunityResponse { community_view })
143   }
144 }