]> Untitled Git - lemmy.git/blob - crates/api_crud/src/post/create.rs
46d4a7f644befeea10225eada2420b994ff186b8
[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   generate_local_apub_endpoint,
5   post::{CreatePost, PostResponse},
6   request::fetch_site_data,
7   utils::{
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   websocket::{send::send_post_ws_message, UserOperationCrud},
16   EndpointType,
17   LemmyContext,
18 };
19 use lemmy_apub::{
20   objects::post::ApubPost,
21   protocol::activities::{create_or_update::page::CreateOrUpdatePage, CreateOrUpdateType},
22 };
23 use lemmy_db_schema::{
24   impls::actor_language::default_post_language,
25   source::{
26     actor_language::CommunityLanguage,
27     community::Community,
28     local_site::LocalSite,
29     post::{Post, PostInsertForm, PostLike, PostLikeForm, PostUpdateForm},
30   },
31   traits::{Crud, Likeable},
32 };
33 use lemmy_db_views_actor::structs::CommunityView;
34 use lemmy_utils::{
35   error::LemmyError,
36   utils::{check_slurs, check_slurs_opt, clean_url_params, is_valid_post_title},
37   ConnectionId,
38 };
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 = LocalSite::read(context.pool()).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 = Community::read(context.pool(), community_id).await?;
75     if community.posting_restricted_to_mods {
76       let community_id = data.community_id;
77       let is_mod = CommunityView::is_mod_or_admin(
78         context.pool(),
79         local_user_view.local_user.person_id,
80         community_id,
81       )
82       .await?;
83       if !is_mod {
84         return Err(LemmyError::from_message("only_mods_can_post_in_community"));
85       }
86     }
87
88     // Fetch post links and pictrs cached image
89     let (metadata_res, thumbnail_url) =
90       fetch_site_data(context.client(), context.settings(), data_url).await;
91     let (embed_title, embed_description, embed_video_url) = metadata_res
92       .map(|u| (u.title, u.description, u.embed_video_url))
93       .unwrap_or_default();
94
95     let language_id = match data.language_id {
96       Some(lid) => Some(lid),
97       None => {
98         default_post_language(context.pool(), community_id, local_user_view.local_user.id).await?
99       }
100     };
101     CommunityLanguage::is_allowed_community_language(context.pool(), language_id, community_id)
102       .await?;
103
104     let post_form = PostInsertForm::builder()
105       .name(data.name.trim().to_owned())
106       .url(url)
107       .body(data.body.clone())
108       .community_id(data.community_id)
109       .creator_id(local_user_view.person.id)
110       .nsfw(data.nsfw)
111       .embed_title(embed_title)
112       .embed_description(embed_description)
113       .embed_video_url(embed_video_url)
114       .language_id(language_id)
115       .thumbnail_url(thumbnail_url)
116       .build();
117
118     let inserted_post = match Post::create(context.pool(), &post_form).await {
119       Ok(post) => post,
120       Err(e) => {
121         let err_type = if e.to_string() == "value too long for type character varying(200)" {
122           "post_title_too_long"
123         } else {
124           "couldnt_create_post"
125         };
126
127         return Err(LemmyError::from_error_message(e, err_type));
128       }
129     };
130
131     let inserted_post_id = inserted_post.id;
132     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
133     let apub_id = generate_local_apub_endpoint(
134       EndpointType::Post,
135       &inserted_post_id.to_string(),
136       &protocol_and_hostname,
137     )?;
138     let updated_post = Post::update(
139       context.pool(),
140       inserted_post_id,
141       &PostUpdateForm::builder().ap_id(Some(apub_id)).build(),
142     )
143     .await
144     .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_post"))?;
145
146     // They like their own post by default
147     let person_id = local_user_view.person.id;
148     let post_id = inserted_post.id;
149     let like_form = PostLikeForm {
150       post_id,
151       person_id,
152       score: 1,
153     };
154
155     PostLike::like(context.pool(), &like_form)
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     CreateOrUpdatePage::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 }