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