]> Untitled Git - lemmy.git/blob - crates/api_crud/src/comment/create.rs
Add separate Post check for is_valid_body_field (#3263)
[lemmy.git] / crates / api_crud / src / comment / create.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   build_response::{build_comment_response, send_local_notifs},
5   comment::{CommentResponse, CreateComment},
6   context::LemmyContext,
7   utils::{
8     check_community_ban,
9     check_community_deleted_or_removed,
10     check_post_deleted_or_removed,
11     generate_local_apub_endpoint,
12     get_post,
13     local_site_to_slur_regex,
14     local_user_view_from_jwt,
15     EndpointType,
16   },
17 };
18 use lemmy_db_schema::{
19   source::{
20     actor_language::CommunityLanguage,
21     comment::{Comment, CommentInsertForm, CommentLike, CommentLikeForm, CommentUpdateForm},
22     comment_reply::{CommentReply, CommentReplyUpdateForm},
23     local_site::LocalSite,
24     person_mention::{PersonMention, PersonMentionUpdateForm},
25   },
26   traits::{Crud, Likeable},
27 };
28 use lemmy_utils::{
29   error::LemmyError,
30   utils::{
31     mention::scrape_text_for_mentions,
32     slurs::remove_slurs,
33     validation::is_valid_body_field,
34   },
35 };
36 const MAX_COMMENT_DEPTH_LIMIT: usize = 100;
37
38 #[async_trait::async_trait(?Send)]
39 impl PerformCrud for CreateComment {
40   type Response = CommentResponse;
41
42   #[tracing::instrument(skip(context))]
43   async fn perform(&self, context: &Data<LemmyContext>) -> Result<CommentResponse, LemmyError> {
44     let data: &CreateComment = self;
45     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
46     let local_site = LocalSite::read(context.pool()).await?;
47
48     let content_slurs_removed = remove_slurs(
49       &data.content.clone(),
50       &local_site_to_slur_regex(&local_site),
51     );
52     is_valid_body_field(&Some(content_slurs_removed.clone()), false)?;
53
54     // Check for a community ban
55     let post_id = data.post_id;
56     let post = get_post(post_id, context.pool()).await?;
57     let community_id = post.community_id;
58
59     check_community_ban(local_user_view.person.id, community_id, context.pool()).await?;
60     check_community_deleted_or_removed(community_id, context.pool()).await?;
61     check_post_deleted_or_removed(&post)?;
62
63     // Check if post is locked, no new comments
64     if post.locked {
65       return Err(LemmyError::from_message("locked"));
66     }
67
68     // Fetch the parent, if it exists
69     let parent_opt = if let Some(parent_id) = data.parent_id {
70       Comment::read(context.pool(), parent_id).await.ok()
71     } else {
72       None
73     };
74
75     // If there's a parent_id, check to make sure that comment is in that post
76     // Strange issue where sometimes the post ID of the parent comment is incorrect
77     if let Some(parent) = parent_opt.as_ref() {
78       if parent.post_id != post_id {
79         return Err(LemmyError::from_message("couldnt_create_comment"));
80       }
81       check_comment_depth(parent)?;
82     }
83
84     // if no language is set, copy language from parent post/comment
85     let parent_language = parent_opt
86       .as_ref()
87       .map(|p| p.language_id)
88       .unwrap_or(post.language_id);
89     let language_id = data.language_id.unwrap_or(parent_language);
90
91     CommunityLanguage::is_allowed_community_language(
92       context.pool(),
93       Some(language_id),
94       community_id,
95     )
96     .await?;
97
98     let comment_form = CommentInsertForm::builder()
99       .content(content_slurs_removed.clone())
100       .post_id(data.post_id)
101       .creator_id(local_user_view.person.id)
102       .language_id(Some(language_id))
103       .build();
104
105     // Create the comment
106     let parent_path = parent_opt.clone().map(|t| t.path);
107     let inserted_comment = Comment::create(context.pool(), &comment_form, parent_path.as_ref())
108       .await
109       .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?;
110
111     // Necessary to update the ap_id
112     let inserted_comment_id = inserted_comment.id;
113     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
114
115     let apub_id = generate_local_apub_endpoint(
116       EndpointType::Comment,
117       &inserted_comment_id.to_string(),
118       &protocol_and_hostname,
119     )?;
120     let updated_comment = Comment::update(
121       context.pool(),
122       inserted_comment_id,
123       &CommentUpdateForm::builder().ap_id(Some(apub_id)).build(),
124     )
125     .await
126     .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?;
127
128     // Scan the comment for user mentions, add those rows
129     let mentions = scrape_text_for_mentions(&content_slurs_removed);
130     let recipient_ids = send_local_notifs(
131       mentions,
132       &updated_comment,
133       &local_user_view.person,
134       &post,
135       true,
136       context,
137     )
138     .await?;
139
140     // You like your own comment by default
141     let like_form = CommentLikeForm {
142       comment_id: inserted_comment.id,
143       post_id: post.id,
144       person_id: local_user_view.person.id,
145       score: 1,
146     };
147
148     CommentLike::like(context.pool(), &like_form)
149       .await
150       .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_comment"))?;
151
152     // If its a reply, mark the parent as read
153     if let Some(parent) = parent_opt {
154       let parent_id = parent.id;
155       let comment_reply = CommentReply::read_by_comment(context.pool(), parent_id).await;
156       if let Ok(reply) = comment_reply {
157         CommentReply::update(
158           context.pool(),
159           reply.id,
160           &CommentReplyUpdateForm { read: Some(true) },
161         )
162         .await
163         .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_replies"))?;
164       }
165
166       // If the parent has PersonMentions mark them as read too
167       let person_id = local_user_view.person.id;
168       let person_mention =
169         PersonMention::read_by_comment_and_person(context.pool(), parent_id, person_id).await;
170       if let Ok(mention) = person_mention {
171         PersonMention::update(
172           context.pool(),
173           mention.id,
174           &PersonMentionUpdateForm { read: Some(true) },
175         )
176         .await
177         .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_person_mentions"))?;
178       }
179     }
180
181     build_comment_response(
182       context,
183       inserted_comment.id,
184       Some(local_user_view),
185       self.form_id.clone(),
186       recipient_ids,
187     )
188     .await
189   }
190 }
191
192 pub fn check_comment_depth(comment: &Comment) -> Result<(), LemmyError> {
193   let path = &comment.path.0;
194   let length = path.split('.').collect::<Vec<&str>>().len();
195   if length > MAX_COMMENT_DEPTH_LIMIT {
196     Err(LemmyError::from_message("max_comment_depth_reached"))
197   } else {
198     Ok(())
199   }
200 }