]> Untitled Git - lemmy.git/blob - crates/api_crud/src/post/create.rs
Improve api response times by doing send_activity asynchronously (#3493)
[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   build_response::build_post_response,
5   context::LemmyContext,
6   post::{CreatePost, PostResponse},
7   request::fetch_site_data,
8   utils::{
9     check_community_ban,
10     check_community_deleted_or_removed,
11     generate_local_apub_endpoint,
12     honeypot_check,
13     local_site_to_slur_regex,
14     local_user_view_from_jwt,
15     mark_post_as_read,
16     EndpointType,
17   },
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   spawn_try_task,
33   utils::{
34     slurs::{check_slurs, check_slurs_opt},
35     validation::{check_url_scheme, clean_url_params, is_valid_body_field, is_valid_post_title},
36   },
37   SYNCHRONOUS_FEDERATION,
38 };
39 use tracing::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))]
48   async fn perform(&self, context: &Data<LemmyContext>) -> Result<PostResponse, LemmyError> {
49     let data: &CreatePost = self;
50     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
51     let local_site = LocalSite::read(context.pool()).await?;
52
53     let slur_regex = local_site_to_slur_regex(&local_site);
54     check_slurs(&data.name, &slur_regex)?;
55     check_slurs_opt(&data.body, &slur_regex)?;
56     honeypot_check(&data.honeypot)?;
57
58     let data_url = data.url.as_ref();
59     let url = data_url.map(clean_url_params).map(Into::into); // TODO no good way to handle a "clear"
60
61     is_valid_post_title(&data.name)?;
62     is_valid_body_field(&data.body, true)?;
63     check_url_scheme(&data.url)?;
64
65     check_community_ban(local_user_view.person.id, data.community_id, context.pool()).await?;
66     check_community_deleted_or_removed(data.community_id, context.pool()).await?;
67
68     let community_id = data.community_id;
69     let community = Community::read(context.pool(), community_id).await?;
70     if community.posting_restricted_to_mods {
71       let community_id = data.community_id;
72       let is_mod = CommunityView::is_mod_or_admin(
73         context.pool(),
74         local_user_view.local_user.person_id,
75         community_id,
76       )
77       .await?;
78       if !is_mod {
79         return Err(LemmyError::from_message("only_mods_can_post_in_community"));
80       }
81     }
82
83     // Fetch post links and pictrs cached image
84     let (metadata_res, thumbnail_url) =
85       fetch_site_data(context.client(), context.settings(), data_url, true).await;
86     let (embed_title, embed_description, embed_video_url) = metadata_res
87       .map(|u| (u.title, u.description, u.embed_video_url))
88       .unwrap_or_default();
89
90     let language_id = match data.language_id {
91       Some(lid) => Some(lid),
92       None => {
93         default_post_language(context.pool(), community_id, local_user_view.local_user.id).await?
94       }
95     };
96     CommunityLanguage::is_allowed_community_language(context.pool(), language_id, community_id)
97       .await?;
98
99     let post_form = PostInsertForm::builder()
100       .name(data.name.trim().to_owned())
101       .url(url)
102       .body(data.body.clone())
103       .community_id(data.community_id)
104       .creator_id(local_user_view.person.id)
105       .nsfw(data.nsfw)
106       .embed_title(embed_title)
107       .embed_description(embed_description)
108       .embed_video_url(embed_video_url)
109       .language_id(language_id)
110       .thumbnail_url(thumbnail_url)
111       .build();
112
113     let inserted_post = Post::create(context.pool(), &post_form)
114       .await
115       .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_post"))?;
116
117     let inserted_post_id = inserted_post.id;
118     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
119     let apub_id = generate_local_apub_endpoint(
120       EndpointType::Post,
121       &inserted_post_id.to_string(),
122       &protocol_and_hostname,
123     )?;
124     let updated_post = Post::update(
125       context.pool(),
126       inserted_post_id,
127       &PostUpdateForm::builder().ap_id(Some(apub_id)).build(),
128     )
129     .await
130     .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_post"))?;
131
132     // They like their own post by default
133     let person_id = local_user_view.person.id;
134     let post_id = inserted_post.id;
135     let like_form = PostLikeForm {
136       post_id,
137       person_id,
138       score: 1,
139     };
140
141     PostLike::like(context.pool(), &like_form)
142       .await
143       .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_post"))?;
144
145     // Mark the post as read
146     mark_post_as_read(person_id, post_id, context.pool()).await?;
147
148     if let Some(url) = updated_post.url.clone() {
149       let task = async move {
150         let mut webmention =
151           Webmention::new::<Url>(updated_post.ap_id.clone().into(), url.clone().into())?;
152         webmention.set_checked(true);
153         match webmention
154           .send()
155           .instrument(tracing::info_span!("Sending webmention"))
156           .await
157         {
158           Err(WebmentionError::NoEndpointDiscovered(_)) => Ok(()),
159           Ok(_) => Ok(()),
160           Err(e) => Err(LemmyError::from_error_message(
161             e,
162             "Couldn't send webmention",
163           )),
164         }
165       };
166       if *SYNCHRONOUS_FEDERATION {
167         task.await?;
168       } else {
169         spawn_try_task(task);
170       }
171     };
172
173     build_post_response(context, community_id, person_id, post_id).await
174   }
175 }