]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/community_view.rs
0ee503a710781a3a232fc5f8d88d58593b1155b7
[lemmy.git] / crates / db_views_actor / src / community_view.rs
1 use crate::{community_moderator_view::CommunityModeratorView, person_view::PersonViewSafe};
2 use diesel::{result::Error, *};
3 use lemmy_db_queries::{
4   aggregates::community_aggregates::CommunityAggregates,
5   functions::hot_rank,
6   fuzzy_search,
7   limit_and_offset,
8   ListingType,
9   MaybeOptional,
10   SortType,
11   ToSafe,
12   ViewToVec,
13 };
14 use lemmy_db_schema::{
15   schema::{community, community_aggregates, community_follower},
16   source::community::{Community, CommunityFollower, CommunitySafe},
17   CommunityId,
18   PersonId,
19 };
20 use serde::Serialize;
21
22 #[derive(Debug, Serialize, Clone)]
23 pub struct CommunityView {
24   pub community: CommunitySafe,
25   pub subscribed: bool,
26   pub counts: CommunityAggregates,
27 }
28
29 type CommunityViewTuple = (
30   CommunitySafe,
31   CommunityAggregates,
32   Option<CommunityFollower>,
33 );
34
35 impl CommunityView {
36   pub fn read(
37     conn: &PgConnection,
38     community_id: CommunityId,
39     my_person_id: Option<PersonId>,
40   ) -> Result<Self, Error> {
41     // The left join below will return None in this case
42     let person_id_join = my_person_id.unwrap_or(PersonId(-1));
43
44     let (community, counts, follower) = community::table
45       .find(community_id)
46       .inner_join(community_aggregates::table)
47       .left_join(
48         community_follower::table.on(
49           community::id
50             .eq(community_follower::community_id)
51             .and(community_follower::person_id.eq(person_id_join)),
52         ),
53       )
54       .select((
55         Community::safe_columns_tuple(),
56         community_aggregates::all_columns,
57         community_follower::all_columns.nullable(),
58       ))
59       .first::<CommunityViewTuple>(conn)?;
60
61     Ok(CommunityView {
62       community,
63       subscribed: follower.is_some(),
64       counts,
65     })
66   }
67
68   // TODO: this function is only used by is_mod_or_admin() below, can probably be merged
69   fn community_mods_and_admins(
70     conn: &PgConnection,
71     community_id: CommunityId,
72   ) -> Result<Vec<PersonId>, Error> {
73     let mut mods_and_admins: Vec<PersonId> = Vec::new();
74     mods_and_admins.append(
75       &mut CommunityModeratorView::for_community(conn, community_id)
76         .map(|v| v.into_iter().map(|m| m.moderator.id).collect())?,
77     );
78     mods_and_admins.append(
79       &mut PersonViewSafe::admins(conn).map(|v| v.into_iter().map(|a| a.person.id).collect())?,
80     );
81     Ok(mods_and_admins)
82   }
83
84   pub fn is_mod_or_admin(
85     conn: &PgConnection,
86     person_id: PersonId,
87     community_id: CommunityId,
88   ) -> bool {
89     Self::community_mods_and_admins(conn, community_id)
90       .unwrap_or_default()
91       .contains(&person_id)
92   }
93 }
94
95 pub struct CommunityQueryBuilder<'a> {
96   conn: &'a PgConnection,
97   listing_type: &'a ListingType,
98   sort: &'a SortType,
99   my_person_id: Option<PersonId>,
100   show_nsfw: bool,
101   search_term: Option<String>,
102   page: Option<i64>,
103   limit: Option<i64>,
104 }
105
106 impl<'a> CommunityQueryBuilder<'a> {
107   pub fn create(conn: &'a PgConnection) -> Self {
108     CommunityQueryBuilder {
109       conn,
110       my_person_id: None,
111       listing_type: &ListingType::All,
112       sort: &SortType::Hot,
113       show_nsfw: true,
114       search_term: None,
115       page: None,
116       limit: None,
117     }
118   }
119
120   pub fn listing_type(mut self, listing_type: &'a ListingType) -> Self {
121     self.listing_type = listing_type;
122     self
123   }
124
125   pub fn sort(mut self, sort: &'a SortType) -> Self {
126     self.sort = sort;
127     self
128   }
129
130   pub fn show_nsfw(mut self, show_nsfw: bool) -> Self {
131     self.show_nsfw = show_nsfw;
132     self
133   }
134
135   pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
136     self.search_term = search_term.get_optional();
137     self
138   }
139
140   pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
141     self.my_person_id = my_person_id.get_optional();
142     self
143   }
144
145   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
146     self.page = page.get_optional();
147     self
148   }
149
150   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
151     self.limit = limit.get_optional();
152     self
153   }
154
155   pub fn list(self) -> Result<Vec<CommunityView>, Error> {
156     // The left join below will return None in this case
157     let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
158
159     let mut query = community::table
160       .inner_join(community_aggregates::table)
161       .left_join(
162         community_follower::table.on(
163           community::id
164             .eq(community_follower::community_id)
165             .and(community_follower::person_id.eq(person_id_join)),
166         ),
167       )
168       .select((
169         Community::safe_columns_tuple(),
170         community_aggregates::all_columns,
171         community_follower::all_columns.nullable(),
172       ))
173       .into_boxed();
174
175     if let Some(search_term) = self.search_term {
176       let searcher = fuzzy_search(&search_term);
177       query = query
178         .filter(community::name.ilike(searcher.to_owned()))
179         .or_filter(community::title.ilike(searcher.to_owned()))
180         .or_filter(community::description.ilike(searcher));
181     };
182
183     match self.sort {
184       SortType::New => query = query.order_by(community::published.desc()),
185       SortType::TopAll => query = query.order_by(community_aggregates::subscribers.desc()),
186       SortType::TopMonth => query = query.order_by(community_aggregates::users_active_month.desc()),
187       // Covers all other sorts, including hot
188       _ => {
189         query = query
190           .order_by(
191             hot_rank(
192               community_aggregates::subscribers,
193               community_aggregates::published,
194             )
195             .desc(),
196           )
197           .then_order_by(community_aggregates::published.desc())
198       }
199     };
200
201     if !self.show_nsfw {
202       query = query.filter(community::nsfw.eq(false));
203     };
204
205     query = match self.listing_type {
206       ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
207       ListingType::Local => query.filter(community::local.eq(true)),
208       _ => query,
209     };
210
211     let (limit, offset) = limit_and_offset(self.page, self.limit);
212     let res = query
213       .limit(limit)
214       .offset(offset)
215       .filter(community::removed.eq(false))
216       .filter(community::deleted.eq(false))
217       .load::<CommunityViewTuple>(self.conn)?;
218
219     Ok(CommunityView::from_tuple_to_vec(res))
220   }
221 }
222
223 impl ViewToVec for CommunityView {
224   type DbTuple = CommunityViewTuple;
225   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
226     items
227       .iter()
228       .map(|a| Self {
229         community: a.0.to_owned(),
230         counts: a.1.to_owned(),
231         subscribed: a.2.is_some(),
232       })
233       .collect::<Vec<Self>>()
234   }
235 }