]> Untitled Git - lemmy.git/blob - crates/api/src/community.rs
1ee2a9a76ae15d3702c93938872d353c8a8b8bc5
[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 = match data.expires {
192       Some(time) => Some(naive_from_unix(time)),
193       None => None,
194     };
195
196     let form = ModBanFromCommunityForm {
197       mod_person_id: local_user_view.person.id,
198       other_person_id: data.person_id,
199       community_id: data.community_id,
200       reason: data.reason.to_owned(),
201       banned: Some(data.ban),
202       expires,
203     };
204     blocking(context.pool(), move |conn| {
205       ModBanFromCommunity::create(conn, &form)
206     })
207     .await??;
208
209     let person_id = data.person_id;
210     let person_view = blocking(context.pool(), move |conn| {
211       PersonViewSafe::read(conn, person_id)
212     })
213     .await??;
214
215     let res = BanFromCommunityResponse {
216       person_view,
217       banned: data.ban,
218     };
219
220     context.chat_server().do_send(SendCommunityRoomMessage {
221       op: UserOperation::BanFromCommunity,
222       response: res.clone(),
223       community_id,
224       websocket_id,
225     });
226
227     Ok(res)
228   }
229 }
230
231 #[async_trait::async_trait(?Send)]
232 impl Perform for AddModToCommunity {
233   type Response = AddModToCommunityResponse;
234
235   async fn perform(
236     &self,
237     context: &Data<LemmyContext>,
238     websocket_id: Option<ConnectionId>,
239   ) -> Result<AddModToCommunityResponse, LemmyError> {
240     let data: &AddModToCommunity = &self;
241     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
242
243     let community_id = data.community_id;
244
245     // Verify that only mods or admins can add mod
246     is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
247
248     // Update in local database
249     let community_moderator_form = CommunityModeratorForm {
250       community_id: data.community_id,
251       person_id: data.person_id,
252     };
253     if data.added {
254       let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
255       if blocking(context.pool(), join).await?.is_err() {
256         return Err(ApiError::err("community_moderator_already_exists").into());
257       }
258     } else {
259       let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form);
260       if blocking(context.pool(), leave).await?.is_err() {
261         return Err(ApiError::err("community_moderator_already_exists").into());
262       }
263     }
264
265     // Mod tables
266     let form = ModAddCommunityForm {
267       mod_person_id: local_user_view.person.id,
268       other_person_id: data.person_id,
269       community_id: data.community_id,
270       removed: Some(!data.added),
271     };
272     blocking(context.pool(), move |conn| {
273       ModAddCommunity::create(conn, &form)
274     })
275     .await??;
276
277     // Send to federated instances
278     let updated_mod_id = data.person_id;
279     let updated_mod = blocking(context.pool(), move |conn| {
280       Person::read(conn, updated_mod_id)
281     })
282     .await??;
283     let community = blocking(context.pool(), move |conn| {
284       Community::read(conn, community_id)
285     })
286     .await??;
287     if data.added {
288       community
289         .send_add_mod(&local_user_view.person, updated_mod, context)
290         .await?;
291     } else {
292       community
293         .send_remove_mod(&local_user_view.person, updated_mod, context)
294         .await?;
295     }
296
297     // Note: in case a remote mod is added, this returns the old moderators list, it will only get
298     //       updated once we receive an activity from the community (like `Announce/Add/Moderator`)
299     let community_id = data.community_id;
300     let moderators = blocking(context.pool(), move |conn| {
301       CommunityModeratorView::for_community(conn, community_id)
302     })
303     .await??;
304
305     let res = AddModToCommunityResponse { moderators };
306     context.chat_server().do_send(SendCommunityRoomMessage {
307       op: UserOperation::AddModToCommunity,
308       response: res.clone(),
309       community_id,
310       websocket_id,
311     });
312     Ok(res)
313   }
314 }
315
316 // TODO: we dont do anything for federation here, it should be updated the next time the community
317 //       gets fetched. i hope we can get rid of the community creator role soon.
318 #[async_trait::async_trait(?Send)]
319 impl Perform for TransferCommunity {
320   type Response = GetCommunityResponse;
321
322   async fn perform(
323     &self,
324     context: &Data<LemmyContext>,
325     _websocket_id: Option<ConnectionId>,
326   ) -> Result<GetCommunityResponse, LemmyError> {
327     let data: &TransferCommunity = &self;
328     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
329
330     let community_id = data.community_id;
331     let read_community = blocking(context.pool(), move |conn| {
332       Community::read(conn, community_id)
333     })
334     .await??;
335
336     let site_creator_id = blocking(context.pool(), move |conn| {
337       Site::read(conn, 1).map(|s| s.creator_id)
338     })
339     .await??;
340
341     let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
342
343     // Making sure the creator, if an admin, is at the top
344     let creator_index = admins
345       .iter()
346       .position(|r| r.person.id == site_creator_id)
347       .context(location_info!())?;
348     let creator_person = admins.remove(creator_index);
349     admins.insert(0, creator_person);
350
351     // Make sure user is the creator, or an admin
352     if local_user_view.person.id != read_community.creator_id
353       && !admins
354         .iter()
355         .map(|a| a.person.id)
356         .any(|x| x == local_user_view.person.id)
357     {
358       return Err(ApiError::err("not_an_admin").into());
359     }
360
361     let community_id = data.community_id;
362     let new_creator = data.person_id;
363     let update = move |conn: &'_ _| Community::update_creator(conn, community_id, new_creator);
364     if blocking(context.pool(), update).await?.is_err() {
365       return Err(ApiError::err("couldnt_update_community").into());
366     };
367
368     // You also have to re-do the community_moderator table, reordering it.
369     let community_id = data.community_id;
370     let mut community_mods = blocking(context.pool(), move |conn| {
371       CommunityModeratorView::for_community(conn, community_id)
372     })
373     .await??;
374     let creator_index = community_mods
375       .iter()
376       .position(|r| r.moderator.id == data.person_id)
377       .context(location_info!())?;
378     let creator_person = community_mods.remove(creator_index);
379     community_mods.insert(0, creator_person);
380
381     let community_id = data.community_id;
382     blocking(context.pool(), move |conn| {
383       CommunityModerator::delete_for_community(conn, community_id)
384     })
385     .await??;
386
387     // TODO: this should probably be a bulk operation
388     for cmod in &community_mods {
389       let community_moderator_form = CommunityModeratorForm {
390         community_id: cmod.community.id,
391         person_id: cmod.moderator.id,
392       };
393
394       let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
395       if blocking(context.pool(), join).await?.is_err() {
396         return Err(ApiError::err("community_moderator_already_exists").into());
397       }
398     }
399
400     // Mod tables
401     let form = ModAddCommunityForm {
402       mod_person_id: local_user_view.person.id,
403       other_person_id: data.person_id,
404       community_id: data.community_id,
405       removed: Some(false),
406     };
407     blocking(context.pool(), move |conn| {
408       ModAddCommunity::create(conn, &form)
409     })
410     .await??;
411
412     let community_id = data.community_id;
413     let person_id = local_user_view.person.id;
414     let community_view = match blocking(context.pool(), move |conn| {
415       CommunityView::read(conn, community_id, Some(person_id))
416     })
417     .await?
418     {
419       Ok(community) => community,
420       Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
421     };
422
423     let community_id = data.community_id;
424     let moderators = match blocking(context.pool(), move |conn| {
425       CommunityModeratorView::for_community(conn, community_id)
426     })
427     .await?
428     {
429       Ok(moderators) => moderators,
430       Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
431     };
432
433     // Return the jwt
434     Ok(GetCommunityResponse {
435       community_view,
436       moderators,
437       online: 0,
438     })
439   }
440 }