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