]> Untitled Git - lemmy.git/blob - crates/api/src/comment/mark_as_read.rs
85881f1ca2c325ef5c951415891363f100b49129
[lemmy.git] / crates / api / src / comment / mark_as_read.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   comment::{CommentResponse, MarkCommentAsRead},
5   utils::{blocking, get_local_user_view_from_jwt},
6 };
7 use lemmy_db_schema::source::comment::Comment;
8 use lemmy_db_views::structs::CommentView;
9 use lemmy_utils::{error::LemmyError, ConnectionId};
10 use lemmy_websocket::LemmyContext;
11
12 #[async_trait::async_trait(?Send)]
13 impl Perform for MarkCommentAsRead {
14   type Response = CommentResponse;
15
16   #[tracing::instrument(skip(context, _websocket_id))]
17   async fn perform(
18     &self,
19     context: &Data<LemmyContext>,
20     _websocket_id: Option<ConnectionId>,
21   ) -> Result<CommentResponse, LemmyError> {
22     let data: &MarkCommentAsRead = self;
23     let local_user_view =
24       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
25
26     let comment_id = data.comment_id;
27     let orig_comment = blocking(context.pool(), move |conn| {
28       CommentView::read(conn, comment_id, None)
29     })
30     .await??;
31
32     // Verify that only the recipient can mark as read
33     if local_user_view.person.id != orig_comment.get_recipient_id() {
34       return Err(LemmyError::from_message("no_comment_edit_allowed"));
35     }
36
37     // Do the mark as read
38     let read = data.read;
39     blocking(context.pool(), move |conn| {
40       Comment::update_read(conn, comment_id, read)
41     })
42     .await?
43     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
44
45     // Refetch it
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     let res = CommentResponse {
54       comment_view,
55       recipient_ids: Vec::new(),
56       form_id: None,
57     };
58
59     Ok(res)
60   }
61 }