]> Untitled Git - lemmy.git/blob - crates/api/src/local_user/notifications/mark_all_read.rs
Split apart api files (#2216)
[lemmy.git] / crates / api / src / local_user / notifications / mark_all_read.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   person::{GetRepliesResponse, MarkAllAsRead},
7 };
8 use lemmy_db_schema::source::{
9   comment::Comment,
10   person_mention::PersonMention,
11   private_message::PrivateMessage,
12 };
13 use lemmy_db_views::comment_view::CommentQueryBuilder;
14 use lemmy_utils::{ConnectionId, LemmyError};
15 use lemmy_websocket::LemmyContext;
16
17 #[async_trait::async_trait(?Send)]
18 impl Perform for MarkAllAsRead {
19   type Response = GetRepliesResponse;
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<GetRepliesResponse, LemmyError> {
27     let data: &MarkAllAsRead = self;
28     let local_user_view =
29       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
30
31     let person_id = local_user_view.person.id;
32     let replies = blocking(context.pool(), move |conn| {
33       CommentQueryBuilder::create(conn)
34         .my_person_id(person_id)
35         .recipient_id(person_id)
36         .unread_only(true)
37         .page(1)
38         .limit(999)
39         .list()
40     })
41     .await??;
42
43     // TODO: this should probably be a bulk operation
44     // Not easy to do as a bulk operation,
45     // because recipient_id isn't in the comment table
46     for comment_view in &replies {
47       let reply_id = comment_view.comment.id;
48       let mark_as_read = move |conn: &'_ _| Comment::update_read(conn, reply_id, true);
49       blocking(context.pool(), mark_as_read)
50         .await?
51         .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
52     }
53
54     // Mark all user mentions as read
55     let update_person_mentions =
56       move |conn: &'_ _| PersonMention::mark_all_as_read(conn, person_id);
57     blocking(context.pool(), update_person_mentions)
58       .await?
59       .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?;
60
61     // Mark all private_messages as read
62     let update_pm = move |conn: &'_ _| PrivateMessage::mark_all_as_read(conn, person_id);
63     blocking(context.pool(), update_pm)
64       .await?
65       .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?;
66
67     Ok(GetRepliesResponse { replies: vec![] })
68   }
69 }