]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/community_view.rs
Implement restricted community (only mods can post) (fixes #187) (#2235)
[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_schema::{
4   aggregates::community_aggregates::CommunityAggregates,
5   functions::hot_rank,
6   fuzzy_search,
7   limit_and_offset,
8   newtypes::{CommunityId, PersonId},
9   schema::{community, community_aggregates, community_block, community_follower, local_user},
10   source::{
11     community::{Community, CommunityFollower, CommunitySafe},
12     community_block::CommunityBlock,
13   },
14   traits::{MaybeOptional, ToSafe, ViewToVec},
15   ListingType,
16   SortType,
17 };
18 use serde::{Deserialize, Serialize};
19
20 #[derive(Debug, Serialize, Deserialize, Clone)]
21 pub struct CommunityView {
22   pub community: CommunitySafe,
23   pub subscribed: bool,
24   pub blocked: bool,
25   pub counts: CommunityAggregates,
26 }
27
28 type CommunityViewTuple = (
29   CommunitySafe,
30   CommunityAggregates,
31   Option<CommunityFollower>,
32   Option<CommunityBlock>,
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, blocked) = 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       .left_join(
55         community_block::table.on(
56           community::id
57             .eq(community_block::community_id)
58             .and(community_block::person_id.eq(person_id_join)),
59         ),
60       )
61       .select((
62         Community::safe_columns_tuple(),
63         community_aggregates::all_columns,
64         community_follower::all_columns.nullable(),
65         community_block::all_columns.nullable(),
66       ))
67       .first::<CommunityViewTuple>(conn)?;
68
69     Ok(CommunityView {
70       community,
71       subscribed: follower.is_some(),
72       blocked: blocked.is_some(),
73       counts,
74     })
75   }
76
77   pub fn is_mod_or_admin(
78     conn: &PgConnection,
79     person_id: PersonId,
80     community_id: CommunityId,
81   ) -> bool {
82     let is_mod = CommunityModeratorView::for_community(conn, community_id)
83       .map(|v| {
84         v.into_iter()
85           .map(|m| m.moderator.id)
86           .collect::<Vec<PersonId>>()
87       })
88       .unwrap_or_default()
89       .contains(&person_id);
90     if is_mod {
91       return true;
92     }
93
94     PersonViewSafe::admins(conn)
95       .map(|v| {
96         v.into_iter()
97           .map(|a| a.person.id)
98           .collect::<Vec<PersonId>>()
99       })
100       .unwrap_or_default()
101       .contains(&person_id)
102   }
103 }
104
105 pub struct CommunityQueryBuilder<'a> {
106   conn: &'a PgConnection,
107   listing_type: Option<ListingType>,
108   sort: Option<SortType>,
109   my_person_id: Option<PersonId>,
110   show_nsfw: Option<bool>,
111   search_term: Option<String>,
112   page: Option<i64>,
113   limit: Option<i64>,
114 }
115
116 impl<'a> CommunityQueryBuilder<'a> {
117   pub fn create(conn: &'a PgConnection) -> Self {
118     CommunityQueryBuilder {
119       conn,
120       my_person_id: None,
121       listing_type: None,
122       sort: None,
123       show_nsfw: None,
124       search_term: None,
125       page: None,
126       limit: None,
127     }
128   }
129
130   pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
131     self.listing_type = listing_type.get_optional();
132     self
133   }
134
135   pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
136     self.sort = sort.get_optional();
137     self
138   }
139
140   pub fn show_nsfw<T: MaybeOptional<bool>>(mut self, show_nsfw: T) -> Self {
141     self.show_nsfw = show_nsfw.get_optional();
142     self
143   }
144
145   pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
146     self.search_term = search_term.get_optional();
147     self
148   }
149
150   pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
151     self.my_person_id = my_person_id.get_optional();
152     self
153   }
154
155   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
156     self.page = page.get_optional();
157     self
158   }
159
160   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
161     self.limit = limit.get_optional();
162     self
163   }
164
165   pub fn list(self) -> Result<Vec<CommunityView>, Error> {
166     // The left join below will return None in this case
167     let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
168
169     let mut query = community::table
170       .inner_join(community_aggregates::table)
171       .left_join(local_user::table.on(local_user::person_id.eq(person_id_join)))
172       .left_join(
173         community_follower::table.on(
174           community::id
175             .eq(community_follower::community_id)
176             .and(community_follower::person_id.eq(person_id_join)),
177         ),
178       )
179       .left_join(
180         community_block::table.on(
181           community::id
182             .eq(community_block::community_id)
183             .and(community_block::person_id.eq(person_id_join)),
184         ),
185       )
186       .select((
187         Community::safe_columns_tuple(),
188         community_aggregates::all_columns,
189         community_follower::all_columns.nullable(),
190         community_block::all_columns.nullable(),
191       ))
192       .into_boxed();
193
194     if let Some(search_term) = self.search_term {
195       let searcher = fuzzy_search(&search_term);
196       query = query
197         .filter(community::name.ilike(searcher.to_owned()))
198         .or_filter(community::title.ilike(searcher.to_owned()))
199         .or_filter(community::description.ilike(searcher));
200     };
201
202     match self.sort.unwrap_or(SortType::Hot) {
203       SortType::New => query = query.order_by(community::published.desc()),
204       SortType::TopAll => query = query.order_by(community_aggregates::subscribers.desc()),
205       SortType::TopMonth => query = query.order_by(community_aggregates::users_active_month.desc()),
206       SortType::Hot => {
207         query = query
208           .order_by(
209             hot_rank(
210               community_aggregates::subscribers,
211               community_aggregates::published,
212             )
213             .desc(),
214           )
215           .then_order_by(community_aggregates::published.desc());
216         // Don't show hidden communities in Hot (trending)
217         query = query.filter(
218           community::hidden
219             .eq(false)
220             .or(community_follower::person_id.eq(person_id_join)),
221         );
222       }
223       // Covers all other sorts
224       _ => {
225         query = query
226           .order_by(
227             hot_rank(
228               community_aggregates::subscribers,
229               community_aggregates::published,
230             )
231             .desc(),
232           )
233           .then_order_by(community_aggregates::published.desc())
234       }
235     };
236
237     if let Some(listing_type) = self.listing_type {
238       query = match listing_type {
239         ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
240         ListingType::Local => query.filter(community::local.eq(true)),
241         _ => query,
242       };
243     }
244
245     // Don't show blocked communities or nsfw communities if not enabled in profile
246     if self.my_person_id.is_some() {
247       query = query.filter(community_block::person_id.is_null());
248       query = query.filter(community::nsfw.eq(false).or(local_user::show_nsfw.eq(true)));
249     } else {
250       // No person in request, only show nsfw communities if show_nsfw passed into request
251       if !self.show_nsfw.unwrap_or(false) {
252         query = query.filter(community::nsfw.eq(false));
253       }
254     }
255
256     let (limit, offset) = limit_and_offset(self.page, self.limit);
257     let res = query
258       .limit(limit)
259       .offset(offset)
260       .filter(community::removed.eq(false))
261       .filter(community::deleted.eq(false))
262       .load::<CommunityViewTuple>(self.conn)?;
263
264     Ok(CommunityView::from_tuple_to_vec(res))
265   }
266 }
267
268 impl ViewToVec for CommunityView {
269   type DbTuple = CommunityViewTuple;
270   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
271     items
272       .iter()
273       .map(|a| Self {
274         community: a.0.to_owned(),
275         counts: a.1.to_owned(),
276         subscribed: a.2.is_some(),
277         blocked: a.3.is_some(),
278       })
279       .collect::<Vec<Self>>()
280   }
281 }