]> Untitled Git - lemmy.git/blob - crates/api/src/comment/like.rs
Error enum fixed (#3487)
[lemmy.git] / crates / api / src / comment / like.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   build_response::build_comment_response,
5   comment::{CommentResponse, CreateCommentLike},
6   context::LemmyContext,
7   utils::{check_community_ban, check_downvotes_enabled, local_user_view_from_jwt},
8 };
9 use lemmy_db_schema::{
10   newtypes::LocalUserId,
11   source::{
12     comment::{CommentLike, CommentLikeForm},
13     comment_reply::CommentReply,
14     local_site::LocalSite,
15   },
16   traits::Likeable,
17 };
18 use lemmy_db_views::structs::{CommentView, LocalUserView};
19 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
20
21 #[async_trait::async_trait(?Send)]
22 impl Perform for CreateCommentLike {
23   type Response = CommentResponse;
24
25   #[tracing::instrument(skip(context))]
26   async fn perform(&self, context: &Data<LemmyContext>) -> Result<CommentResponse, LemmyError> {
27     let data: &CreateCommentLike = self;
28     let local_site = LocalSite::read(context.pool()).await?;
29     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
30
31     let mut recipient_ids = Vec::<LocalUserId>::new();
32
33     // Don't do a downvote if site has downvotes disabled
34     check_downvotes_enabled(data.score, &local_site)?;
35
36     let comment_id = data.comment_id;
37     let orig_comment = CommentView::read(context.pool(), comment_id, None).await?;
38
39     check_community_ban(
40       local_user_view.person.id,
41       orig_comment.community.id,
42       context.pool(),
43     )
44     .await?;
45
46     // Add parent poster or commenter to recipients
47     let comment_reply = CommentReply::read_by_comment(context.pool(), comment_id).await;
48     if let Ok(reply) = comment_reply {
49       let recipient_id = reply.recipient_id;
50       if let Ok(local_recipient) = LocalUserView::read_person(context.pool(), recipient_id).await {
51         recipient_ids.push(local_recipient.local_user.id);
52       }
53     }
54
55     let like_form = CommentLikeForm {
56       comment_id: data.comment_id,
57       post_id: orig_comment.post.id,
58       person_id: local_user_view.person.id,
59       score: data.score,
60     };
61
62     // Remove any likes first
63     let person_id = local_user_view.person.id;
64
65     CommentLike::remove(context.pool(), person_id, comment_id).await?;
66
67     // Only add the like if the score isnt 0
68     let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1);
69     if do_add {
70       CommentLike::like(context.pool(), &like_form)
71         .await
72         .with_lemmy_type(LemmyErrorType::CouldntLikeComment)?;
73     }
74
75     build_comment_response(
76       context,
77       comment_id,
78       Some(local_user_view),
79       None,
80       recipient_ids,
81     )
82     .await
83   }
84 }