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