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