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