]> Untitled Git - lemmy.git/blob - crates/api_crud/src/comment/create.rs
678bcfb08ab8f22c0fed39fe55517e8760224f0c
[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::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);
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   ActivityChannel::submit_activity(
162     SendActivityData::CreateComment(updated_comment.clone()),
163     &context,
164   )
165   .await?;
166
167   // If its a reply, mark the parent as read
168   if let Some(parent) = parent_opt {
169     let parent_id = parent.id;
170     let comment_reply = CommentReply::read_by_comment(&mut context.pool(), parent_id).await;
171     if let Ok(reply) = comment_reply {
172       CommentReply::update(
173         &mut context.pool(),
174         reply.id,
175         &CommentReplyUpdateForm { read: Some(true) },
176       )
177       .await
178       .with_lemmy_type(LemmyErrorType::CouldntUpdateReplies)?;
179     }
180
181     // If the parent has PersonMentions mark them as read too
182     let person_id = local_user_view.person.id;
183     let person_mention =
184       PersonMention::read_by_comment_and_person(&mut context.pool(), parent_id, person_id).await;
185     if let Ok(mention) = person_mention {
186       PersonMention::update(
187         &mut context.pool(),
188         mention.id,
189         &PersonMentionUpdateForm { read: Some(true) },
190       )
191       .await
192       .with_lemmy_type(LemmyErrorType::CouldntUpdatePersonMentions)?;
193     }
194   }
195
196   Ok(Json(
197     build_comment_response(
198       &context,
199       inserted_comment.id,
200       Some(local_user_view),
201       recipient_ids,
202     )
203     .await?,
204   ))
205 }
206
207 pub fn check_comment_depth(comment: &Comment) -> Result<(), LemmyError> {
208   let path = &comment.path.0;
209   let length = path.split('.').count();
210   if length > MAX_COMMENT_DEPTH_LIMIT {
211     Err(LemmyErrorType::MaxCommentDepthReached)?
212   } else {
213     Ok(())
214   }
215 }