1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
5 post::{GetPost, GetPostResponse},
7 check_private_instance,
9 local_user_view_from_jwt_opt,
13 use lemmy_db_schema::{
14 aggregates::structs::{PersonPostAggregates, PersonPostAggregatesForm},
15 source::{comment::Comment, local_site::LocalSite, post::Post},
18 use lemmy_db_views::{post_view::PostQuery, structs::PostView};
19 use lemmy_db_views_actor::structs::{CommunityModeratorView, CommunityView};
20 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
22 #[async_trait::async_trait(?Send)]
23 impl PerformCrud for GetPost {
24 type Response = GetPostResponse;
26 #[tracing::instrument(skip(context))]
27 async fn perform(&self, context: &Data<LemmyContext>) -> Result<GetPostResponse, LemmyError> {
28 let data: &GetPost = self;
29 let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), context).await;
30 let local_site = LocalSite::read(context.pool()).await?;
32 check_private_instance(&local_user_view, &local_site)?;
34 let person_id = local_user_view.as_ref().map(|u| u.person.id);
36 // I'd prefer fetching the post_view by a comment join, but it adds a lot of boilerplate
37 let post_id = if let Some(id) = data.id {
39 } else if let Some(comment_id) = data.comment_id {
40 Comment::read(context.pool(), comment_id)
42 .with_lemmy_type(LemmyErrorType::CouldntFindPost)?
45 Err(LemmyErrorType::CouldntFindPost)?
48 // Check to see if the person is a mod or admin, to show deleted / removed
49 let community_id = Post::read(context.pool(), post_id).await?.community_id;
51 is_mod_or_admin_opt(context.pool(), local_user_view.as_ref(), Some(community_id))
55 let post_view = PostView::read(context.pool(), post_id, person_id, Some(is_mod_or_admin))
57 .with_lemmy_type(LemmyErrorType::CouldntFindPost)?;
59 // Mark the post as read
60 let post_id = post_view.post.id;
61 if let Some(person_id) = person_id {
62 mark_post_as_read(person_id, post_id, context.pool()).await?;
65 // Necessary for the sidebar subscribed
66 let community_view = CommunityView::read(
70 Some(is_mod_or_admin),
73 .with_lemmy_type(LemmyErrorType::CouldntFindCommunity)?;
75 // Insert into PersonPostAggregates
76 // to update the read_comments count
77 if let Some(person_id) = person_id {
78 let read_comments = post_view.counts.comments;
79 let person_post_agg_form = PersonPostAggregatesForm {
83 ..PersonPostAggregatesForm::default()
85 PersonPostAggregates::upsert(context.pool(), &person_post_agg_form)
87 .with_lemmy_type(LemmyErrorType::CouldntFindPost)?;
90 let moderators = CommunityModeratorView::for_community(context.pool(), community_id).await?;
92 // Fetch the cross_posts
93 let cross_posts = if let Some(url) = &post_view.post.url {
94 let mut x_posts = PostQuery::builder()
96 .url_search(Some(url.inner().as_str().into()))
101 // Don't return this post as one of the cross_posts
102 x_posts.retain(|x| x.post.id != post_id);