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