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