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