]> Untitled Git - lemmy.git/blob - crates/api_crud/src/post/create.rs
Opentelemetry (#1992)
[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::{check_slurs, check_slurs_opt, clean_url_params, is_valid_post_title},
30   ConnectionId,
31   LemmyError,
32 };
33 use lemmy_websocket::{send::send_post_ws_message, LemmyContext, UserOperationCrud};
34 use tracing::{warn, Instrument};
35 use url::Url;
36 use webmention::{Webmention, WebmentionError};
37
38 #[async_trait::async_trait(?Send)]
39 impl PerformCrud for CreatePost {
40   type Response = PostResponse;
41
42   #[tracing::instrument(skip(context, websocket_id))]
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(LemmyError::from_message("invalid_post_title"));
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(LemmyError::from(e).with_message(err_type));
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(LemmyError::from)
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     if blocking(context.pool(), like).await?.is_err() {
125       return Err(LemmyError::from_message("couldnt_like_post"));
126     }
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     let object = PostOrComment::Post(Box::new(apub_post));
155     Vote::send(
156       &object,
157       &local_user_view.person.clone().into(),
158       inserted_post.community_id,
159       VoteType::Like,
160       context,
161     )
162     .await?;
163
164     send_post_ws_message(
165       inserted_post.id,
166       UserOperationCrud::CreatePost,
167       websocket_id,
168       Some(local_user_view.person.id),
169       context,
170     )
171     .await
172   }
173 }