1 use actix_web::web::{Data, Json, Query};
2 use lemmy_api_common::{
4 post::{GetPost, GetPostResponse},
6 check_private_instance,
8 local_user_view_from_jwt_opt,
12 use lemmy_db_schema::{
13 aggregates::structs::{PersonPostAggregates, PersonPostAggregatesForm},
14 source::{comment::Comment, local_site::LocalSite, post::Post},
17 use lemmy_db_views::{post_view::PostQuery, structs::PostView};
18 use lemmy_db_views_actor::structs::{CommunityModeratorView, CommunityView};
19 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
21 #[tracing::instrument(skip(context))]
22 pub async fn get_post(
24 context: Data<LemmyContext>,
25 ) -> Result<Json<GetPostResponse>, LemmyError> {
26 let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), &context).await;
27 let local_site = LocalSite::read(&mut context.pool()).await?;
29 check_private_instance(&local_user_view, &local_site)?;
31 let person_id = local_user_view.as_ref().map(|u| u.person.id);
33 // I'd prefer fetching the post_view by a comment join, but it adds a lot of boilerplate
34 let post_id = if let Some(id) = data.id {
36 } else if let Some(comment_id) = data.comment_id {
37 Comment::read(&mut context.pool(), comment_id)
39 .with_lemmy_type(LemmyErrorType::CouldntFindPost)?
42 Err(LemmyErrorType::CouldntFindPost)?
45 // Check to see if the person is a mod or admin, to show deleted / removed
46 let community_id = Post::read(&mut context.pool(), post_id).await?.community_id;
47 let is_mod_or_admin = is_mod_or_admin_opt(
49 local_user_view.as_ref(),
55 let post_view = PostView::read(
59 Some(is_mod_or_admin),
62 .with_lemmy_type(LemmyErrorType::CouldntFindPost)?;
64 // Mark the post as read
65 let post_id = post_view.post.id;
66 if let Some(person_id) = person_id {
67 mark_post_as_read(person_id, post_id, &mut context.pool()).await?;
70 // Necessary for the sidebar subscribed
71 let community_view = CommunityView::read(
75 Some(is_mod_or_admin),
78 .with_lemmy_type(LemmyErrorType::CouldntFindCommunity)?;
80 // Insert into PersonPostAggregates
81 // to update the read_comments count
82 if let Some(person_id) = person_id {
83 let read_comments = post_view.counts.comments;
84 let person_post_agg_form = PersonPostAggregatesForm {
88 ..PersonPostAggregatesForm::default()
90 PersonPostAggregates::upsert(&mut context.pool(), &person_post_agg_form)
92 .with_lemmy_type(LemmyErrorType::CouldntFindPost)?;
95 let moderators = CommunityModeratorView::for_community(&mut context.pool(), community_id).await?;
97 // Fetch the cross_posts
98 let cross_posts = if let Some(url) = &post_view.post.url {
99 let mut x_posts = PostQuery {
100 url_search: Some(url.inner().as_str().into()),
103 .list(&mut context.pool())
106 // Don't return this post as one of the cross_posts
107 x_posts.retain(|x| x.post.id != post_id);
114 Ok(Json(GetPostResponse {