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