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