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