]> Untitled Git - lemmy.git/blob - crates/api_crud/src/post/create.rs
implement language tags for site/community in db and api (#2434)
[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   impls::actor_language::default_post_language,
23   source::{
24     actor_language::CommunityLanguage,
25     community::Community,
26     post::{Post, PostForm, PostLike, PostLikeForm},
27   },
28   traits::{Crud, Likeable},
29   utils::diesel_option_overwrite,
30 };
31 use lemmy_db_views_actor::structs::CommunityView;
32 use lemmy_utils::{
33   error::LemmyError,
34   utils::{check_slurs, check_slurs_opt, clean_url_params, is_valid_post_title},
35   ConnectionId,
36 };
37 use lemmy_websocket::{send::send_post_ws_message, LemmyContext, UserOperationCrud};
38 use tracing::{warn, Instrument};
39 use url::Url;
40 use webmention::{Webmention, WebmentionError};
41
42 #[async_trait::async_trait(?Send)]
43 impl PerformCrud for CreatePost {
44   type Response = PostResponse;
45
46   #[tracing::instrument(skip(context, websocket_id))]
47   async fn perform(
48     &self,
49     context: &Data<LemmyContext>,
50     websocket_id: Option<ConnectionId>,
51   ) -> Result<PostResponse, LemmyError> {
52     let data: &CreatePost = self;
53     let local_user_view =
54       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
55
56     let slur_regex = &context.settings().slur_regex();
57     check_slurs(&data.name, slur_regex)?;
58     check_slurs_opt(&data.body, slur_regex)?;
59     honeypot_check(&data.honeypot)?;
60
61     let data_url = data.url.as_ref();
62     let url = Some(data_url.map(clean_url_params).map(Into::into)); // TODO no good way to handle a "clear"
63     let body = diesel_option_overwrite(&data.body);
64
65     if !is_valid_post_title(&data.name) {
66       return Err(LemmyError::from_message("invalid_post_title"));
67     }
68
69     check_community_ban(local_user_view.person.id, data.community_id, context.pool()).await?;
70     check_community_deleted_or_removed(data.community_id, context.pool()).await?;
71
72     let community_id = data.community_id;
73     let community = blocking(context.pool(), move |conn| {
74       Community::read(conn, community_id)
75     })
76     .await??;
77     if community.posting_restricted_to_mods {
78       let community_id = data.community_id;
79       let is_mod = blocking(context.pool(), move |conn| {
80         CommunityView::is_mod_or_admin(conn, local_user_view.local_user.person_id, 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| (Some(u.title), Some(u.description), Some(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         blocking(context.pool(), move |conn| {
99           default_post_language(conn, community_id, local_user_view.local_user.id)
100         })
101         .await??
102       }
103     };
104     blocking(context.pool(), move |conn| {
105       CommunityLanguage::is_allowed_community_language(conn, language_id, community_id)
106     })
107     .await??;
108
109     let post_form = PostForm {
110       name: data.name.trim().to_owned(),
111       url,
112       body,
113       community_id: data.community_id,
114       creator_id: local_user_view.person.id,
115       nsfw: data.nsfw,
116       embed_title,
117       embed_description,
118       embed_video_url,
119       language_id,
120       thumbnail_url: Some(thumbnail_url),
121       ..PostForm::default()
122     };
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_ap_id(conn, inserted_post_id, apub_id)?)
147     })
148     .await?
149     .map_err(|e| e.with_message("couldnt_create_post"))?;
150
151     // They like their own post by default
152     let person_id = local_user_view.person.id;
153     let post_id = inserted_post.id;
154     let like_form = PostLikeForm {
155       post_id,
156       person_id,
157       score: 1,
158     };
159
160     let like = move |conn: &mut _| PostLike::like(conn, &like_form);
161     blocking(context.pool(), like)
162       .await?
163       .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_post"))?;
164
165     // Mark the post as read
166     mark_post_as_read(person_id, post_id, context.pool()).await?;
167
168     if let Some(url) = &updated_post.url {
169       let mut webmention =
170         Webmention::new::<Url>(updated_post.ap_id.clone().into(), url.clone().into())?;
171       webmention.set_checked(true);
172       match webmention
173         .send()
174         .instrument(tracing::info_span!("Sending webmention"))
175         .await
176       {
177         Ok(_) => {}
178         Err(WebmentionError::NoEndpointDiscovered(_)) => {}
179         Err(e) => warn!("Failed to send webmention: {}", e),
180       }
181     }
182
183     let apub_post: ApubPost = updated_post.into();
184     CreateOrUpdatePost::send(
185       apub_post.clone(),
186       &local_user_view.person.clone().into(),
187       CreateOrUpdateType::Create,
188       context,
189     )
190     .await?;
191
192     send_post_ws_message(
193       inserted_post.id,
194       UserOperationCrud::CreatePost,
195       websocket_id,
196       Some(local_user_view.person.id),
197       context,
198     )
199     .await
200   }
201 }