]> Untitled Git - lemmy.git/blob - crates/api/src/community.rs
Merge branch 'split_user_table' into strictly_type_db_ids
[lemmy.git] / crates / api / src / community.rs
1 use crate::{
2   check_community_ban,
3   get_local_user_view_from_jwt,
4   get_local_user_view_from_jwt_opt,
5   is_admin,
6   is_mod_or_admin,
7   Perform,
8 };
9 use actix_web::web::Data;
10 use anyhow::Context;
11 use lemmy_api_structs::{blocking, community::*};
12 use lemmy_apub::{
13   generate_apub_endpoint,
14   generate_followers_url,
15   generate_inbox_url,
16   generate_shared_inbox_url,
17   ActorType,
18   EndpointType,
19 };
20 use lemmy_db_queries::{
21   diesel_option_overwrite_to_url,
22   source::{
23     comment::Comment_,
24     community::{CommunityModerator_, Community_},
25     post::Post_,
26   },
27   ApubObject,
28   Bannable,
29   Crud,
30   Followable,
31   Joinable,
32   ListingType,
33   SortType,
34 };
35 use lemmy_db_schema::{
36   naive_now,
37   source::{comment::Comment, community::*, moderator::*, post::Post, site::*},
38   PersonId,
39 };
40 use lemmy_db_views::comment_view::CommentQueryBuilder;
41 use lemmy_db_views_actor::{
42   community_follower_view::CommunityFollowerView,
43   community_moderator_view::CommunityModeratorView,
44   community_view::{CommunityQueryBuilder, CommunityView},
45   person_view::PersonViewSafe,
46 };
47 use lemmy_utils::{
48   apub::generate_actor_keypair,
49   location_info,
50   utils::{check_slurs, check_slurs_opt, is_valid_community_name, naive_from_unix},
51   ApiError,
52   ConnectionId,
53   LemmyError,
54 };
55 use lemmy_websocket::{
56   messages::{GetCommunityUsersOnline, SendCommunityRoomMessage},
57   LemmyContext,
58   UserOperation,
59 };
60 use std::str::FromStr;
61
62 #[async_trait::async_trait(?Send)]
63 impl Perform for GetCommunity {
64   type Response = GetCommunityResponse;
65
66   async fn perform(
67     &self,
68     context: &Data<LemmyContext>,
69     _websocket_id: Option<ConnectionId>,
70   ) -> Result<GetCommunityResponse, LemmyError> {
71     let data: &GetCommunity = &self;
72     let local_user_view = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?;
73     let person_id = local_user_view.map(|u| u.person.id);
74
75     let community_id = match data.id {
76       Some(id) => id,
77       None => {
78         let name = data.name.to_owned().unwrap_or_else(|| "main".to_string());
79         match blocking(context.pool(), move |conn| {
80           Community::read_from_name(conn, &name)
81         })
82         .await?
83         {
84           Ok(community) => community,
85           Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
86         }
87         .id
88       }
89     };
90
91     let community_view = match blocking(context.pool(), move |conn| {
92       CommunityView::read(conn, community_id, person_id)
93     })
94     .await?
95     {
96       Ok(community) => community,
97       Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
98     };
99
100     let moderators: Vec<CommunityModeratorView> = match blocking(context.pool(), move |conn| {
101       CommunityModeratorView::for_community(conn, community_id)
102     })
103     .await?
104     {
105       Ok(moderators) => moderators,
106       Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
107     };
108
109     let online = context
110       .chat_server()
111       .send(GetCommunityUsersOnline { community_id })
112       .await
113       .unwrap_or(1);
114
115     let res = GetCommunityResponse {
116       community_view,
117       moderators,
118       online,
119     };
120
121     // Return the jwt
122     Ok(res)
123   }
124 }
125
126 #[async_trait::async_trait(?Send)]
127 impl Perform for CreateCommunity {
128   type Response = CommunityResponse;
129
130   async fn perform(
131     &self,
132     context: &Data<LemmyContext>,
133     _websocket_id: Option<ConnectionId>,
134   ) -> Result<CommunityResponse, LemmyError> {
135     let data: &CreateCommunity = &self;
136     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
137
138     check_slurs(&data.name)?;
139     check_slurs(&data.title)?;
140     check_slurs_opt(&data.description)?;
141
142     if !is_valid_community_name(&data.name) {
143       return Err(ApiError::err("invalid_community_name").into());
144     }
145
146     // Double check for duplicate community actor_ids
147     let community_actor_id = generate_apub_endpoint(EndpointType::Community, &data.name)?;
148     let actor_id_cloned = community_actor_id.to_owned();
149     let community_dupe = blocking(context.pool(), move |conn| {
150       Community::read_from_apub_id(conn, &actor_id_cloned)
151     })
152     .await?;
153     if community_dupe.is_ok() {
154       return Err(ApiError::err("community_already_exists").into());
155     }
156
157     // Check to make sure the icon and banners are urls
158     let icon = diesel_option_overwrite_to_url(&data.icon)?;
159     let banner = diesel_option_overwrite_to_url(&data.banner)?;
160
161     // When you create a community, make sure the user becomes a moderator and a follower
162     let keypair = generate_actor_keypair()?;
163
164     let community_form = CommunityForm {
165       name: data.name.to_owned(),
166       title: data.title.to_owned(),
167       description: data.description.to_owned(),
168       icon,
169       banner,
170       creator_id: local_user_view.person.id,
171       removed: None,
172       deleted: None,
173       nsfw: data.nsfw,
174       updated: None,
175       actor_id: Some(community_actor_id.to_owned()),
176       local: true,
177       private_key: Some(keypair.private_key),
178       public_key: Some(keypair.public_key),
179       last_refreshed_at: None,
180       published: None,
181       followers_url: Some(generate_followers_url(&community_actor_id)?),
182       inbox_url: Some(generate_inbox_url(&community_actor_id)?),
183       shared_inbox_url: Some(Some(generate_shared_inbox_url(&community_actor_id)?)),
184     };
185
186     let inserted_community = match blocking(context.pool(), move |conn| {
187       Community::create(conn, &community_form)
188     })
189     .await?
190     {
191       Ok(community) => community,
192       Err(_e) => return Err(ApiError::err("community_already_exists").into()),
193     };
194
195     // The community creator becomes a moderator
196     let community_moderator_form = CommunityModeratorForm {
197       community_id: inserted_community.id,
198       person_id: local_user_view.person.id,
199     };
200
201     let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
202     if blocking(context.pool(), join).await?.is_err() {
203       return Err(ApiError::err("community_moderator_already_exists").into());
204     }
205
206     // Follow your own community
207     let community_follower_form = CommunityFollowerForm {
208       community_id: inserted_community.id,
209       person_id: local_user_view.person.id,
210       pending: false,
211     };
212
213     let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
214     if blocking(context.pool(), follow).await?.is_err() {
215       return Err(ApiError::err("community_follower_already_exists").into());
216     }
217
218     let person_id = local_user_view.person.id;
219     let community_view = blocking(context.pool(), move |conn| {
220       CommunityView::read(conn, inserted_community.id, Some(person_id))
221     })
222     .await??;
223
224     Ok(CommunityResponse { community_view })
225   }
226 }
227
228 #[async_trait::async_trait(?Send)]
229 impl Perform for EditCommunity {
230   type Response = CommunityResponse;
231
232   async fn perform(
233     &self,
234     context: &Data<LemmyContext>,
235     websocket_id: Option<ConnectionId>,
236   ) -> Result<CommunityResponse, LemmyError> {
237     let data: &EditCommunity = &self;
238     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
239
240     check_slurs(&data.title)?;
241     check_slurs_opt(&data.description)?;
242
243     // Verify its a mod (only mods can edit it)
244     let community_id = data.community_id;
245     let mods: Vec<PersonId> = blocking(context.pool(), move |conn| {
246       CommunityModeratorView::for_community(conn, community_id)
247         .map(|v| v.into_iter().map(|m| m.moderator.id).collect())
248     })
249     .await??;
250     if !mods.contains(&local_user_view.person.id) {
251       return Err(ApiError::err("not_a_moderator").into());
252     }
253
254     let community_id = data.community_id;
255     let read_community = blocking(context.pool(), move |conn| {
256       Community::read(conn, community_id)
257     })
258     .await??;
259
260     let icon = diesel_option_overwrite_to_url(&data.icon)?;
261     let banner = diesel_option_overwrite_to_url(&data.banner)?;
262
263     let community_form = CommunityForm {
264       name: read_community.name,
265       title: data.title.to_owned(),
266       description: data.description.to_owned(),
267       icon,
268       banner,
269       creator_id: read_community.creator_id,
270       removed: Some(read_community.removed),
271       deleted: Some(read_community.deleted),
272       nsfw: data.nsfw,
273       updated: Some(naive_now()),
274       actor_id: Some(read_community.actor_id),
275       local: read_community.local,
276       private_key: read_community.private_key,
277       public_key: read_community.public_key,
278       last_refreshed_at: None,
279       published: None,
280       followers_url: None,
281       inbox_url: None,
282       shared_inbox_url: None,
283     };
284
285     let community_id = data.community_id;
286     match blocking(context.pool(), move |conn| {
287       Community::update(conn, community_id, &community_form)
288     })
289     .await?
290     {
291       Ok(community) => community,
292       Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
293     };
294
295     // TODO there needs to be some kind of an apub update
296     // process for communities and users
297
298     let community_id = data.community_id;
299     let person_id = local_user_view.person.id;
300     let community_view = blocking(context.pool(), move |conn| {
301       CommunityView::read(conn, community_id, Some(person_id))
302     })
303     .await??;
304
305     let res = CommunityResponse { community_view };
306
307     send_community_websocket(&res, context, websocket_id, UserOperation::EditCommunity);
308
309     Ok(res)
310   }
311 }
312
313 #[async_trait::async_trait(?Send)]
314 impl Perform for DeleteCommunity {
315   type Response = CommunityResponse;
316
317   async fn perform(
318     &self,
319     context: &Data<LemmyContext>,
320     websocket_id: Option<ConnectionId>,
321   ) -> Result<CommunityResponse, LemmyError> {
322     let data: &DeleteCommunity = &self;
323     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
324
325     // Verify its the creator (only a creator can delete the community)
326     let community_id = data.community_id;
327     let read_community = blocking(context.pool(), move |conn| {
328       Community::read(conn, community_id)
329     })
330     .await??;
331     if read_community.creator_id != local_user_view.person.id {
332       return Err(ApiError::err("no_community_edit_allowed").into());
333     }
334
335     // Do the delete
336     let community_id = data.community_id;
337     let deleted = data.deleted;
338     let updated_community = match blocking(context.pool(), move |conn| {
339       Community::update_deleted(conn, community_id, deleted)
340     })
341     .await?
342     {
343       Ok(community) => community,
344       Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
345     };
346
347     // Send apub messages
348     if deleted {
349       updated_community.send_delete(context).await?;
350     } else {
351       updated_community.send_undo_delete(context).await?;
352     }
353
354     let community_id = data.community_id;
355     let person_id = local_user_view.person.id;
356     let community_view = blocking(context.pool(), move |conn| {
357       CommunityView::read(conn, community_id, Some(person_id))
358     })
359     .await??;
360
361     let res = CommunityResponse { community_view };
362
363     send_community_websocket(&res, context, websocket_id, UserOperation::DeleteCommunity);
364
365     Ok(res)
366   }
367 }
368
369 #[async_trait::async_trait(?Send)]
370 impl Perform for RemoveCommunity {
371   type Response = CommunityResponse;
372
373   async fn perform(
374     &self,
375     context: &Data<LemmyContext>,
376     websocket_id: Option<ConnectionId>,
377   ) -> Result<CommunityResponse, LemmyError> {
378     let data: &RemoveCommunity = &self;
379     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
380
381     // Verify its an admin (only an admin can remove a community)
382     is_admin(&local_user_view)?;
383
384     // Do the remove
385     let community_id = data.community_id;
386     let removed = data.removed;
387     let updated_community = match blocking(context.pool(), move |conn| {
388       Community::update_removed(conn, community_id, removed)
389     })
390     .await?
391     {
392       Ok(community) => community,
393       Err(_e) => return Err(ApiError::err("couldnt_update_community").into()),
394     };
395
396     // Mod tables
397     let expires = match data.expires {
398       Some(time) => Some(naive_from_unix(time)),
399       None => None,
400     };
401     let form = ModRemoveCommunityForm {
402       mod_person_id: local_user_view.person.id,
403       community_id: data.community_id,
404       removed: Some(removed),
405       reason: data.reason.to_owned(),
406       expires,
407     };
408     blocking(context.pool(), move |conn| {
409       ModRemoveCommunity::create(conn, &form)
410     })
411     .await??;
412
413     // Apub messages
414     if removed {
415       updated_community.send_remove(context).await?;
416     } else {
417       updated_community.send_undo_remove(context).await?;
418     }
419
420     let community_id = data.community_id;
421     let person_id = local_user_view.person.id;
422     let community_view = blocking(context.pool(), move |conn| {
423       CommunityView::read(conn, community_id, Some(person_id))
424     })
425     .await??;
426
427     let res = CommunityResponse { community_view };
428
429     send_community_websocket(&res, context, websocket_id, UserOperation::RemoveCommunity);
430
431     Ok(res)
432   }
433 }
434
435 #[async_trait::async_trait(?Send)]
436 impl Perform for ListCommunities {
437   type Response = ListCommunitiesResponse;
438
439   async fn perform(
440     &self,
441     context: &Data<LemmyContext>,
442     _websocket_id: Option<ConnectionId>,
443   ) -> Result<ListCommunitiesResponse, LemmyError> {
444     let data: &ListCommunities = &self;
445     let local_user_view = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?;
446
447     let person_id = match &local_user_view {
448       Some(uv) => Some(uv.person.id),
449       None => None,
450     };
451
452     // Don't show NSFW by default
453     let show_nsfw = match &local_user_view {
454       Some(uv) => uv.local_user.show_nsfw,
455       None => false,
456     };
457
458     let type_ = ListingType::from_str(&data.type_)?;
459     let sort = SortType::from_str(&data.sort)?;
460
461     let page = data.page;
462     let limit = data.limit;
463     let communities = blocking(context.pool(), move |conn| {
464       CommunityQueryBuilder::create(conn)
465         .listing_type(&type_)
466         .sort(&sort)
467         .show_nsfw(show_nsfw)
468         .my_person_id(person_id)
469         .page(page)
470         .limit(limit)
471         .list()
472     })
473     .await??;
474
475     // Return the jwt
476     Ok(ListCommunitiesResponse { communities })
477   }
478 }
479
480 #[async_trait::async_trait(?Send)]
481 impl Perform for FollowCommunity {
482   type Response = CommunityResponse;
483
484   async fn perform(
485     &self,
486     context: &Data<LemmyContext>,
487     _websocket_id: Option<ConnectionId>,
488   ) -> Result<CommunityResponse, LemmyError> {
489     let data: &FollowCommunity = &self;
490     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
491
492     let community_id = data.community_id;
493     let community = blocking(context.pool(), move |conn| {
494       Community::read(conn, community_id)
495     })
496     .await??;
497     let community_follower_form = CommunityFollowerForm {
498       community_id: data.community_id,
499       person_id: local_user_view.person.id,
500       pending: false,
501     };
502
503     if community.local {
504       if data.follow {
505         check_community_ban(local_user_view.person.id, community_id, context.pool()).await?;
506
507         let follow = move |conn: &'_ _| CommunityFollower::follow(conn, &community_follower_form);
508         if blocking(context.pool(), follow).await?.is_err() {
509           return Err(ApiError::err("community_follower_already_exists").into());
510         }
511       } else {
512         let unfollow =
513           move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
514         if blocking(context.pool(), unfollow).await?.is_err() {
515           return Err(ApiError::err("community_follower_already_exists").into());
516         }
517       }
518     } else if data.follow {
519       // Dont actually add to the community followers here, because you need
520       // to wait for the accept
521       local_user_view
522         .person
523         .send_follow(&community.actor_id(), context)
524         .await?;
525     } else {
526       local_user_view
527         .person
528         .send_unfollow(&community.actor_id(), context)
529         .await?;
530       let unfollow = move |conn: &'_ _| CommunityFollower::unfollow(conn, &community_follower_form);
531       if blocking(context.pool(), unfollow).await?.is_err() {
532         return Err(ApiError::err("community_follower_already_exists").into());
533       }
534     }
535
536     let community_id = data.community_id;
537     let person_id = local_user_view.person.id;
538     let mut community_view = blocking(context.pool(), move |conn| {
539       CommunityView::read(conn, community_id, Some(person_id))
540     })
541     .await??;
542
543     // TODO: this needs to return a "pending" state, until Accept is received from the remote server
544     // For now, just assume that remote follows are accepted.
545     // Otherwise, the subscribed will be null
546     if !community.local {
547       community_view.subscribed = data.follow;
548     }
549
550     Ok(CommunityResponse { community_view })
551   }
552 }
553
554 #[async_trait::async_trait(?Send)]
555 impl Perform for GetFollowedCommunities {
556   type Response = GetFollowedCommunitiesResponse;
557
558   async fn perform(
559     &self,
560     context: &Data<LemmyContext>,
561     _websocket_id: Option<ConnectionId>,
562   ) -> Result<GetFollowedCommunitiesResponse, LemmyError> {
563     let data: &GetFollowedCommunities = &self;
564     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
565
566     let person_id = local_user_view.person.id;
567     let communities = match blocking(context.pool(), move |conn| {
568       CommunityFollowerView::for_person(conn, person_id)
569     })
570     .await?
571     {
572       Ok(communities) => communities,
573       _ => return Err(ApiError::err("system_err_login").into()),
574     };
575
576     // Return the jwt
577     Ok(GetFollowedCommunitiesResponse { communities })
578   }
579 }
580
581 #[async_trait::async_trait(?Send)]
582 impl Perform for BanFromCommunity {
583   type Response = BanFromCommunityResponse;
584
585   async fn perform(
586     &self,
587     context: &Data<LemmyContext>,
588     websocket_id: Option<ConnectionId>,
589   ) -> Result<BanFromCommunityResponse, LemmyError> {
590     let data: &BanFromCommunity = &self;
591     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
592
593     let community_id = data.community_id;
594     let banned_person_id = data.person_id;
595
596     // Verify that only mods or admins can ban
597     is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
598
599     let community_user_ban_form = CommunityPersonBanForm {
600       community_id: data.community_id,
601       person_id: data.person_id,
602     };
603
604     if data.ban {
605       let ban = move |conn: &'_ _| CommunityPersonBan::ban(conn, &community_user_ban_form);
606       if blocking(context.pool(), ban).await?.is_err() {
607         return Err(ApiError::err("community_user_already_banned").into());
608       }
609
610       // Also unsubscribe them from the community, if they are subscribed
611       let community_follower_form = CommunityFollowerForm {
612         community_id: data.community_id,
613         person_id: banned_person_id,
614         pending: false,
615       };
616       blocking(context.pool(), move |conn: &'_ _| {
617         CommunityFollower::unfollow(conn, &community_follower_form)
618       })
619       .await?
620       .ok();
621     } else {
622       let unban = move |conn: &'_ _| CommunityPersonBan::unban(conn, &community_user_ban_form);
623       if blocking(context.pool(), unban).await?.is_err() {
624         return Err(ApiError::err("community_user_already_banned").into());
625       }
626     }
627
628     // Remove/Restore their data if that's desired
629     if data.remove_data {
630       // Posts
631       blocking(context.pool(), move |conn: &'_ _| {
632         Post::update_removed_for_creator(conn, banned_person_id, Some(community_id), true)
633       })
634       .await??;
635
636       // Comments
637       // TODO Diesel doesn't allow updates with joins, so this has to be a loop
638       let comments = blocking(context.pool(), move |conn| {
639         CommentQueryBuilder::create(conn)
640           .creator_id(banned_person_id)
641           .community_id(community_id)
642           .limit(std::i64::MAX)
643           .list()
644       })
645       .await??;
646
647       for comment_view in &comments {
648         let comment_id = comment_view.comment.id;
649         blocking(context.pool(), move |conn: &'_ _| {
650           Comment::update_removed(conn, comment_id, true)
651         })
652         .await??;
653       }
654     }
655
656     // Mod tables
657     // TODO eventually do correct expires
658     let expires = match data.expires {
659       Some(time) => Some(naive_from_unix(time)),
660       None => None,
661     };
662
663     let form = ModBanFromCommunityForm {
664       mod_person_id: local_user_view.person.id,
665       other_person_id: data.person_id,
666       community_id: data.community_id,
667       reason: data.reason.to_owned(),
668       banned: Some(data.ban),
669       expires,
670     };
671     blocking(context.pool(), move |conn| {
672       ModBanFromCommunity::create(conn, &form)
673     })
674     .await??;
675
676     let person_id = data.person_id;
677     let person_view = blocking(context.pool(), move |conn| {
678       PersonViewSafe::read(conn, person_id)
679     })
680     .await??;
681
682     let res = BanFromCommunityResponse {
683       person_view,
684       banned: data.ban,
685     };
686
687     context.chat_server().do_send(SendCommunityRoomMessage {
688       op: UserOperation::BanFromCommunity,
689       response: res.clone(),
690       community_id,
691       websocket_id,
692     });
693
694     Ok(res)
695   }
696 }
697
698 #[async_trait::async_trait(?Send)]
699 impl Perform for AddModToCommunity {
700   type Response = AddModToCommunityResponse;
701
702   async fn perform(
703     &self,
704     context: &Data<LemmyContext>,
705     websocket_id: Option<ConnectionId>,
706   ) -> Result<AddModToCommunityResponse, LemmyError> {
707     let data: &AddModToCommunity = &self;
708     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
709
710     let community_moderator_form = CommunityModeratorForm {
711       community_id: data.community_id,
712       person_id: data.person_id,
713     };
714
715     let community_id = data.community_id;
716
717     // Verify that only mods or admins can add mod
718     is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
719
720     if data.added {
721       let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
722       if blocking(context.pool(), join).await?.is_err() {
723         return Err(ApiError::err("community_moderator_already_exists").into());
724       }
725     } else {
726       let leave = move |conn: &'_ _| CommunityModerator::leave(conn, &community_moderator_form);
727       if blocking(context.pool(), leave).await?.is_err() {
728         return Err(ApiError::err("community_moderator_already_exists").into());
729       }
730     }
731
732     // Mod tables
733     let form = ModAddCommunityForm {
734       mod_person_id: local_user_view.person.id,
735       other_person_id: data.person_id,
736       community_id: data.community_id,
737       removed: Some(!data.added),
738     };
739     blocking(context.pool(), move |conn| {
740       ModAddCommunity::create(conn, &form)
741     })
742     .await??;
743
744     let community_id = data.community_id;
745     let moderators = blocking(context.pool(), move |conn| {
746       CommunityModeratorView::for_community(conn, community_id)
747     })
748     .await??;
749
750     let res = AddModToCommunityResponse { moderators };
751
752     context.chat_server().do_send(SendCommunityRoomMessage {
753       op: UserOperation::AddModToCommunity,
754       response: res.clone(),
755       community_id,
756       websocket_id,
757     });
758
759     Ok(res)
760   }
761 }
762
763 #[async_trait::async_trait(?Send)]
764 impl Perform for TransferCommunity {
765   type Response = GetCommunityResponse;
766
767   async fn perform(
768     &self,
769     context: &Data<LemmyContext>,
770     _websocket_id: Option<ConnectionId>,
771   ) -> Result<GetCommunityResponse, LemmyError> {
772     let data: &TransferCommunity = &self;
773     let local_user_view = get_local_user_view_from_jwt(&data.auth, context.pool()).await?;
774
775     let community_id = data.community_id;
776     let read_community = blocking(context.pool(), move |conn| {
777       Community::read(conn, community_id)
778     })
779     .await??;
780
781     let site_creator_id = blocking(context.pool(), move |conn| {
782       Site::read(conn, 1).map(|s| s.creator_id)
783     })
784     .await??;
785
786     let mut admins = blocking(context.pool(), move |conn| PersonViewSafe::admins(conn)).await??;
787
788     // Making sure the creator, if an admin, is at the top
789     let creator_index = admins
790       .iter()
791       .position(|r| r.person.id == site_creator_id)
792       .context(location_info!())?;
793     let creator_person = admins.remove(creator_index);
794     admins.insert(0, creator_person);
795
796     // Make sure user is the creator, or an admin
797     if local_user_view.person.id != read_community.creator_id
798       && !admins
799         .iter()
800         .map(|a| a.person.id)
801         .any(|x| x == local_user_view.person.id)
802     {
803       return Err(ApiError::err("not_an_admin").into());
804     }
805
806     let community_id = data.community_id;
807     let new_creator = data.person_id;
808     let update = move |conn: &'_ _| Community::update_creator(conn, community_id, new_creator);
809     if blocking(context.pool(), update).await?.is_err() {
810       return Err(ApiError::err("couldnt_update_community").into());
811     };
812
813     // You also have to re-do the community_moderator table, reordering it.
814     let community_id = data.community_id;
815     let mut community_mods = blocking(context.pool(), move |conn| {
816       CommunityModeratorView::for_community(conn, community_id)
817     })
818     .await??;
819     let creator_index = community_mods
820       .iter()
821       .position(|r| r.moderator.id == data.person_id)
822       .context(location_info!())?;
823     let creator_person = community_mods.remove(creator_index);
824     community_mods.insert(0, creator_person);
825
826     let community_id = data.community_id;
827     blocking(context.pool(), move |conn| {
828       CommunityModerator::delete_for_community(conn, community_id)
829     })
830     .await??;
831
832     // TODO: this should probably be a bulk operation
833     for cmod in &community_mods {
834       let community_moderator_form = CommunityModeratorForm {
835         community_id: cmod.community.id,
836         person_id: cmod.moderator.id,
837       };
838
839       let join = move |conn: &'_ _| CommunityModerator::join(conn, &community_moderator_form);
840       if blocking(context.pool(), join).await?.is_err() {
841         return Err(ApiError::err("community_moderator_already_exists").into());
842       }
843     }
844
845     // Mod tables
846     let form = ModAddCommunityForm {
847       mod_person_id: local_user_view.person.id,
848       other_person_id: data.person_id,
849       community_id: data.community_id,
850       removed: Some(false),
851     };
852     blocking(context.pool(), move |conn| {
853       ModAddCommunity::create(conn, &form)
854     })
855     .await??;
856
857     let community_id = data.community_id;
858     let person_id = local_user_view.person.id;
859     let community_view = match blocking(context.pool(), move |conn| {
860       CommunityView::read(conn, community_id, Some(person_id))
861     })
862     .await?
863     {
864       Ok(community) => community,
865       Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
866     };
867
868     let community_id = data.community_id;
869     let moderators = match blocking(context.pool(), move |conn| {
870       CommunityModeratorView::for_community(conn, community_id)
871     })
872     .await?
873     {
874       Ok(moderators) => moderators,
875       Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
876     };
877
878     // Return the jwt
879     Ok(GetCommunityResponse {
880       community_view,
881       moderators,
882       online: 0,
883     })
884   }
885 }
886
887 fn send_community_websocket(
888   res: &CommunityResponse,
889   context: &Data<LemmyContext>,
890   websocket_id: Option<ConnectionId>,
891   op: UserOperation,
892 ) {
893   // Strip out the person id and subscribed when sending to others
894   let mut res_sent = res.clone();
895   res_sent.community_view.subscribed = false;
896
897   context.chat_server().do_send(SendCommunityRoomMessage {
898     op,
899     response: res_sent,
900     community_id: res.community_view.community.id,
901     websocket_id,
902   });
903 }