]> Untitled Git - lemmy.git/blob - crates/api_crud/src/post/create.rs
e0c1a5d13aa743adcb0ca1cf89c90acdc3f77c1c
[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   context::LemmyContext,
5   post::{CreatePost, PostResponse},
6   request::fetch_site_data,
7   utils::{
8     check_community_ban,
9     check_community_deleted_or_removed,
10     generate_local_apub_endpoint,
11     honeypot_check,
12     local_site_to_slur_regex,
13     local_user_view_from_jwt,
14     mark_post_as_read,
15     EndpointType,
16   },
17   websocket::UserOperationCrud,
18 };
19 use lemmy_db_schema::{
20   impls::actor_language::default_post_language,
21   source::{
22     actor_language::CommunityLanguage,
23     community::Community,
24     local_site::LocalSite,
25     post::{Post, PostInsertForm, PostLike, PostLikeForm, PostUpdateForm},
26   },
27   traits::{Crud, Likeable},
28 };
29 use lemmy_db_views_actor::structs::CommunityView;
30 use lemmy_utils::{
31   error::LemmyError,
32   utils::{
33     slurs::{check_slurs, check_slurs_opt},
34     validation::{clean_url_params, is_valid_body_field, is_valid_post_title},
35   },
36   ConnectionId,
37 };
38 use tracing::{warn, Instrument};
39 use url::Url;
40 use webmention::{Webmention, WebmentionError};
41
42 #[async_trait::async_trait(?Send)]
43 impl PerformCrud for CreatePost {
44   type Response = PostResponse;
45
46   #[tracing::instrument(skip(context, websocket_id))]
47   async fn perform(
48     &self,
49     context: &Data<LemmyContext>,
50     websocket_id: Option<ConnectionId>,
51   ) -> Result<PostResponse, LemmyError> {
52     let data: &CreatePost = self;
53     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
54     let local_site = LocalSite::read(context.pool()).await?;
55
56     let slur_regex = local_site_to_slur_regex(&local_site);
57     check_slurs(&data.name, &slur_regex)?;
58     check_slurs_opt(&data.body, &slur_regex)?;
59     honeypot_check(&data.honeypot)?;
60
61     let data_url = data.url.as_ref();
62     let url = data_url.map(clean_url_params).map(Into::into); // TODO no good way to handle a "clear"
63
64     is_valid_post_title(&data.name)?;
65     is_valid_body_field(&data.body)?;
66
67     check_community_ban(local_user_view.person.id, data.community_id, context.pool()).await?;
68     check_community_deleted_or_removed(data.community_id, context.pool()).await?;
69
70     let community_id = data.community_id;
71     let community = Community::read(context.pool(), community_id).await?;
72     if community.posting_restricted_to_mods {
73       let community_id = data.community_id;
74       let is_mod = CommunityView::is_mod_or_admin(
75         context.pool(),
76         local_user_view.local_user.person_id,
77         community_id,
78       )
79       .await?;
80       if !is_mod {
81         return Err(LemmyError::from_message("only_mods_can_post_in_community"));
82       }
83     }
84
85     // Fetch post links and pictrs cached image
86     let (metadata_res, thumbnail_url) =
87       fetch_site_data(context.client(), context.settings(), data_url).await;
88     let (embed_title, embed_description, embed_video_url) = metadata_res
89       .map(|u| (u.title, u.description, u.embed_video_url))
90       .unwrap_or_default();
91
92     let language_id = match data.language_id {
93       Some(lid) => Some(lid),
94       None => {
95         default_post_language(context.pool(), community_id, local_user_view.local_user.id).await?
96       }
97     };
98     CommunityLanguage::is_allowed_community_language(context.pool(), language_id, community_id)
99       .await?;
100
101     let post_form = PostInsertForm::builder()
102       .name(data.name.trim().to_owned())
103       .url(url)
104       .body(data.body.clone())
105       .community_id(data.community_id)
106       .creator_id(local_user_view.person.id)
107       .nsfw(data.nsfw)
108       .embed_title(embed_title)
109       .embed_description(embed_description)
110       .embed_video_url(embed_video_url)
111       .language_id(language_id)
112       .thumbnail_url(thumbnail_url)
113       .build();
114
115     let inserted_post = match Post::create(context.pool(), &post_form).await {
116       Ok(post) => post,
117       Err(e) => {
118         let err_type = if e.to_string() == "value too long for type character varying(200)" {
119           "post_title_too_long"
120         } else {
121           "couldnt_create_post"
122         };
123
124         return Err(LemmyError::from_error_message(e, err_type));
125       }
126     };
127
128     let inserted_post_id = inserted_post.id;
129     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
130     let apub_id = generate_local_apub_endpoint(
131       EndpointType::Post,
132       &inserted_post_id.to_string(),
133       &protocol_and_hostname,
134     )?;
135     let updated_post = Post::update(
136       context.pool(),
137       inserted_post_id,
138       &PostUpdateForm::builder().ap_id(Some(apub_id)).build(),
139     )
140     .await
141     .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_post"))?;
142
143     // They like their own post by default
144     let person_id = local_user_view.person.id;
145     let post_id = inserted_post.id;
146     let like_form = PostLikeForm {
147       post_id,
148       person_id,
149       score: 1,
150     };
151
152     PostLike::like(context.pool(), &like_form)
153       .await
154       .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_post"))?;
155
156     // Mark the post as read
157     mark_post_as_read(person_id, post_id, context.pool()).await?;
158
159     if let Some(url) = &updated_post.url {
160       let mut webmention =
161         Webmention::new::<Url>(updated_post.ap_id.clone().into(), url.clone().into())?;
162       webmention.set_checked(true);
163       match webmention
164         .send()
165         .instrument(tracing::info_span!("Sending webmention"))
166         .await
167       {
168         Ok(_) => {}
169         Err(WebmentionError::NoEndpointDiscovered(_)) => {}
170         Err(e) => warn!("Failed to send webmention: {}", e),
171       }
172     }
173
174     context
175       .send_post_ws_message(
176         &UserOperationCrud::CreatePost,
177         inserted_post.id,
178         websocket_id,
179         Some(local_user_view.person.id),
180       )
181       .await
182   }
183 }