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