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