]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/community_view.rs
Merge pull request #1428 from LemmyNet/split_user_table
[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, person},
16   source::{
17     community::{Community, CommunityFollower, CommunitySafe},
18     person::{Person, PersonSafe},
19   },
20 };
21 use serde::Serialize;
22
23 #[derive(Debug, Serialize, Clone)]
24 pub struct CommunityView {
25   pub community: CommunitySafe,
26   pub creator: PersonSafe,
27   pub subscribed: bool,
28   pub counts: CommunityAggregates,
29 }
30
31 type CommunityViewTuple = (
32   CommunitySafe,
33   PersonSafe,
34   CommunityAggregates,
35   Option<CommunityFollower>,
36 );
37
38 impl CommunityView {
39   pub fn read(
40     conn: &PgConnection,
41     community_id: i32,
42     my_person_id: Option<i32>,
43   ) -> Result<Self, Error> {
44     // The left join below will return None in this case
45     let person_id_join = my_person_id.unwrap_or(-1);
46
47     let (community, creator, counts, follower) = community::table
48       .find(community_id)
49       .inner_join(person::table)
50       .inner_join(community_aggregates::table)
51       .left_join(
52         community_follower::table.on(
53           community::id
54             .eq(community_follower::community_id)
55             .and(community_follower::person_id.eq(person_id_join)),
56         ),
57       )
58       .select((
59         Community::safe_columns_tuple(),
60         Person::safe_columns_tuple(),
61         community_aggregates::all_columns,
62         community_follower::all_columns.nullable(),
63       ))
64       .first::<CommunityViewTuple>(conn)?;
65
66     Ok(CommunityView {
67       community,
68       creator,
69       subscribed: follower.is_some(),
70       counts,
71     })
72   }
73
74   // TODO: this function is only used by is_mod_or_admin() below, can probably be merged
75   fn community_mods_and_admins(conn: &PgConnection, community_id: i32) -> Result<Vec<i32>, Error> {
76     let mut mods_and_admins: Vec<i32> = Vec::new();
77     mods_and_admins.append(
78       &mut CommunityModeratorView::for_community(conn, community_id)
79         .map(|v| v.into_iter().map(|m| m.moderator.id).collect())?,
80     );
81     mods_and_admins.append(
82       &mut PersonViewSafe::admins(conn).map(|v| v.into_iter().map(|a| a.person.id).collect())?,
83     );
84     Ok(mods_and_admins)
85   }
86
87   pub fn is_mod_or_admin(conn: &PgConnection, person_id: i32, community_id: i32) -> bool {
88     Self::community_mods_and_admins(conn, community_id)
89       .unwrap_or_default()
90       .contains(&person_id)
91   }
92 }
93
94 pub struct CommunityQueryBuilder<'a> {
95   conn: &'a PgConnection,
96   listing_type: &'a ListingType,
97   sort: &'a SortType,
98   my_person_id: Option<i32>,
99   show_nsfw: bool,
100   search_term: Option<String>,
101   page: Option<i64>,
102   limit: Option<i64>,
103 }
104
105 impl<'a> CommunityQueryBuilder<'a> {
106   pub fn create(conn: &'a PgConnection) -> Self {
107     CommunityQueryBuilder {
108       conn,
109       my_person_id: None,
110       listing_type: &ListingType::All,
111       sort: &SortType::Hot,
112       show_nsfw: true,
113       search_term: None,
114       page: None,
115       limit: None,
116     }
117   }
118
119   pub fn listing_type(mut self, listing_type: &'a ListingType) -> Self {
120     self.listing_type = listing_type;
121     self
122   }
123
124   pub fn sort(mut self, sort: &'a SortType) -> Self {
125     self.sort = sort;
126     self
127   }
128
129   pub fn show_nsfw(mut self, show_nsfw: bool) -> Self {
130     self.show_nsfw = show_nsfw;
131     self
132   }
133
134   pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
135     self.search_term = search_term.get_optional();
136     self
137   }
138
139   pub fn my_person_id<T: MaybeOptional<i32>>(mut self, my_person_id: T) -> Self {
140     self.my_person_id = my_person_id.get_optional();
141     self
142   }
143
144   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
145     self.page = page.get_optional();
146     self
147   }
148
149   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
150     self.limit = limit.get_optional();
151     self
152   }
153
154   pub fn list(self) -> Result<Vec<CommunityView>, Error> {
155     // The left join below will return None in this case
156     let person_id_join = self.my_person_id.unwrap_or(-1);
157
158     let mut query = community::table
159       .inner_join(person::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         Person::safe_columns_tuple(),
171         community_aggregates::all_columns,
172         community_follower::all_columns.nullable(),
173       ))
174       .into_boxed();
175
176     if let Some(search_term) = self.search_term {
177       let searcher = fuzzy_search(&search_term);
178       query = query
179         .filter(community::name.ilike(searcher.to_owned()))
180         .or_filter(community::title.ilike(searcher.to_owned()))
181         .or_filter(community::description.ilike(searcher));
182     };
183
184     match self.sort {
185       SortType::New => query = query.order_by(community::published.desc()),
186       SortType::TopAll => query = query.order_by(community_aggregates::subscribers.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         creator: a.1.to_owned(),
231         counts: a.2.to_owned(),
232         subscribed: a.3.is_some(),
233       })
234       .collect::<Vec<Self>>()
235   }
236 }