1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4 build_response::build_post_response,
6 post::{EditPost, PostResponse},
7 request::fetch_site_data,
8 utils::{check_community_ban, local_site_to_slur_regex, local_user_view_from_jwt},
10 use lemmy_db_schema::{
12 actor_language::CommunityLanguage,
13 local_site::LocalSite,
14 post::{Post, PostUpdateForm},
17 utils::{diesel_option_overwrite, naive_now},
22 slurs::check_slurs_opt,
23 validation::{clean_url_params, is_valid_body_field, is_valid_post_title},
27 #[async_trait::async_trait(?Send)]
28 impl PerformCrud for EditPost {
29 type Response = PostResponse;
31 #[tracing::instrument(skip(context))]
32 async fn perform(&self, context: &Data<LemmyContext>) -> Result<PostResponse, LemmyError> {
33 let data: &EditPost = self;
34 let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
35 let local_site = LocalSite::read(context.pool()).await?;
37 let data_url = data.url.as_ref();
39 // TODO No good way to handle a clear.
40 // Issue link: https://github.com/LemmyNet/lemmy/issues/2287
41 let url = Some(data_url.map(clean_url_params).map(Into::into));
42 let body = diesel_option_overwrite(&data.body);
44 let slur_regex = local_site_to_slur_regex(&local_site);
45 check_slurs_opt(&data.name, &slur_regex)?;
46 check_slurs_opt(&data.body, &slur_regex)?;
48 if let Some(name) = &data.name {
49 is_valid_post_title(name)?;
52 is_valid_body_field(&data.body, true)?;
54 let post_id = data.post_id;
55 let orig_post = Post::read(context.pool(), post_id).await?;
58 local_user_view.person.id,
59 orig_post.community_id,
64 // Verify that only the creator can edit
65 if !Post::is_post_creator(local_user_view.person.id, orig_post.creator_id) {
66 return Err(LemmyError::from_message("no_post_edit_allowed"));
69 // Fetch post links and Pictrs cached image
70 let data_url = data.url.as_ref();
71 let (metadata_res, thumbnail_url) =
72 fetch_site_data(context.client(), context.settings(), data_url).await;
73 let (embed_title, embed_description, embed_video_url) = metadata_res
74 .map(|u| (Some(u.title), Some(u.description), Some(u.embed_video_url)))
77 let language_id = self.language_id;
78 CommunityLanguage::is_allowed_community_language(
81 orig_post.community_id,
85 let post_form = PostUpdateForm::builder()
86 .name(data.name.clone())
90 .embed_title(embed_title)
91 .embed_description(embed_description)
92 .embed_video_url(embed_video_url)
93 .language_id(data.language_id)
94 .thumbnail_url(Some(thumbnail_url))
95 .updated(Some(Some(naive_now())))
98 let post_id = data.post_id;
99 let res = Post::update(context.pool(), post_id, &post_form).await;
100 if let Err(e) = 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 orig_post.community_id,
113 local_user_view.person.id,