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