1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
5 post::{GetPost, GetPostResponse},
7 check_private_instance,
8 get_local_user_view_from_jwt_opt,
12 websocket::handlers::online_users::GetPostUsersOnline,
14 use lemmy_db_schema::{
15 aggregates::structs::{PersonPostAggregates, PersonPostAggregatesForm},
16 source::{comment::Comment, local_site::LocalSite, post::Post},
19 use lemmy_db_views::structs::PostView;
20 use lemmy_db_views_actor::structs::{CommunityModeratorView, CommunityView};
21 use lemmy_utils::{error::LemmyError, ConnectionId};
23 #[async_trait::async_trait(?Send)]
24 impl PerformCrud for GetPost {
25 type Response = GetPostResponse;
27 #[tracing::instrument(skip(context, _websocket_id))]
30 context: &Data<LemmyContext>,
31 _websocket_id: Option<ConnectionId>,
32 ) -> Result<GetPostResponse, LemmyError> {
33 let data: &GetPost = self;
35 get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
37 let local_site = LocalSite::read(context.pool()).await?;
39 check_private_instance(&local_user_view, &local_site)?;
41 let person_id = local_user_view.as_ref().map(|u| u.person.id);
43 // I'd prefer fetching the post_view by a comment join, but it adds a lot of boilerplate
44 let post_id = if let Some(id) = data.id {
46 } else if let Some(comment_id) = data.comment_id {
47 Comment::read(context.pool(), comment_id)
49 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))?
52 Err(LemmyError::from_message("couldnt_find_post"))?
55 // Check to see if the person is a mod or admin, to show deleted / removed
56 let community_id = Post::read(context.pool(), post_id).await?.community_id;
58 is_mod_or_admin_opt(context.pool(), local_user_view.as_ref(), Some(community_id))
62 let post_view = PostView::read(context.pool(), post_id, person_id, Some(is_mod_or_admin))
64 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))?;
66 // Mark the post as read
67 let post_id = post_view.post.id;
68 if let Some(person_id) = person_id {
69 mark_post_as_read(person_id, post_id, context.pool()).await?;
72 // Necessary for the sidebar subscribed
73 let community_view = CommunityView::read(
77 Some(is_mod_or_admin),
80 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
82 // Insert into PersonPostAggregates
83 // to update the read_comments count
84 if let Some(person_id) = person_id {
85 let read_comments = post_view.counts.comments;
86 let person_post_agg_form = PersonPostAggregatesForm {
90 ..PersonPostAggregatesForm::default()
92 PersonPostAggregates::upsert(context.pool(), &person_post_agg_form)
94 .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))?;
97 let moderators = CommunityModeratorView::for_community(context.pool(), community_id).await?;
101 .send(GetPostUsersOnline { post_id })