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