]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/list.rs
Extract Activitypub logic into separate library (#2288)
[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   utils::{blocking, check_private_instance, get_local_user_view_from_jwt_opt},
6 };
7 use lemmy_db_schema::traits::DeleteableOrRemoveable;
8 use lemmy_db_views_actor::community_view::CommunityQueryBuilder;
9 use lemmy_utils::{error::LemmyError, ConnectionId};
10 use lemmy_websocket::LemmyContext;
11
12 #[async_trait::async_trait(?Send)]
13 impl PerformCrud for ListCommunities {
14   type Response = ListCommunitiesResponse;
15
16   #[tracing::instrument(skip(context, _websocket_id))]
17   async fn perform(
18     &self,
19     context: &Data<LemmyContext>,
20     _websocket_id: Option<ConnectionId>,
21   ) -> Result<ListCommunitiesResponse, LemmyError> {
22     let data: &ListCommunities = self;
23     let local_user_view =
24       get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
25         .await?;
26
27     check_private_instance(&local_user_view, context.pool()).await?;
28
29     let person_id = local_user_view.to_owned().map(|l| l.person.id);
30
31     // Don't show NSFW by default
32     let show_nsfw = match &local_user_view {
33       Some(uv) => uv.local_user.show_nsfw,
34       None => false,
35     };
36
37     let sort = data.sort;
38     let listing_type = data.type_;
39     let page = data.page;
40     let limit = data.limit;
41     let mut communities = blocking(context.pool(), move |conn| {
42       CommunityQueryBuilder::create(conn)
43         .listing_type(listing_type)
44         .sort(sort)
45         .show_nsfw(show_nsfw)
46         .my_person_id(person_id)
47         .page(page)
48         .limit(limit)
49         .list()
50     })
51     .await??;
52
53     // Blank out deleted or removed info for non-logged in users
54     if person_id.is_none() {
55       for cv in communities
56         .iter_mut()
57         .filter(|cv| cv.community.deleted || cv.community.removed)
58       {
59         cv.community = cv.to_owned().community.blank_out_deleted_or_removed_info();
60       }
61     }
62
63     // Return the jwt
64     Ok(ListCommunitiesResponse { communities })
65   }
66 }