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