]> Untitled Git - lemmy.git/blob - crates/api/src/post/save.rs
973b99de9e422638b2d08361b68e8bf0f9557898
[lemmy.git] / crates / api / src / post / save.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   blocking,
5   get_local_user_view_from_jwt,
6   mark_post_as_read,
7   post::{PostResponse, SavePost},
8 };
9 use lemmy_db_schema::{
10   source::post::{PostSaved, PostSavedForm},
11   traits::Saveable,
12 };
13 use lemmy_db_views::post_view::PostView;
14 use lemmy_utils::{ConnectionId, LemmyError};
15 use lemmy_websocket::LemmyContext;
16
17 #[async_trait::async_trait(?Send)]
18 impl Perform for SavePost {
19   type Response = PostResponse;
20
21   #[tracing::instrument(skip(context, _websocket_id))]
22   async fn perform(
23     &self,
24     context: &Data<LemmyContext>,
25     _websocket_id: Option<ConnectionId>,
26   ) -> Result<PostResponse, LemmyError> {
27     let data: &SavePost = self;
28     let local_user_view =
29       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
30
31     let post_saved_form = PostSavedForm {
32       post_id: data.post_id,
33       person_id: local_user_view.person.id,
34     };
35
36     if data.save {
37       let save = move |conn: &'_ _| PostSaved::save(conn, &post_saved_form);
38       blocking(context.pool(), save)
39         .await?
40         .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_post"))?;
41     } else {
42       let unsave = move |conn: &'_ _| PostSaved::unsave(conn, &post_saved_form);
43       blocking(context.pool(), unsave)
44         .await?
45         .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_post"))?;
46     }
47
48     let post_id = data.post_id;
49     let person_id = local_user_view.person.id;
50     let post_view = blocking(context.pool(), move |conn| {
51       PostView::read(conn, post_id, Some(person_id))
52     })
53     .await??;
54
55     // Mark the post as read
56     mark_post_as_read(person_id, post_id, context.pool()).await?;
57
58     Ok(PostResponse { post_view })
59   }
60 }