]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/read.rs
Rework error handling (fixes #1714) (#2135)
[lemmy.git] / crates / api_crud / src / community / read.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   blocking,
5   check_private_instance,
6   community::*,
7   get_local_user_view_from_jwt_opt,
8   resolve_actor_identifier,
9 };
10 use lemmy_db_schema::{
11   from_opt_str_to_opt_enum,
12   source::community::Community,
13   traits::DeleteableOrRemoveable,
14   ListingType,
15   SortType,
16 };
17 use lemmy_db_views_actor::{
18   community_moderator_view::CommunityModeratorView,
19   community_view::{CommunityQueryBuilder, CommunityView},
20 };
21 use lemmy_utils::{ConnectionId, LemmyError};
22 use lemmy_websocket::{messages::GetCommunityUsersOnline, LemmyContext};
23
24 #[async_trait::async_trait(?Send)]
25 impl PerformCrud for GetCommunity {
26   type Response = GetCommunityResponse;
27
28   #[tracing::instrument(skip(context, _websocket_id))]
29   async fn perform(
30     &self,
31     context: &Data<LemmyContext>,
32     _websocket_id: Option<ConnectionId>,
33   ) -> Result<GetCommunityResponse, LemmyError> {
34     let data: &GetCommunity = self;
35     let local_user_view =
36       get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
37         .await?;
38
39     check_private_instance(&local_user_view, context.pool()).await?;
40
41     let person_id = local_user_view.map(|u| u.person.id);
42
43     let community_id = match data.id {
44       Some(id) => id,
45       None => {
46         let name = data.name.to_owned().unwrap_or_else(|| "main".to_string());
47         resolve_actor_identifier::<Community>(&name, context.pool())
48           .await
49           .map_err(|e| e.with_message("couldnt_find_community"))?
50           .id
51       }
52     };
53
54     let mut community_view = blocking(context.pool(), move |conn| {
55       CommunityView::read(conn, community_id, person_id)
56     })
57     .await?
58     .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
59
60     // Blank out deleted or removed info for non-logged in users
61     if person_id.is_none() && (community_view.community.deleted || community_view.community.removed)
62     {
63       community_view.community = community_view.community.blank_out_deleted_or_removed_info();
64     }
65
66     let moderators: Vec<CommunityModeratorView> = blocking(context.pool(), move |conn| {
67       CommunityModeratorView::for_community(conn, community_id)
68     })
69     .await?
70     .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?;
71
72     let online = context
73       .chat_server()
74       .send(GetCommunityUsersOnline { community_id })
75       .await
76       .unwrap_or(1);
77
78     let res = GetCommunityResponse {
79       community_view,
80       moderators,
81       online,
82     };
83
84     // Return the jwt
85     Ok(res)
86   }
87 }
88
89 #[async_trait::async_trait(?Send)]
90 impl PerformCrud for ListCommunities {
91   type Response = ListCommunitiesResponse;
92
93   #[tracing::instrument(skip(context, _websocket_id))]
94   async fn perform(
95     &self,
96     context: &Data<LemmyContext>,
97     _websocket_id: Option<ConnectionId>,
98   ) -> Result<ListCommunitiesResponse, LemmyError> {
99     let data: &ListCommunities = self;
100     let local_user_view =
101       get_local_user_view_from_jwt_opt(data.auth.as_ref(), context.pool(), context.secret())
102         .await?;
103
104     check_private_instance(&local_user_view, context.pool()).await?;
105
106     let person_id = local_user_view.to_owned().map(|l| l.person.id);
107
108     // Don't show NSFW by default
109     let show_nsfw = match &local_user_view {
110       Some(uv) => uv.local_user.show_nsfw,
111       None => false,
112     };
113
114     let sort: Option<SortType> = from_opt_str_to_opt_enum(&data.sort);
115     let listing_type: Option<ListingType> = from_opt_str_to_opt_enum(&data.type_);
116
117     let page = data.page;
118     let limit = data.limit;
119     let mut communities = blocking(context.pool(), move |conn| {
120       CommunityQueryBuilder::create(conn)
121         .listing_type(listing_type)
122         .sort(sort)
123         .show_nsfw(show_nsfw)
124         .my_person_id(person_id)
125         .page(page)
126         .limit(limit)
127         .list()
128     })
129     .await??;
130
131     // Blank out deleted or removed info for non-logged in users
132     if person_id.is_none() {
133       for cv in communities
134         .iter_mut()
135         .filter(|cv| cv.community.deleted || cv.community.removed)
136       {
137         cv.community = cv.to_owned().community.blank_out_deleted_or_removed_info();
138       }
139     }
140
141     // Return the jwt
142     Ok(ListCommunitiesResponse { communities })
143   }
144 }