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