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