]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/person_mention_view.rs
Derive default for api request structs, move type enums (#2245)
[lemmy.git] / crates / db_views_actor / src / person_mention_view.rs
1 use crate::structs::PersonMentionView;
2 use diesel::{dsl::*, result::Error, *};
3 use lemmy_db_schema::{
4   aggregates::structs::CommentAggregates,
5   newtypes::{PersonId, PersonMentionId},
6   schema::{
7     comment,
8     comment_aggregates,
9     comment_like,
10     comment_saved,
11     community,
12     community_follower,
13     community_person_ban,
14     person,
15     person_alias_1,
16     person_block,
17     person_mention,
18     post,
19   },
20   source::{
21     comment::{Comment, CommentSaved},
22     community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
23     person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1},
24     person_block::PersonBlock,
25     person_mention::PersonMention,
26     post::Post,
27   },
28   traits::{MaybeOptional, ToSafe, ViewToVec},
29   utils::{functions::hot_rank, limit_and_offset},
30   SortType,
31 };
32
33 type PersonMentionViewTuple = (
34   PersonMention,
35   Comment,
36   PersonSafe,
37   Post,
38   CommunitySafe,
39   PersonSafeAlias1,
40   CommentAggregates,
41   Option<CommunityPersonBan>,
42   Option<CommunityFollower>,
43   Option<CommentSaved>,
44   Option<PersonBlock>,
45   Option<i16>,
46 );
47
48 impl PersonMentionView {
49   pub fn read(
50     conn: &PgConnection,
51     person_mention_id: PersonMentionId,
52     my_person_id: Option<PersonId>,
53   ) -> Result<Self, Error> {
54     // The left join below will return None in this case
55     let person_id_join = my_person_id.unwrap_or(PersonId(-1));
56
57     let (
58       person_mention,
59       comment,
60       creator,
61       post,
62       community,
63       recipient,
64       counts,
65       creator_banned_from_community,
66       subscribed,
67       saved,
68       creator_blocked,
69       my_vote,
70     ) = person_mention::table
71       .find(person_mention_id)
72       .inner_join(comment::table)
73       .inner_join(person::table.on(comment::creator_id.eq(person::id)))
74       .inner_join(post::table.on(comment::post_id.eq(post::id)))
75       .inner_join(community::table.on(post::community_id.eq(community::id)))
76       .inner_join(person_alias_1::table)
77       .inner_join(comment_aggregates::table.on(comment::id.eq(comment_aggregates::comment_id)))
78       .left_join(
79         community_person_ban::table.on(
80           community::id
81             .eq(community_person_ban::community_id)
82             .and(community_person_ban::person_id.eq(comment::creator_id))
83             .and(
84               community_person_ban::expires
85                 .is_null()
86                 .or(community_person_ban::expires.gt(now)),
87             ),
88         ),
89       )
90       .left_join(
91         community_follower::table.on(
92           post::community_id
93             .eq(community_follower::community_id)
94             .and(community_follower::person_id.eq(person_id_join)),
95         ),
96       )
97       .left_join(
98         comment_saved::table.on(
99           comment::id
100             .eq(comment_saved::comment_id)
101             .and(comment_saved::person_id.eq(person_id_join)),
102         ),
103       )
104       .left_join(
105         person_block::table.on(
106           comment::creator_id
107             .eq(person_block::target_id)
108             .and(person_block::person_id.eq(person_id_join)),
109         ),
110       )
111       .left_join(
112         comment_like::table.on(
113           comment::id
114             .eq(comment_like::comment_id)
115             .and(comment_like::person_id.eq(person_id_join)),
116         ),
117       )
118       .select((
119         person_mention::all_columns,
120         comment::all_columns,
121         Person::safe_columns_tuple(),
122         post::all_columns,
123         Community::safe_columns_tuple(),
124         PersonAlias1::safe_columns_tuple(),
125         comment_aggregates::all_columns,
126         community_person_ban::all_columns.nullable(),
127         community_follower::all_columns.nullable(),
128         comment_saved::all_columns.nullable(),
129         person_block::all_columns.nullable(),
130         comment_like::score.nullable(),
131       ))
132       .first::<PersonMentionViewTuple>(conn)?;
133
134     Ok(PersonMentionView {
135       person_mention,
136       comment,
137       creator,
138       post,
139       community,
140       recipient,
141       counts,
142       creator_banned_from_community: creator_banned_from_community.is_some(),
143       subscribed: subscribed.is_some(),
144       saved: saved.is_some(),
145       creator_blocked: creator_blocked.is_some(),
146       my_vote,
147     })
148   }
149
150   /// Gets the number of unread mentions
151   pub fn get_unread_mentions(conn: &PgConnection, my_person_id: PersonId) -> Result<i64, Error> {
152     use diesel::dsl::*;
153
154     person_mention::table
155       .filter(person_mention::recipient_id.eq(my_person_id))
156       .filter(person_mention::read.eq(false))
157       .select(count(person_mention::id))
158       .first::<i64>(conn)
159   }
160 }
161
162 pub struct PersonMentionQueryBuilder<'a> {
163   conn: &'a PgConnection,
164   my_person_id: Option<PersonId>,
165   recipient_id: Option<PersonId>,
166   sort: Option<SortType>,
167   unread_only: Option<bool>,
168   page: Option<i64>,
169   limit: Option<i64>,
170 }
171
172 impl<'a> PersonMentionQueryBuilder<'a> {
173   pub fn create(conn: &'a PgConnection) -> Self {
174     PersonMentionQueryBuilder {
175       conn,
176       my_person_id: None,
177       recipient_id: None,
178       sort: None,
179       unread_only: None,
180       page: None,
181       limit: None,
182     }
183   }
184
185   pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
186     self.sort = sort.get_optional();
187     self
188   }
189
190   pub fn unread_only<T: MaybeOptional<bool>>(mut self, unread_only: T) -> Self {
191     self.unread_only = unread_only.get_optional();
192     self
193   }
194
195   pub fn recipient_id<T: MaybeOptional<PersonId>>(mut self, recipient_id: T) -> Self {
196     self.recipient_id = recipient_id.get_optional();
197     self
198   }
199
200   pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
201     self.my_person_id = my_person_id.get_optional();
202     self
203   }
204
205   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
206     self.page = page.get_optional();
207     self
208   }
209
210   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
211     self.limit = limit.get_optional();
212     self
213   }
214
215   pub fn list(self) -> Result<Vec<PersonMentionView>, Error> {
216     use diesel::dsl::*;
217
218     // The left join below will return None in this case
219     let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
220
221     let mut query = person_mention::table
222       .inner_join(comment::table)
223       .inner_join(person::table.on(comment::creator_id.eq(person::id)))
224       .inner_join(post::table.on(comment::post_id.eq(post::id)))
225       .inner_join(community::table.on(post::community_id.eq(community::id)))
226       .inner_join(person_alias_1::table)
227       .inner_join(comment_aggregates::table.on(comment::id.eq(comment_aggregates::comment_id)))
228       .left_join(
229         community_person_ban::table.on(
230           community::id
231             .eq(community_person_ban::community_id)
232             .and(community_person_ban::person_id.eq(comment::creator_id))
233             .and(
234               community_person_ban::expires
235                 .is_null()
236                 .or(community_person_ban::expires.gt(now)),
237             ),
238         ),
239       )
240       .left_join(
241         community_follower::table.on(
242           post::community_id
243             .eq(community_follower::community_id)
244             .and(community_follower::person_id.eq(person_id_join)),
245         ),
246       )
247       .left_join(
248         comment_saved::table.on(
249           comment::id
250             .eq(comment_saved::comment_id)
251             .and(comment_saved::person_id.eq(person_id_join)),
252         ),
253       )
254       .left_join(
255         person_block::table.on(
256           comment::creator_id
257             .eq(person_block::target_id)
258             .and(person_block::person_id.eq(person_id_join)),
259         ),
260       )
261       .left_join(
262         comment_like::table.on(
263           comment::id
264             .eq(comment_like::comment_id)
265             .and(comment_like::person_id.eq(person_id_join)),
266         ),
267       )
268       .select((
269         person_mention::all_columns,
270         comment::all_columns,
271         Person::safe_columns_tuple(),
272         post::all_columns,
273         Community::safe_columns_tuple(),
274         PersonAlias1::safe_columns_tuple(),
275         comment_aggregates::all_columns,
276         community_person_ban::all_columns.nullable(),
277         community_follower::all_columns.nullable(),
278         comment_saved::all_columns.nullable(),
279         person_block::all_columns.nullable(),
280         comment_like::score.nullable(),
281       ))
282       .into_boxed();
283
284     if let Some(recipient_id) = self.recipient_id {
285       query = query.filter(person_mention::recipient_id.eq(recipient_id));
286     }
287
288     if self.unread_only.unwrap_or(false) {
289       query = query.filter(person_mention::read.eq(false));
290     }
291
292     query = match self.sort.unwrap_or(SortType::Hot) {
293       SortType::Hot | SortType::Active => query
294         .order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
295         .then_order_by(comment_aggregates::published.desc()),
296       SortType::New | SortType::MostComments | SortType::NewComments => {
297         query.order_by(comment::published.desc())
298       }
299       SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
300       SortType::TopYear => query
301         .filter(comment::published.gt(now - 1.years()))
302         .order_by(comment_aggregates::score.desc()),
303       SortType::TopMonth => query
304         .filter(comment::published.gt(now - 1.months()))
305         .order_by(comment_aggregates::score.desc()),
306       SortType::TopWeek => query
307         .filter(comment::published.gt(now - 1.weeks()))
308         .order_by(comment_aggregates::score.desc()),
309       SortType::TopDay => query
310         .filter(comment::published.gt(now - 1.days()))
311         .order_by(comment_aggregates::score.desc()),
312     };
313
314     let (limit, offset) = limit_and_offset(self.page, self.limit);
315
316     let res = query
317       .limit(limit)
318       .offset(offset)
319       .load::<PersonMentionViewTuple>(self.conn)?;
320
321     Ok(PersonMentionView::from_tuple_to_vec(res))
322   }
323 }
324
325 impl ViewToVec for PersonMentionView {
326   type DbTuple = PersonMentionViewTuple;
327   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
328     items
329       .iter()
330       .map(|a| Self {
331         person_mention: a.0.to_owned(),
332         comment: a.1.to_owned(),
333         creator: a.2.to_owned(),
334         post: a.3.to_owned(),
335         community: a.4.to_owned(),
336         recipient: a.5.to_owned(),
337         counts: a.6.to_owned(),
338         creator_banned_from_community: a.7.is_some(),
339         subscribed: a.8.is_some(),
340         saved: a.9.is_some(),
341         creator_blocked: a.10.is_some(),
342         my_vote: a.11,
343       })
344       .collect::<Vec<Self>>()
345   }
346 }