]> Untitled Git - lemmy.git/blob - crates/api/src/post/feature.rs
Making the chat server an actor. (#2793)
[lemmy.git] / crates / api / src / post / feature.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   context::LemmyContext,
5   post::{FeaturePost, PostResponse},
6   utils::{
7     check_community_ban,
8     check_community_deleted_or_removed,
9     get_local_user_view_from_jwt,
10     is_admin,
11     is_mod_or_admin,
12   },
13   websocket::UserOperation,
14 };
15 use lemmy_db_schema::{
16   source::{
17     moderator::{ModFeaturePost, ModFeaturePostForm},
18     post::{Post, PostUpdateForm},
19   },
20   traits::Crud,
21   PostFeatureType,
22 };
23 use lemmy_utils::{error::LemmyError, ConnectionId};
24
25 #[async_trait::async_trait(?Send)]
26 impl Perform for FeaturePost {
27   type Response = PostResponse;
28
29   #[tracing::instrument(skip(context, websocket_id))]
30   async fn perform(
31     &self,
32     context: &Data<LemmyContext>,
33     websocket_id: Option<ConnectionId>,
34   ) -> Result<PostResponse, LemmyError> {
35     let data: &FeaturePost = self;
36     let local_user_view =
37       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
38
39     let post_id = data.post_id;
40     let orig_post = Post::read(context.pool(), post_id).await?;
41
42     check_community_ban(
43       local_user_view.person.id,
44       orig_post.community_id,
45       context.pool(),
46     )
47     .await?;
48     check_community_deleted_or_removed(orig_post.community_id, context.pool()).await?;
49
50     if data.feature_type == PostFeatureType::Community {
51       // Verify that only the mods can feature in community
52       is_mod_or_admin(
53         context.pool(),
54         local_user_view.person.id,
55         orig_post.community_id,
56       )
57       .await?;
58     } else {
59       is_admin(&local_user_view)?;
60     }
61
62     // Update the post
63     let post_id = data.post_id;
64     let new_post: PostUpdateForm = if data.feature_type == PostFeatureType::Community {
65       PostUpdateForm::builder()
66         .featured_community(Some(data.featured))
67         .build()
68     } else {
69       PostUpdateForm::builder()
70         .featured_local(Some(data.featured))
71         .build()
72     };
73     Post::update(context.pool(), post_id, &new_post).await?;
74
75     // Mod tables
76     let form = ModFeaturePostForm {
77       mod_person_id: local_user_view.person.id,
78       post_id: data.post_id,
79       featured: data.featured,
80       is_featured_community: data.feature_type == PostFeatureType::Community,
81     };
82
83     ModFeaturePost::create(context.pool(), &form).await?;
84
85     context
86       .send_post_ws_message(
87         &UserOperation::FeaturePost,
88         data.post_id,
89         websocket_id,
90         Some(local_user_view.person.id),
91       )
92       .await
93   }
94 }