]> Untitled Git - lemmy.git/blob - crates/api_crud/src/post/create.rs
Cleaning optional post bodies. Fixes #2039 (#2043)
[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   blocking,
5   check_community_ban,
6   check_community_deleted_or_removed,
7   get_local_user_view_from_jwt,
8   honeypot_check,
9   mark_post_as_read,
10   post::*,
11 };
12 use lemmy_apub::{
13   fetcher::post_or_comment::PostOrComment,
14   generate_local_apub_endpoint,
15   objects::post::ApubPost,
16   protocol::activities::{
17     create_or_update::post::CreateOrUpdatePost,
18     voting::vote::{Vote, VoteType},
19     CreateOrUpdateType,
20   },
21   EndpointType,
22 };
23 use lemmy_db_schema::{
24   source::post::{Post, PostForm, PostLike, PostLikeForm},
25   traits::{Crud, Likeable},
26 };
27 use lemmy_utils::{
28   request::fetch_site_data,
29   utils::{
30     check_slurs,
31     check_slurs_opt,
32     clean_optional_text,
33     clean_url_params,
34     is_valid_post_title,
35   },
36   ConnectionId,
37   LemmyError,
38 };
39 use lemmy_websocket::{send::send_post_ws_message, LemmyContext, UserOperationCrud};
40 use tracing::{warn, Instrument};
41 use url::Url;
42 use webmention::{Webmention, WebmentionError};
43
44 #[async_trait::async_trait(?Send)]
45 impl PerformCrud for CreatePost {
46   type Response = PostResponse;
47
48   #[tracing::instrument(skip(context, websocket_id))]
49   async fn perform(
50     &self,
51     context: &Data<LemmyContext>,
52     websocket_id: Option<ConnectionId>,
53   ) -> Result<PostResponse, LemmyError> {
54     let data: &CreatePost = self;
55     let local_user_view =
56       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
57
58     let slur_regex = &context.settings().slur_regex();
59     check_slurs(&data.name, slur_regex)?;
60     check_slurs_opt(&data.body, slur_regex)?;
61     honeypot_check(&data.honeypot)?;
62
63     if !is_valid_post_title(&data.name) {
64       return Err(LemmyError::from_message("invalid_post_title"));
65     }
66
67     check_community_ban(local_user_view.person.id, data.community_id, context.pool()).await?;
68     check_community_deleted_or_removed(data.community_id, context.pool()).await?;
69
70     // Fetch post links and pictrs cached image
71     let data_url = data.url.as_ref();
72     let (metadata_res, pictrs_thumbnail) =
73       fetch_site_data(context.client(), &context.settings(), data_url).await;
74     let (embed_title, embed_description, embed_html) = metadata_res
75       .map(|u| (u.title, u.description, u.html))
76       .unwrap_or((None, None, None));
77
78     let post_form = PostForm {
79       name: data.name.trim().to_owned(),
80       url: data_url.map(|u| clean_url_params(u.to_owned()).into()),
81       body: clean_optional_text(&data.body),
82       community_id: data.community_id,
83       creator_id: local_user_view.person.id,
84       nsfw: data.nsfw,
85       embed_title,
86       embed_description,
87       embed_html,
88       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
89       ..PostForm::default()
90     };
91
92     let inserted_post =
93       match blocking(context.pool(), move |conn| Post::create(conn, &post_form)).await? {
94         Ok(post) => post,
95         Err(e) => {
96           let err_type = if e.to_string() == "value too long for type character varying(200)" {
97             "post_title_too_long"
98           } else {
99             "couldnt_create_post"
100           };
101
102           return Err(LemmyError::from(e).with_message(err_type));
103         }
104       };
105
106     let inserted_post_id = inserted_post.id;
107     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
108     let updated_post = blocking(context.pool(), move |conn| -> Result<Post, LemmyError> {
109       let apub_id = generate_local_apub_endpoint(
110         EndpointType::Post,
111         &inserted_post_id.to_string(),
112         &protocol_and_hostname,
113       )?;
114       Ok(Post::update_ap_id(conn, inserted_post_id, apub_id)?)
115     })
116     .await?
117     .map_err(LemmyError::from)
118     .map_err(|e| e.with_message("couldnt_create_post"))?;
119
120     // They like their own post by default
121     let person_id = local_user_view.person.id;
122     let post_id = inserted_post.id;
123     let like_form = PostLikeForm {
124       post_id,
125       person_id,
126       score: 1,
127     };
128
129     let like = move |conn: &'_ _| PostLike::like(conn, &like_form);
130     if blocking(context.pool(), like).await?.is_err() {
131       return Err(LemmyError::from_message("couldnt_like_post"));
132     }
133
134     // Mark the post as read
135     mark_post_as_read(person_id, post_id, context.pool()).await?;
136
137     if let Some(url) = &updated_post.url {
138       let mut webmention =
139         Webmention::new::<Url>(updated_post.ap_id.clone().into(), url.clone().into())?;
140       webmention.set_checked(true);
141       match webmention
142         .send()
143         .instrument(tracing::info_span!("Sending webmention"))
144         .await
145       {
146         Ok(_) => {}
147         Err(WebmentionError::NoEndpointDiscovered(_)) => {}
148         Err(e) => warn!("Failed to send webmention: {}", e),
149       }
150     }
151
152     let apub_post: ApubPost = updated_post.into();
153     CreateOrUpdatePost::send(
154       apub_post.clone(),
155       &local_user_view.person.clone().into(),
156       CreateOrUpdateType::Create,
157       context,
158     )
159     .await?;
160     let object = PostOrComment::Post(Box::new(apub_post));
161     Vote::send(
162       &object,
163       &local_user_view.person.clone().into(),
164       inserted_post.community_id,
165       VoteType::Like,
166       context,
167     )
168     .await?;
169
170     send_post_ws_message(
171       inserted_post.id,
172       UserOperationCrud::CreatePost,
173       websocket_id,
174       Some(local_user_view.person.id),
175       context,
176     )
177     .await
178   }
179 }