]> Untitled Git - lemmy.git/blob - crates/api/src/comment/save.rs
Extract Activitypub logic into separate library (#2288)
[lemmy.git] / crates / api / src / comment / save.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   comment::{CommentResponse, SaveComment},
5   utils::{blocking, get_local_user_view_from_jwt},
6 };
7 use lemmy_db_schema::{
8   source::comment::{CommentSaved, CommentSavedForm},
9   traits::Saveable,
10 };
11 use lemmy_db_views::structs::CommentView;
12 use lemmy_utils::{error::LemmyError, ConnectionId};
13 use lemmy_websocket::LemmyContext;
14
15 #[async_trait::async_trait(?Send)]
16 impl Perform for SaveComment {
17   type Response = CommentResponse;
18
19   #[tracing::instrument(skip(context, _websocket_id))]
20   async fn perform(
21     &self,
22     context: &Data<LemmyContext>,
23     _websocket_id: Option<ConnectionId>,
24   ) -> Result<CommentResponse, LemmyError> {
25     let data: &SaveComment = self;
26     let local_user_view =
27       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
28
29     let comment_saved_form = CommentSavedForm {
30       comment_id: data.comment_id,
31       person_id: local_user_view.person.id,
32     };
33
34     if data.save {
35       let save_comment = move |conn: &'_ _| CommentSaved::save(conn, &comment_saved_form);
36       blocking(context.pool(), save_comment)
37         .await?
38         .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_comment"))?;
39     } else {
40       let unsave_comment = move |conn: &'_ _| CommentSaved::unsave(conn, &comment_saved_form);
41       blocking(context.pool(), unsave_comment)
42         .await?
43         .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_comment"))?;
44     }
45
46     let comment_id = data.comment_id;
47     let person_id = local_user_view.person.id;
48     let comment_view = blocking(context.pool(), move |conn| {
49       CommentView::read(conn, comment_id, Some(person_id))
50     })
51     .await??;
52
53     Ok(CommentResponse {
54       comment_view,
55       recipient_ids: Vec::new(),
56       form_id: None,
57     })
58   }
59 }