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