]> Untitled Git - lemmy.git/blob - crates/api_crud/src/post/create.rs
a7aafe81249e0b9f2a25799eaf82cc01ce11311a
[lemmy.git] / crates / api_crud / src / post / create.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   build_response::build_post_response,
5   context::LemmyContext,
6   post::{CreatePost, PostResponse},
7   request::fetch_site_data,
8   utils::{
9     check_community_ban,
10     check_community_deleted_or_removed,
11     generate_local_apub_endpoint,
12     honeypot_check,
13     local_site_to_slur_regex,
14     local_user_view_from_jwt,
15     mark_post_as_read,
16     EndpointType,
17   },
18 };
19 use lemmy_db_schema::{
20   impls::actor_language::default_post_language,
21   source::{
22     actor_language::CommunityLanguage,
23     community::Community,
24     local_site::LocalSite,
25     post::{Post, PostInsertForm, PostLike, PostLikeForm, PostUpdateForm},
26   },
27   traits::{Crud, Likeable},
28 };
29 use lemmy_db_views_actor::structs::CommunityView;
30 use lemmy_utils::{
31   error::{LemmyError, LemmyErrorExt, LemmyErrorType},
32   spawn_try_task,
33   utils::{
34     slurs::{check_slurs, check_slurs_opt},
35     validation::{check_url_scheme, clean_url_params, is_valid_body_field, is_valid_post_title},
36   },
37   SYNCHRONOUS_FEDERATION,
38 };
39 use tracing::Instrument;
40 use url::Url;
41 use webmention::{Webmention, WebmentionError};
42
43 #[async_trait::async_trait(?Send)]
44 impl PerformCrud for CreatePost {
45   type Response = PostResponse;
46
47   #[tracing::instrument(skip(context))]
48   async fn perform(&self, context: &Data<LemmyContext>) -> Result<PostResponse, LemmyError> {
49     let data: &CreatePost = self;
50     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
51     let local_site = LocalSite::read(&mut context.pool()).await?;
52
53     let slur_regex = local_site_to_slur_regex(&local_site);
54     check_slurs(&data.name, &slur_regex)?;
55     check_slurs_opt(&data.body, &slur_regex)?;
56     honeypot_check(&data.honeypot)?;
57
58     let data_url = data.url.as_ref();
59     let url = data_url.map(clean_url_params).map(Into::into); // TODO no good way to handle a "clear"
60
61     is_valid_post_title(&data.name)?;
62     is_valid_body_field(&data.body, true)?;
63     check_url_scheme(&data.url)?;
64
65     check_community_ban(
66       local_user_view.person.id,
67       data.community_id,
68       &mut context.pool(),
69     )
70     .await?;
71     check_community_deleted_or_removed(data.community_id, &mut context.pool()).await?;
72
73     let community_id = data.community_id;
74     let community = Community::read(&mut context.pool(), community_id).await?;
75     if community.posting_restricted_to_mods {
76       let community_id = data.community_id;
77       let is_mod = CommunityView::is_mod_or_admin(
78         &mut context.pool(),
79         local_user_view.local_user.person_id,
80         community_id,
81       )
82       .await?;
83       if !is_mod {
84         return Err(LemmyErrorType::OnlyModsCanPostInCommunity)?;
85       }
86     }
87
88     // Fetch post links and pictrs cached image
89     let (metadata_res, thumbnail_url) =
90       fetch_site_data(context.client(), context.settings(), data_url, true).await;
91     let (embed_title, embed_description, embed_video_url) = metadata_res
92       .map(|u| (u.title, u.description, u.embed_video_url))
93       .unwrap_or_default();
94
95     let language_id = match data.language_id {
96       Some(lid) => Some(lid),
97       None => {
98         default_post_language(
99           &mut context.pool(),
100           community_id,
101           local_user_view.local_user.id,
102         )
103         .await?
104       }
105     };
106     CommunityLanguage::is_allowed_community_language(
107       &mut context.pool(),
108       language_id,
109       community_id,
110     )
111     .await?;
112
113     let post_form = PostInsertForm::builder()
114       .name(data.name.trim().to_owned())
115       .url(url)
116       .body(data.body.clone())
117       .community_id(data.community_id)
118       .creator_id(local_user_view.person.id)
119       .nsfw(data.nsfw)
120       .embed_title(embed_title)
121       .embed_description(embed_description)
122       .embed_video_url(embed_video_url)
123       .language_id(language_id)
124       .thumbnail_url(thumbnail_url)
125       .build();
126
127     let inserted_post = Post::create(&mut context.pool(), &post_form)
128       .await
129       .with_lemmy_type(LemmyErrorType::CouldntCreatePost)?;
130
131     let inserted_post_id = inserted_post.id;
132     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
133     let apub_id = generate_local_apub_endpoint(
134       EndpointType::Post,
135       &inserted_post_id.to_string(),
136       &protocol_and_hostname,
137     )?;
138     let updated_post = Post::update(
139       &mut context.pool(),
140       inserted_post_id,
141       &PostUpdateForm::builder().ap_id(Some(apub_id)).build(),
142     )
143     .await
144     .with_lemmy_type(LemmyErrorType::CouldntCreatePost)?;
145
146     // They like their own post by default
147     let person_id = local_user_view.person.id;
148     let post_id = inserted_post.id;
149     let like_form = PostLikeForm {
150       post_id,
151       person_id,
152       score: 1,
153     };
154
155     PostLike::like(&mut context.pool(), &like_form)
156       .await
157       .with_lemmy_type(LemmyErrorType::CouldntLikePost)?;
158
159     // Mark the post as read
160     mark_post_as_read(person_id, post_id, &mut context.pool()).await?;
161
162     if let Some(url) = updated_post.url.clone() {
163       let task = async move {
164         let mut webmention =
165           Webmention::new::<Url>(updated_post.ap_id.clone().into(), url.clone().into())?;
166         webmention.set_checked(true);
167         match webmention
168           .send()
169           .instrument(tracing::info_span!("Sending webmention"))
170           .await
171         {
172           Err(WebmentionError::NoEndpointDiscovered(_)) => Ok(()),
173           Ok(_) => Ok(()),
174           Err(e) => Err(e).with_lemmy_type(LemmyErrorType::CouldntSendWebmention),
175         }
176       };
177       if *SYNCHRONOUS_FEDERATION {
178         task.await?;
179       } else {
180         spawn_try_task(task);
181       }
182     };
183
184     build_post_response(context, community_id, person_id, post_id).await
185   }
186 }