1 use actix_web::web::Data;
2 use lemmy_api_common::{
3 post::{EditPost, PostResponse},
4 request::fetch_site_data,
8 check_community_deleted_or_removed,
9 get_local_user_view_from_jwt,
12 use lemmy_apub::protocol::activities::{
13 create_or_update::post::CreateOrUpdatePost,
16 use lemmy_db_schema::{
17 source::post::{Post, PostForm},
23 utils::{check_slurs_opt, clean_optional_text, clean_url_params, is_valid_post_title},
26 use lemmy_websocket::{send::send_post_ws_message, LemmyContext, UserOperationCrud};
28 use crate::PerformCrud;
30 #[async_trait::async_trait(?Send)]
31 impl PerformCrud for EditPost {
32 type Response = PostResponse;
34 #[tracing::instrument(skip(context, websocket_id))]
37 context: &Data<LemmyContext>,
38 websocket_id: Option<ConnectionId>,
39 ) -> Result<PostResponse, LemmyError> {
40 let data: &EditPost = self;
42 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
44 let slur_regex = &context.settings().slur_regex();
45 check_slurs_opt(&data.name, slur_regex)?;
46 check_slurs_opt(&data.body, slur_regex)?;
48 if let Some(name) = &data.name {
49 if !is_valid_post_title(name) {
50 return Err(LemmyError::from_message("invalid_post_title"));
54 let post_id = data.post_id;
55 let orig_post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
58 local_user_view.person.id,
59 orig_post.community_id,
63 check_community_deleted_or_removed(orig_post.community_id, context.pool()).await?;
65 // Verify that only the creator can edit
66 if !Post::is_post_creator(local_user_view.person.id, orig_post.creator_id) {
67 return Err(LemmyError::from_message("no_post_edit_allowed"));
70 // Fetch post links and Pictrs cached image
71 let data_url = data.url.as_ref();
72 let (metadata_res, pictrs_thumbnail) =
73 fetch_site_data(context.client(), &context.settings(), data_url).await;
74 let (embed_title, embed_description, embed_html) = metadata_res
75 .map(|u| (u.title, u.description, u.html))
76 .unwrap_or((None, None, None));
78 let post_form = PostForm {
79 creator_id: orig_post.creator_id.to_owned(),
80 community_id: orig_post.community_id,
81 name: data.name.to_owned().unwrap_or(orig_post.name),
82 url: data_url.map(|u| clean_url_params(u.to_owned()).into()),
83 body: clean_optional_text(&data.body),
85 updated: Some(naive_now()),
89 thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
93 let post_id = data.post_id;
94 let res = blocking(context.pool(), move |conn| {
95 Post::update(conn, post_id, &post_form)
98 let updated_post: Post = match res {
101 let err_type = if e.to_string() == "value too long for type character varying(200)" {
102 "post_title_too_long"
104 "couldnt_update_post"
107 return Err(LemmyError::from_error_message(e, err_type));
112 CreateOrUpdatePost::send(
114 &local_user_view.person.clone().into(),
115 CreateOrUpdateType::Update,
120 send_post_ws_message(
122 UserOperationCrud::EditPost,
124 Some(local_user_view.person.id),