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