]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/list.rs
bd8189951528f80f992b04180015fa7372b6b1a6
[lemmy.git] / crates / api_crud / src / community / list.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   community::{ListCommunities, ListCommunitiesResponse},
5   context::LemmyContext,
6   utils::{check_private_instance, is_admin, local_user_view_from_jwt_opt},
7 };
8 use lemmy_db_schema::source::local_site::LocalSite;
9 use lemmy_db_views_actor::community_view::CommunityQuery;
10 use lemmy_utils::error::LemmyError;
11
12 #[async_trait::async_trait(?Send)]
13 impl PerformCrud for ListCommunities {
14   type Response = ListCommunitiesResponse;
15
16   #[tracing::instrument(skip(context))]
17   async fn perform(
18     &self,
19     context: &Data<LemmyContext>,
20   ) -> Result<ListCommunitiesResponse, LemmyError> {
21     let data: &ListCommunities = self;
22     let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), context).await;
23     let local_site = LocalSite::read(&mut context.pool()).await?;
24     let is_admin = local_user_view.as_ref().map(|luv| is_admin(luv).is_ok());
25
26     check_private_instance(&local_user_view, &local_site)?;
27
28     let sort = data.sort;
29     let listing_type = data.type_;
30     let show_nsfw = data.show_nsfw;
31     let page = data.page;
32     let limit = data.limit;
33     let local_user = local_user_view.map(|l| l.local_user);
34     let communities = CommunityQuery {
35       listing_type,
36       show_nsfw,
37       sort,
38       local_user: local_user.as_ref(),
39       page,
40       limit,
41       is_mod_or_admin: is_admin,
42       ..Default::default()
43     }
44     .list(&mut context.pool())
45     .await?;
46
47     // Return the jwt
48     Ok(ListCommunitiesResponse { communities })
49   }
50 }