]> Untitled Git - lemmy.git/blob - crates/api_crud/src/comment/create.rs
f3effaad6cf9d1e3bbc009dabbf0705b13ed5dbc
[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   utils::{
6     blocking,
7     check_community_ban,
8     check_community_deleted_or_removed,
9     check_post_deleted_or_removed,
10     get_local_user_view_from_jwt,
11     get_post,
12   },
13 };
14 use lemmy_apub::{
15   generate_local_apub_endpoint,
16   objects::comment::ApubComment,
17   protocol::activities::{create_or_update::comment::CreateOrUpdateComment, CreateOrUpdateType},
18   EndpointType,
19 };
20 use lemmy_db_schema::{
21   source::{
22     actor_language::CommunityLanguage,
23     comment::{Comment, CommentForm, CommentLike, CommentLikeForm},
24     comment_reply::CommentReply,
25     person_mention::PersonMention,
26   },
27   traits::{Crud, Likeable},
28 };
29 use lemmy_utils::{
30   error::LemmyError,
31   utils::{remove_slurs, scrape_text_for_mentions},
32   ConnectionId,
33 };
34 use lemmy_websocket::{
35   send::{send_comment_ws_message, send_local_notifs},
36   LemmyContext,
37   UserOperationCrud,
38 };
39
40 #[async_trait::async_trait(?Send)]
41 impl PerformCrud for CreateComment {
42   type Response = CommentResponse;
43
44   #[tracing::instrument(skip(context, websocket_id))]
45   async fn perform(
46     &self,
47     context: &Data<LemmyContext>,
48     websocket_id: Option<ConnectionId>,
49   ) -> Result<CommentResponse, LemmyError> {
50     let data: &CreateComment = self;
51     let local_user_view =
52       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
53
54     let content_slurs_removed =
55       remove_slurs(&data.content.to_owned(), &context.settings().slur_regex());
56
57     // Check for a community ban
58     let post_id = data.post_id;
59     let post = get_post(post_id, context.pool()).await?;
60     let community_id = post.community_id;
61
62     check_community_ban(local_user_view.person.id, community_id, context.pool()).await?;
63     check_community_deleted_or_removed(community_id, 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(LemmyError::from_message("locked"));
69     }
70
71     // Fetch the parent, if it exists
72     let parent_opt = if let Some(parent_id) = data.parent_id {
73       blocking(context.pool(), move |conn| Comment::read(conn, parent_id))
74         .await?
75         .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     blocking(context.pool(), move |conn| {
96       CommunityLanguage::is_allowed_community_language(conn, Some(language_id), community_id)
97     })
98     .await??;
99
100     let comment_form = CommentForm {
101       content: content_slurs_removed,
102       post_id: data.post_id,
103       creator_id: local_user_view.person.id,
104       language_id: Some(language_id),
105       ..CommentForm::default()
106     };
107
108     // Create the comment
109     let comment_form2 = comment_form.clone();
110     let parent_path = parent_opt.to_owned().map(|t| t.path);
111     let inserted_comment = blocking(context.pool(), move |conn| {
112       Comment::create(conn, &comment_form2, parent_path.as_ref())
113     })
114     .await?
115     .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?;
116
117     // Necessary to update the ap_id
118     let inserted_comment_id = inserted_comment.id;
119     let protocol_and_hostname = context.settings().get_protocol_and_hostname();
120
121     let updated_comment: Comment =
122       blocking(context.pool(), move |conn| -> Result<Comment, LemmyError> {
123         let apub_id = generate_local_apub_endpoint(
124           EndpointType::Comment,
125           &inserted_comment_id.to_string(),
126           &protocol_and_hostname,
127         )?;
128         Ok(Comment::update_ap_id(conn, inserted_comment_id, apub_id)?)
129       })
130       .await?
131       .map_err(|e| e.with_message("couldnt_create_comment"))?;
132
133     // Scan the comment for user mentions, add those rows
134     let post_id = post.id;
135     let mentions = scrape_text_for_mentions(&comment_form.content);
136     let recipient_ids = send_local_notifs(
137       mentions,
138       &updated_comment,
139       &local_user_view.person,
140       &post,
141       true,
142       context,
143     )
144     .await?;
145
146     // You like your own comment by default
147     let like_form = CommentLikeForm {
148       comment_id: inserted_comment.id,
149       post_id,
150       person_id: local_user_view.person.id,
151       score: 1,
152     };
153
154     let like = move |conn: &mut _| CommentLike::like(conn, &like_form);
155     blocking(context.pool(), like)
156       .await?
157       .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_comment"))?;
158
159     let apub_comment: ApubComment = updated_comment.into();
160     CreateOrUpdateComment::send(
161       apub_comment.clone(),
162       &local_user_view.person.clone().into(),
163       CreateOrUpdateType::Create,
164       context,
165       &mut 0,
166     )
167     .await?;
168
169     // If its a reply, mark the parent as read
170     if let Some(parent) = parent_opt {
171       let parent_id = parent.id;
172       let comment_reply = blocking(context.pool(), move |conn| {
173         CommentReply::read_by_comment(conn, parent_id)
174       })
175       .await?;
176       if let Ok(reply) = comment_reply {
177         blocking(context.pool(), move |conn| {
178           CommentReply::update_read(conn, reply.id, true)
179         })
180         .await?
181         .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_replies"))?;
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 = blocking(context.pool(), move |conn| {
187         PersonMention::read_by_comment_and_person(conn, parent_id, person_id)
188       })
189       .await?;
190       if let Ok(mention) = person_mention {
191         blocking(context.pool(), move |conn| {
192           PersonMention::update_read(conn, mention.id, true)
193         })
194         .await?
195         .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_person_mentions"))?;
196       }
197     }
198
199     send_comment_ws_message(
200       inserted_comment.id,
201       UserOperationCrud::CreateComment,
202       websocket_id,
203       data.form_id.to_owned(),
204       Some(local_user_view.person.id),
205       recipient_ids,
206       context,
207     )
208     .await
209   }
210 }