]> Untitled Git - lemmy.git/blob - crates/api/src/post/lock.rs
Merge pull request #2593 from LemmyNet/refactor-notifications
[lemmy.git] / crates / api / src / post / lock.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   context::LemmyContext,
5   post::{LockPost, PostResponse},
6   utils::{
7     check_community_ban,
8     check_community_deleted_or_removed,
9     get_local_user_view_from_jwt,
10     is_mod_or_admin,
11   },
12   websocket::{send::send_post_ws_message, UserOperation},
13 };
14 use lemmy_db_schema::{
15   source::{
16     moderator::{ModLockPost, ModLockPostForm},
17     post::{Post, PostUpdateForm},
18   },
19   traits::Crud,
20 };
21 use lemmy_utils::{error::LemmyError, ConnectionId};
22
23 #[async_trait::async_trait(?Send)]
24 impl Perform for LockPost {
25   type Response = PostResponse;
26
27   #[tracing::instrument(skip(context, websocket_id))]
28   async fn perform(
29     &self,
30     context: &Data<LemmyContext>,
31     websocket_id: Option<ConnectionId>,
32   ) -> Result<PostResponse, LemmyError> {
33     let data: &LockPost = self;
34     let local_user_view =
35       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
36
37     let post_id = data.post_id;
38     let orig_post = Post::read(context.pool(), post_id).await?;
39
40     check_community_ban(
41       local_user_view.person.id,
42       orig_post.community_id,
43       context.pool(),
44     )
45     .await?;
46     check_community_deleted_or_removed(orig_post.community_id, context.pool()).await?;
47
48     // Verify that only the mods can lock
49     is_mod_or_admin(
50       context.pool(),
51       local_user_view.person.id,
52       orig_post.community_id,
53     )
54     .await?;
55
56     // Update the post
57     let post_id = data.post_id;
58     let locked = data.locked;
59     Post::update(
60       context.pool(),
61       post_id,
62       &PostUpdateForm::builder().locked(Some(locked)).build(),
63     )
64     .await?;
65
66     // Mod tables
67     let form = ModLockPostForm {
68       mod_person_id: local_user_view.person.id,
69       post_id: data.post_id,
70       locked: Some(locked),
71     };
72     ModLockPost::create(context.pool(), &form).await?;
73
74     send_post_ws_message(
75       data.post_id,
76       UserOperation::LockPost,
77       websocket_id,
78       Some(local_user_view.person.id),
79       context,
80     )
81     .await
82   }
83 }