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