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