1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{blocking, community::*, get_local_user_view_from_jwt_opt};
4 use lemmy_db_queries::{source::community::Community_, ListingType, SortType};
5 use lemmy_db_schema::source::community::*;
6 use lemmy_db_views_actor::{
7 community_moderator_view::CommunityModeratorView,
8 community_view::{CommunityQueryBuilder, CommunityView},
10 use lemmy_utils::{ApiError, ConnectionId, LemmyError};
11 use lemmy_websocket::{messages::GetCommunityUsersOnline, LemmyContext};
12 use std::str::FromStr;
14 #[async_trait::async_trait(?Send)]
15 impl PerformCrud for GetCommunity {
16 type Response = GetCommunityResponse;
20 context: &Data<LemmyContext>,
21 _websocket_id: Option<ConnectionId>,
22 ) -> Result<GetCommunityResponse, LemmyError> {
23 let data: &GetCommunity = &self;
24 let local_user_view = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?;
25 let person_id = local_user_view.map(|u| u.person.id);
27 let community_id = match data.id {
30 let name = data.name.to_owned().unwrap_or_else(|| "main".to_string());
31 match blocking(context.pool(), move |conn| {
32 Community::read_from_name(conn, &name)
36 Ok(community) => community,
37 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
43 let community_view = match blocking(context.pool(), move |conn| {
44 CommunityView::read(conn, community_id, person_id)
48 Ok(community) => community,
49 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
52 let moderators: Vec<CommunityModeratorView> = match blocking(context.pool(), move |conn| {
53 CommunityModeratorView::for_community(conn, community_id)
57 Ok(moderators) => moderators,
58 Err(_e) => return Err(ApiError::err("couldnt_find_community").into()),
63 .send(GetCommunityUsersOnline { community_id })
67 let res = GetCommunityResponse {
78 #[async_trait::async_trait(?Send)]
79 impl PerformCrud for ListCommunities {
80 type Response = ListCommunitiesResponse;
84 context: &Data<LemmyContext>,
85 _websocket_id: Option<ConnectionId>,
86 ) -> Result<ListCommunitiesResponse, LemmyError> {
87 let data: &ListCommunities = &self;
88 let local_user_view = get_local_user_view_from_jwt_opt(&data.auth, context.pool()).await?;
90 let person_id = local_user_view.to_owned().map(|l| l.person.id);
92 // Don't show NSFW by default
93 let show_nsfw = match &local_user_view {
94 Some(uv) => uv.local_user.show_nsfw,
98 let type_ = ListingType::from_str(&data.type_)?;
99 let sort = SortType::from_str(&data.sort)?;
101 let page = data.page;
102 let limit = data.limit;
103 let communities = blocking(context.pool(), move |conn| {
104 CommunityQueryBuilder::create(conn)
105 .listing_type(&type_)
107 .show_nsfw(show_nsfw)
108 .my_person_id(person_id)
116 Ok(ListCommunitiesResponse { communities })