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