]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/list.rs
Use typed-builder crate for queries (#2379)
[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::CommunityQuery;
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       CommunityQuery::builder()
43         .conn(conn)
44         .listing_type(listing_type)
45         .sort(sort)
46         .show_nsfw(Some(show_nsfw))
47         .my_person_id(person_id)
48         .page(page)
49         .limit(limit)
50         .build()
51         .list()
52     })
53     .await??;
54
55     // Blank out deleted or removed info for non-logged in users
56     if person_id.is_none() {
57       for cv in communities
58         .iter_mut()
59         .filter(|cv| cv.community.deleted || cv.community.removed)
60       {
61         cv.community = cv.to_owned().community.blank_out_deleted_or_removed_info();
62       }
63     }
64
65     // Return the jwt
66     Ok(ListCommunitiesResponse { communities })
67   }
68 }