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