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