]> Untitled Git - lemmy.git/blob - crates/api_crud/src/post/create.rs
Add separate Post check for is_valid_body_field (#3263)
[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,
32   utils::{
33     slurs::{check_slurs, check_slurs_opt},
34     validation::{clean_url_params, is_valid_body_field, is_valid_post_title},
35   },
36 };
37 use tracing::{warn, Instrument};
38 use url::Url;
39 use webmention::{Webmention, WebmentionError};
40
41 #[async_trait::async_trait(?Send)]
42 impl PerformCrud for CreatePost {
43   type Response = PostResponse;
44
45   #[tracing::instrument(skip(context))]
46   async fn perform(&self, context: &Data<LemmyContext>) -> Result<PostResponse, LemmyError> {
47     let data: &CreatePost = self;
48     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
49     let local_site = LocalSite::read(context.pool()).await?;
50
51     let slur_regex = local_site_to_slur_regex(&local_site);
52     check_slurs(&data.name, &slur_regex)?;
53     check_slurs_opt(&data.body, &slur_regex)?;
54     honeypot_check(&data.honeypot)?;
55
56     let data_url = data.url.as_ref();
57     let url = data_url.map(clean_url_params).map(Into::into); // TODO no good way to handle a "clear"
58
59     is_valid_post_title(&data.name)?;
60     is_valid_body_field(&data.body, true)?;
61
62     check_community_ban(local_user_view.person.id, data.community_id, context.pool()).await?;
63     check_community_deleted_or_removed(data.community_id, context.pool()).await?;
64
65     let community_id = data.community_id;
66     let community = Community::read(context.pool(), community_id).await?;
67     if community.posting_restricted_to_mods {
68       let community_id = data.community_id;
69       let is_mod = CommunityView::is_mod_or_admin(
70         context.pool(),
71         local_user_view.local_user.person_id,
72         community_id,
73       )
74       .await?;
75       if !is_mod {
76         return Err(LemmyError::from_message("only_mods_can_post_in_community"));
77       }
78     }
79
80     // Fetch post links and pictrs cached image
81     let (metadata_res, thumbnail_url) =
82       fetch_site_data(context.client(), context.settings(), data_url).await;
83     let (embed_title, embed_description, embed_video_url) = metadata_res
84       .map(|u| (u.title, u.description, u.embed_video_url))
85       .unwrap_or_default();
86
87     let language_id = match data.language_id {
88       Some(lid) => Some(lid),
89       None => {
90         default_post_language(context.pool(), community_id, local_user_view.local_user.id).await?
91       }
92     };
93     CommunityLanguage::is_allowed_community_language(context.pool(), language_id, community_id)
94       .await?;
95
96     let post_form = PostInsertForm::builder()
97       .name(data.name.trim().to_owned())
98       .url(url)
99       .body(data.body.clone())
100       .community_id(data.community_id)
101       .creator_id(local_user_view.person.id)
102       .nsfw(data.nsfw)
103       .embed_title(embed_title)
104       .embed_description(embed_description)
105       .embed_video_url(embed_video_url)
106       .language_id(language_id)
107       .thumbnail_url(thumbnail_url)
108       .build();
109
110     let inserted_post = match Post::create(context.pool(), &post_form).await {
111       Ok(post) => post,
112       Err(e) => {
113         let err_type = if e.to_string() == "value too long for type character varying(200)" {
114           "post_title_too_long"
115         } else {
116           "couldnt_create_post"
117         };
118
119         return Err(LemmyError::from_error_message(e, err_type));
120       }
121     };
122
123     let inserted_post_id = inserted_post.id;
124     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
125     let apub_id = generate_local_apub_endpoint(
126       EndpointType::Post,
127       &inserted_post_id.to_string(),
128       &protocol_and_hostname,
129     )?;
130     let updated_post = Post::update(
131       context.pool(),
132       inserted_post_id,
133       &PostUpdateForm::builder().ap_id(Some(apub_id)).build(),
134     )
135     .await
136     .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_post"))?;
137
138     // They like their own post by default
139     let person_id = local_user_view.person.id;
140     let post_id = inserted_post.id;
141     let like_form = PostLikeForm {
142       post_id,
143       person_id,
144       score: 1,
145     };
146
147     PostLike::like(context.pool(), &like_form)
148       .await
149       .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_post"))?;
150
151     // Mark the post as read
152     mark_post_as_read(person_id, post_id, context.pool()).await?;
153
154     if let Some(url) = &updated_post.url {
155       let mut webmention =
156         Webmention::new::<Url>(updated_post.ap_id.clone().into(), url.clone().into())?;
157       webmention.set_checked(true);
158       match webmention
159         .send()
160         .instrument(tracing::info_span!("Sending webmention"))
161         .await
162       {
163         Ok(_) => {}
164         Err(WebmentionError::NoEndpointDiscovered(_)) => {}
165         Err(e) => warn!("Failed to send webmention: {}", e),
166       }
167     }
168
169     build_post_response(context, community_id, person_id, post_id).await
170   }
171 }