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