]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/community_view.rs
Merge crates db_schema and db_queries
[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},
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   // TODO: this function is only used by is_mod_or_admin() below, can probably be merged
78   fn community_mods_and_admins(
79     conn: &PgConnection,
80     community_id: CommunityId,
81   ) -> Result<Vec<PersonId>, Error> {
82     let mut mods_and_admins: Vec<PersonId> = Vec::new();
83     mods_and_admins.append(
84       &mut CommunityModeratorView::for_community(conn, community_id)
85         .map(|v| v.into_iter().map(|m| m.moderator.id).collect())?,
86     );
87     mods_and_admins.append(
88       &mut PersonViewSafe::admins(conn).map(|v| v.into_iter().map(|a| a.person.id).collect())?,
89     );
90     Ok(mods_and_admins)
91   }
92
93   pub fn is_mod_or_admin(
94     conn: &PgConnection,
95     person_id: PersonId,
96     community_id: CommunityId,
97   ) -> bool {
98     Self::community_mods_and_admins(conn, community_id)
99       .unwrap_or_default()
100       .contains(&person_id)
101   }
102 }
103
104 pub struct CommunityQueryBuilder<'a> {
105   conn: &'a PgConnection,
106   listing_type: Option<ListingType>,
107   sort: Option<SortType>,
108   my_person_id: Option<PersonId>,
109   show_nsfw: Option<bool>,
110   search_term: Option<String>,
111   page: Option<i64>,
112   limit: Option<i64>,
113 }
114
115 impl<'a> CommunityQueryBuilder<'a> {
116   pub fn create(conn: &'a PgConnection) -> Self {
117     CommunityQueryBuilder {
118       conn,
119       my_person_id: None,
120       listing_type: None,
121       sort: None,
122       show_nsfw: None,
123       search_term: None,
124       page: None,
125       limit: None,
126     }
127   }
128
129   pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
130     self.listing_type = listing_type.get_optional();
131     self
132   }
133
134   pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
135     self.sort = sort.get_optional();
136     self
137   }
138
139   pub fn show_nsfw<T: MaybeOptional<bool>>(mut self, show_nsfw: T) -> Self {
140     self.show_nsfw = show_nsfw.get_optional();
141     self
142   }
143
144   pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
145     self.search_term = search_term.get_optional();
146     self
147   }
148
149   pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
150     self.my_person_id = my_person_id.get_optional();
151     self
152   }
153
154   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
155     self.page = page.get_optional();
156     self
157   }
158
159   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
160     self.limit = limit.get_optional();
161     self
162   }
163
164   pub fn list(self) -> Result<Vec<CommunityView>, Error> {
165     // The left join below will return None in this case
166     let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
167
168     let mut query = community::table
169       .inner_join(community_aggregates::table)
170       .left_join(
171         community_follower::table.on(
172           community::id
173             .eq(community_follower::community_id)
174             .and(community_follower::person_id.eq(person_id_join)),
175         ),
176       )
177       .left_join(
178         community_block::table.on(
179           community::id
180             .eq(community_block::community_id)
181             .and(community_block::person_id.eq(person_id_join)),
182         ),
183       )
184       .select((
185         Community::safe_columns_tuple(),
186         community_aggregates::all_columns,
187         community_follower::all_columns.nullable(),
188         community_block::all_columns.nullable(),
189       ))
190       .into_boxed();
191
192     if let Some(search_term) = self.search_term {
193       let searcher = fuzzy_search(&search_term);
194       query = query
195         .filter(community::name.ilike(searcher.to_owned()))
196         .or_filter(community::title.ilike(searcher.to_owned()))
197         .or_filter(community::description.ilike(searcher));
198     };
199
200     match self.sort.unwrap_or(SortType::Hot) {
201       SortType::New => query = query.order_by(community::published.desc()),
202       SortType::TopAll => query = query.order_by(community_aggregates::subscribers.desc()),
203       SortType::TopMonth => query = query.order_by(community_aggregates::users_active_month.desc()),
204       // Covers all other sorts, including hot
205       _ => {
206         query = query
207           .order_by(
208             hot_rank(
209               community_aggregates::subscribers,
210               community_aggregates::published,
211             )
212             .desc(),
213           )
214           .then_order_by(community_aggregates::published.desc())
215       }
216     };
217
218     if !self.show_nsfw.unwrap_or(false) {
219       query = query.filter(community::nsfw.eq(false));
220     };
221
222     if let Some(listing_type) = self.listing_type {
223       query = match listing_type {
224         ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
225         ListingType::Local => query.filter(community::local.eq(true)),
226         _ => query,
227       };
228     }
229
230     // Don't show blocked communities
231     if self.my_person_id.is_some() {
232       query = query.filter(community_block::person_id.is_null());
233     }
234
235     let (limit, offset) = limit_and_offset(self.page, self.limit);
236     let res = query
237       .limit(limit)
238       .offset(offset)
239       .filter(community::removed.eq(false))
240       .filter(community::deleted.eq(false))
241       .load::<CommunityViewTuple>(self.conn)?;
242
243     Ok(CommunityView::from_tuple_to_vec(res))
244   }
245 }
246
247 impl ViewToVec for CommunityView {
248   type DbTuple = CommunityViewTuple;
249   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
250     items
251       .iter()
252       .map(|a| Self {
253         community: a.0.to_owned(),
254         counts: a.1.to_owned(),
255         subscribed: a.2.is_some(),
256         blocked: a.3.is_some(),
257       })
258       .collect::<Vec<Self>>()
259   }
260 }