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