]> Untitled Git - lemmy.git/blob - crates/api/src/community.rs
Merge pull request #1710 from LemmyNet/mod_transfer_community
[lemmy.git] / crates / api / src / community.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use anyhow::Context;
4 use lemmy_api_common::{
5   blocking,
6   check_community_ban,
7   community::*,
8   get_local_user_view_from_jwt,
9   is_mod_or_admin,
10 };
11 use lemmy_apub::{
12   activities::following::{
13     follow::FollowCommunity as FollowCommunityApub,
14     undo::UndoFollowCommunity,
15   },
16   CommunityType,
17 };
18 use lemmy_db_queries::{
19   source::{comment::Comment_, community::CommunityModerator_, post::Post_},
20   Bannable,
21   Crud,
22   Followable,
23   Joinable,
24 };
25 use lemmy_db_schema::source::{
26   comment::Comment,
27   community::*,
28   moderator::*,
29   person::Person,
30   post::Post,
31   site::*,
32 };
33 use lemmy_db_views::comment_view::CommentQueryBuilder;
34 use lemmy_db_views_actor::{
35   community_moderator_view::CommunityModeratorView,
36   community_view::CommunityView,
37   person_view::PersonViewSafe,
38 };
39 use lemmy_utils::{location_info, utils::naive_from_unix, ApiError, ConnectionId, LemmyError};
40 use lemmy_websocket::{messages::SendCommunityRoomMessage, LemmyContext, UserOperation};
41
42 #[async_trait::async_trait(?Send)]
43 impl Perform for FollowCommunity {
44   type Response = CommunityResponse;
45
46   async fn perform(
47     &self,
48     context: &Data<LemmyContext>,
49     _websocket_id: Option<ConnectionId>,
50   ) -> Result<CommunityResponse, LemmyError> {
51     let data: &FollowCommunity = self;
52     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
53
54     let community_id = data.community_id;
55     let community = blocking(context.pool(), move |conn| {
56       Community::read(conn, community_id)
57     })
58     .await??;
59     let community_follower_form = CommunityFollowerForm {
60       community_id: data.community_id,
61       person_id: local_user_view.person.id,
62       pending: false,
63     };
64
65     if community.local {
66       if data.follow {
67         check_community_ban(local_user_view.person.id, community_id, context.pool()).await?;
68
69         let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
70         if blocking(context.pool(), follow).await?.is_err() {
71           return Err(ApiError::err("community_follower_already_exists").into());
72         }
73       } else {
74         let unfollow =
75           move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
76         if blocking(context.pool(), unfollow).await?.is_err() {
77           return Err(ApiError::err("community_follower_already_exists").into());
78         }
79       }
80     } else if data.follow {
81       // Dont actually add to the community followers here, because you need
82       // to wait for the accept
83       FollowCommunityApub::send(&local_user_view.person, &community, context).await?;
84     } else {
85       UndoFollowCommunity::send(&local_user_view.person, &community, context).await?;
86       let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
87       if blocking(context.pool(), unfollow).await?.is_err() {
88         return Err(ApiError::err("community_follower_already_exists").into());
89       }
90     }
91
92     let community_id = data.community_id;
93     let person_id = local_user_view.person.id;
94     let mut community_view = blocking(context.pool(), move |conn| {
95       CommunityView::read(conn, community_id, Some(person_id))
96     })
97     .await??;
98
99     // TODO: this needs to return a "pending" state, until Accept is received from the remote server
100     // For now, just assume that remote follows are accepted.
101     // Otherwise, the subscribed will be null
102     if !community.local {
103       community_view.subscribed = data.follow;
104     }
105
106     Ok(CommunityResponse { community_view })
107   }
108 }
109
110 #[async_trait::async_trait(?Send)]
111 impl Perform for BanFromCommunity {
112   type Response = BanFromCommunityResponse;
113
114   async fn perform(
115     &self,
116     context: &Data<LemmyContext>,
117     websocket_id: Option<ConnectionId>,
118   ) -> Result<BanFromCommunityResponse, LemmyError> {
119     let data: &BanFromCommunity = self;
120     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
121
122     let community_id = data.community_id;
123     let banned_person_id = data.person_id;
124
125     // Verify that only mods or admins can ban
126     is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
127
128     let community_user_ban_form = CommunityPersonBanForm {
129       community_id: data.community_id,
130       person_id: data.person_id,
131     };
132
133     let community = blocking(context.pool(), move |conn: &'_ _| {
134       Community::read(conn, community_id)
135     })
136     .await??;
137     let banned_person = blocking(context.pool(), move |conn: &'_ _| {
138       Person::read(conn, banned_person_id)
139     })
140     .await??;
141
142     if data.ban {
143       let ban = move |conn: &'_ _| CommunityPersonBan::ban(conn, &community_user_ban_form);
144       if blocking(context.pool(), ban).await?.is_err() {
145         return Err(ApiError::err("community_user_already_banned").into());
146       }
147
148       // Also unsubscribe them from the community, if they are subscribed
149       let community_follower_form = CommunityFollowerForm {
150         community_id: data.community_id,
151         person_id: banned_person_id,
152         pending: false,
153       };
154       blocking(context.pool(), move |conn: &'_ _| {
155         CommunityFollower::unfollow(conn, &community_follower_form)
156       })
157       .await?
158       .ok();
159
160       community
161         .send_block_user(&local_user_view.person, banned_person, context)
162         .await?;
163     } else {
164       let unban = move |conn: &'_ _| CommunityPersonBan::unban(conn, &community_user_ban_form);
165       if blocking(context.pool(), unban).await?.is_err() {
166         return Err(ApiError::err("community_user_already_banned").into());
167       }
168       community
169         .send_undo_block_user(&local_user_view.person, banned_person, context)
170         .await?;
171     }
172
173     // Remove/Restore their data if that's desired
174     if data.remove_data.unwrap_or(false) {
175       // Posts
176       blocking(context.pool(), move |conn: &'_ _| {
177         Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
178       })
179       .await??;
180
181       // Comments
182       // TODO Diesel doesn't allow updates with joins, so this has to be a loop
183       let comments = blocking(context.pool(), move |conn| {
184         CommentQueryBuilder::create(conn)
185           .creator_id(banned_person_id)
186           .community_id(community_id)
187           .limit(std::i64::MAX)
188           .list()
189       })
190       .await??;
191
192       for comment_view in &comments {
193         let comment_id = comment_view.comment.id;
194         blocking(context.pool(), move |conn: &'_ _| {
195           Comment::update_removed(conn, comment_id, true)
196         })
197         .await??;
198       }
199     }
200
201     // Mod tables
202     // TODO eventually do correct expires
203     let expires = data.expires.map(naive_from_unix);
204
205     let form = ModBanFromCommunityForm {
206       mod_person_id: local_user_view.person.id,
207       other_person_id: data.person_id,
208       community_id: data.community_id,
209       reason: data.reason.to_owned(),
210       banned: Some(data.ban),
211       expires,
212     };
213     blocking(context.pool(), move |conn| {
214       ModBanFromCommunity::create(conn, &form)
215     })
216     .await??;
217
218     let person_id = data.person_id;
219     let person_view = blocking(context.pool(), move |conn| {
220       PersonViewSafe::read(conn, person_id)
221     })
222     .await??;
223
224     let res = BanFromCommunityResponse {
225       person_view,
226       banned: data.ban,
227     };
228
229     context.chat_server().do_send(SendCommunityRoomMessage {
230       op: UserOperation::BanFromCommunity,
231       response: res.clone(),
232       community_id,
233       websocket_id,
234     });
235
236     Ok(res)
237   }
238 }
239
240 #[async_trait::async_trait(?Send)]
241 impl Perform for AddModToCommunity {
242   type Response = AddModToCommunityResponse;
243
244   async fn perform(
245     &self,
246     context: &Data<LemmyContext>,
247     websocket_id: Option<ConnectionId>,
248   ) -> Result<AddModToCommunityResponse, LemmyError> {
249     let data: &AddModToCommunity = self;
250     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
251
252     let community_id = data.community_id;
253
254     // Verify that only mods or admins can add mod
255     is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
256
257     // Update in local database
258     let community_moderator_form = CommunityModeratorForm {
259       community_id: data.community_id,
260       person_id: data.person_id,
261     };
262     if data.added {
263       let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
264       if blocking(context.pool(), join).await?.is_err() {
265         return Err(ApiError::err("community_moderator_already_exists").into());
266       }
267     } else {
268       let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form);
269       if blocking(context.pool(), leave).await?.is_err() {
270         return Err(ApiError::err("community_moderator_already_exists").into());
271       }
272     }
273
274     // Mod tables
275     let form = ModAddCommunityForm {
276       mod_person_id: local_user_view.person.id,
277       other_person_id: data.person_id,
278       community_id: data.community_id,
279       removed: Some(!data.added),
280     };
281     blocking(context.pool(), move |conn| {
282       ModAddCommunity::create(conn, &form)
283     })
284     .await??;
285
286     // Send to federated instances
287     let updated_mod_id = data.person_id;
288     let updated_mod = blocking(context.pool(), move |conn| {
289       Person::read(conn, updated_mod_id)
290     })
291     .await??;
292     let community = blocking(context.pool(), move |conn| {
293       Community::read(conn, community_id)
294     })
295     .await??;
296     if data.added {
297       community
298         .send_add_mod(&local_user_view.person, updated_mod, context)
299         .await?;
300     } else {
301       community
302         .send_remove_mod(&local_user_view.person, updated_mod, context)
303         .await?;
304     }
305
306     // Note: in case a remote mod is added, this returns the old moderators list, it will only get
307     //       updated once we receive an activity from the community (like `Announce/Add/Moderator`)
308     let community_id = data.community_id;
309     let moderators = blocking(context.pool(), move |conn| {
310       CommunityModeratorView::for_community(conn, community_id)
311     })
312     .await??;
313
314     let res = AddModToCommunityResponse { moderators };
315     context.chat_server().do_send(SendCommunityRoomMessage {
316       op: UserOperation::AddModToCommunity,
317       response: res.clone(),
318       community_id,
319       websocket_id,
320     });
321     Ok(res)
322   }
323 }
324
325 // TODO: we dont do anything for federation here, it should be updated the next time the community
326 //       gets fetched. i hope we can get rid of the community creator role soon.
327 #[async_trait::async_trait(?Send)]
328 impl Perform for TransferCommunity {
329   type Response = GetCommunityResponse;
330
331   async fn perform(
332     &self,
333     context: &Data<LemmyContext>,
334     _websocket_id: Option<ConnectionId>,
335   ) -> Result<GetCommunityResponse, LemmyError> {
336     let data: &TransferCommunity = self;
337     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
338
339     let site_creator_id = blocking(context.pool(), move |conn| {
340       Site::read(conn, 1).map(|s| s.creator_id)
341     })
342     .await??;
343
344     let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
345
346     // Making sure the site creator, if an admin, is at the top
347     let creator_index = admins
348       .iter()
349       .position(|r| r.person.id == site_creator_id)
350       .context(location_info!())?;
351     let creator_person = admins.remove(creator_index);
352     admins.insert(0, creator_person);
353
354     // Fetch the community mods
355     let community_id = data.community_id;
356     let mut community_mods = blocking(context.pool(), move |conn| {
357       CommunityModeratorView::for_community(conn, community_id)
358     })
359     .await??;
360
361     // Make sure transferrer is either the top community mod, or an admin
362     if local_user_view.person.id != community_mods[0].moderator.id
363       && !admins
364         .iter()
365         .map(|a| a.person.id)
366         .any(|x| x == local_user_view.person.id)
367     {
368       return Err(ApiError::err("not_an_admin").into());
369     }
370
371     // You have to re-do the community_moderator table, reordering it.
372     // Add the transferee to the top
373     let creator_index = community_mods
374       .iter()
375       .position(|r| r.moderator.id == data.person_id)
376       .context(location_info!())?;
377     let creator_person = community_mods.remove(creator_index);
378     community_mods.insert(0, creator_person);
379
380     // Delete all the mods
381     let community_id = data.community_id;
382     blocking(context.pool(), move |conn| {
383       CommunityModerator::delete_for_community(conn, community_id)
384     })
385     .await??;
386
387     // TODO: this should probably be a bulk operation
388     // Re-add the mods, in the new order
389     for cmod in &community_mods {
390       let community_moderator_form = CommunityModeratorForm {
391         community_id: cmod.community.id,
392         person_id: cmod.moderator.id,
393       };
394
395       let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
396       if blocking(context.pool(), join).await?.is_err() {
397         return Err(ApiError::err("community_moderator_already_exists").into());
398       }
399     }
400
401     // Mod tables
402     let form = ModTransferCommunityForm {
403       mod_person_id: local_user_view.person.id,
404       other_person_id: data.person_id,
405       community_id: data.community_id,
406       removed: Some(false),
407     };
408     blocking(context.pool(), move |conn| {
409       ModTransferCommunity::create(conn, &form)
410     })
411     .await??;
412
413     let community_id = data.community_id;
414     let person_id = local_user_view.person.id;
415     let community_view = blocking(context.pool(), move |conn| {
416       CommunityView::read(conn, community_id, Some(person_id))
417     })
418     .await?
419     .map_err(|_| ApiError::err("couldnt_find_community"))?;
420
421     let community_id = data.community_id;
422     let moderators = blocking(context.pool(), move |conn| {
423       CommunityModeratorView::for_community(conn, community_id)
424     })
425     .await?
426     .map_err(|_| ApiError::err("couldnt_find_community"))?;
427
428     // Return the jwt
429     Ok(GetCommunityResponse {
430       community_view,
431       moderators,
432       online: 0,
433     })
434   }
435 }