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