]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/person_mention_view.rs
First pass at adding comment trees. (#2362)
[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   CommentSortType,
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       follower,
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: CommunityFollower::to_subscribed_type(&follower),
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<CommentSortType>,
167   unread_only: Option<bool>,
168   show_bot_accounts: Option<bool>,
169   page: Option<i64>,
170   limit: Option<i64>,
171 }
172
173 impl<'a> PersonMentionQueryBuilder<'a> {
174   pub fn create(conn: &'a PgConnection) -> Self {
175     PersonMentionQueryBuilder {
176       conn,
177       my_person_id: None,
178       recipient_id: None,
179       sort: None,
180       unread_only: None,
181       show_bot_accounts: None,
182       page: None,
183       limit: None,
184     }
185   }
186
187   pub fn sort<T: MaybeOptional<CommentSortType>>(mut self, sort: T) -> Self {
188     self.sort = sort.get_optional();
189     self
190   }
191
192   pub fn unread_only<T: MaybeOptional<bool>>(mut self, unread_only: T) -> Self {
193     self.unread_only = unread_only.get_optional();
194     self
195   }
196
197   pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
198     self.show_bot_accounts = show_bot_accounts.get_optional();
199     self
200   }
201
202   pub fn recipient_id<T: MaybeOptional<PersonId>>(mut self, recipient_id: T) -> Self {
203     self.recipient_id = recipient_id.get_optional();
204     self
205   }
206
207   pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
208     self.my_person_id = my_person_id.get_optional();
209     self
210   }
211
212   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
213     self.page = page.get_optional();
214     self
215   }
216
217   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
218     self.limit = limit.get_optional();
219     self
220   }
221
222   pub fn list(self) -> Result<Vec<PersonMentionView>, Error> {
223     use diesel::dsl::*;
224
225     // The left join below will return None in this case
226     let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
227
228     let mut query = person_mention::table
229       .inner_join(comment::table)
230       .inner_join(person::table.on(comment::creator_id.eq(person::id)))
231       .inner_join(post::table.on(comment::post_id.eq(post::id)))
232       .inner_join(community::table.on(post::community_id.eq(community::id)))
233       .inner_join(person_alias_1::table)
234       .inner_join(comment_aggregates::table.on(comment::id.eq(comment_aggregates::comment_id)))
235       .left_join(
236         community_person_ban::table.on(
237           community::id
238             .eq(community_person_ban::community_id)
239             .and(community_person_ban::person_id.eq(comment::creator_id))
240             .and(
241               community_person_ban::expires
242                 .is_null()
243                 .or(community_person_ban::expires.gt(now)),
244             ),
245         ),
246       )
247       .left_join(
248         community_follower::table.on(
249           post::community_id
250             .eq(community_follower::community_id)
251             .and(community_follower::person_id.eq(person_id_join)),
252         ),
253       )
254       .left_join(
255         comment_saved::table.on(
256           comment::id
257             .eq(comment_saved::comment_id)
258             .and(comment_saved::person_id.eq(person_id_join)),
259         ),
260       )
261       .left_join(
262         person_block::table.on(
263           comment::creator_id
264             .eq(person_block::target_id)
265             .and(person_block::person_id.eq(person_id_join)),
266         ),
267       )
268       .left_join(
269         comment_like::table.on(
270           comment::id
271             .eq(comment_like::comment_id)
272             .and(comment_like::person_id.eq(person_id_join)),
273         ),
274       )
275       .select((
276         person_mention::all_columns,
277         comment::all_columns,
278         Person::safe_columns_tuple(),
279         post::all_columns,
280         Community::safe_columns_tuple(),
281         PersonAlias1::safe_columns_tuple(),
282         comment_aggregates::all_columns,
283         community_person_ban::all_columns.nullable(),
284         community_follower::all_columns.nullable(),
285         comment_saved::all_columns.nullable(),
286         person_block::all_columns.nullable(),
287         comment_like::score.nullable(),
288       ))
289       .into_boxed();
290
291     if let Some(recipient_id) = self.recipient_id {
292       query = query.filter(person_mention::recipient_id.eq(recipient_id));
293     }
294
295     if self.unread_only.unwrap_or(false) {
296       query = query.filter(person_mention::read.eq(false));
297     }
298
299     if !self.show_bot_accounts.unwrap_or(true) {
300       query = query.filter(person::bot_account.eq(false));
301     };
302
303     query = match self.sort.unwrap_or(CommentSortType::Hot) {
304       CommentSortType::Hot => query
305         .then_order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
306         .then_order_by(comment_aggregates::published.desc()),
307       CommentSortType::New => query.then_order_by(comment::published.desc()),
308       CommentSortType::Old => query.then_order_by(comment::published.asc()),
309       CommentSortType::Top => query.order_by(comment_aggregates::score.desc()),
310     };
311
312     let (limit, offset) = limit_and_offset(self.page, self.limit)?;
313
314     let res = query
315       .limit(limit)
316       .offset(offset)
317       .load::<PersonMentionViewTuple>(self.conn)?;
318
319     Ok(PersonMentionView::from_tuple_to_vec(res))
320   }
321 }
322
323 impl ViewToVec for PersonMentionView {
324   type DbTuple = PersonMentionViewTuple;
325   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
326     items
327       .iter()
328       .map(|a| Self {
329         person_mention: a.0.to_owned(),
330         comment: a.1.to_owned(),
331         creator: a.2.to_owned(),
332         post: a.3.to_owned(),
333         community: a.4.to_owned(),
334         recipient: a.5.to_owned(),
335         counts: a.6.to_owned(),
336         creator_banned_from_community: a.7.is_some(),
337         subscribed: CommunityFollower::to_subscribed_type(&a.8),
338         saved: a.9.is_some(),
339         creator_blocked: a.10.is_some(),
340         my_vote: a.11,
341       })
342       .collect::<Vec<Self>>()
343   }
344 }