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