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