]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/person_mention_view.rs
Check to make sure comment isnt deleted / removed for unread count. (#2472)
[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_block,
16     person_mention,
17     post,
18   },
19   source::{
20     comment::{Comment, CommentSaved},
21     community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
22     person::{Person, PersonSafe},
23     person_block::PersonBlock,
24     person_mention::PersonMention,
25     post::Post,
26   },
27   traits::{ToSafe, ViewToVec},
28   utils::{functions::hot_rank, limit_and_offset},
29   CommentSortType,
30 };
31 use typed_builder::TypedBuilder;
32
33 type PersonMentionViewTuple = (
34   PersonMention,
35   Comment,
36   PersonSafe,
37   Post,
38   CommunitySafe,
39   PersonSafe,
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: &mut PgConnection,
51     person_mention_id: PersonMentionId,
52     my_person_id: Option<PersonId>,
53   ) -> Result<Self, Error> {
54     let person_alias_1 = diesel::alias!(person as person1);
55
56     // The left join below will return None in this case
57     let person_id_join = my_person_id.unwrap_or(PersonId(-1));
58
59     let (
60       person_mention,
61       comment,
62       creator,
63       post,
64       community,
65       recipient,
66       counts,
67       creator_banned_from_community,
68       follower,
69       saved,
70       creator_blocked,
71       my_vote,
72     ) = person_mention::table
73       .find(person_mention_id)
74       .inner_join(comment::table)
75       .inner_join(person::table.on(comment::creator_id.eq(person::id)))
76       .inner_join(post::table.on(comment::post_id.eq(post::id)))
77       .inner_join(community::table.on(post::community_id.eq(community::id)))
78       .inner_join(person_alias_1)
79       .inner_join(comment_aggregates::table.on(comment::id.eq(comment_aggregates::comment_id)))
80       .left_join(
81         community_person_ban::table.on(
82           community::id
83             .eq(community_person_ban::community_id)
84             .and(community_person_ban::person_id.eq(comment::creator_id))
85             .and(
86               community_person_ban::expires
87                 .is_null()
88                 .or(community_person_ban::expires.gt(now)),
89             ),
90         ),
91       )
92       .left_join(
93         community_follower::table.on(
94           post::community_id
95             .eq(community_follower::community_id)
96             .and(community_follower::person_id.eq(person_id_join)),
97         ),
98       )
99       .left_join(
100         comment_saved::table.on(
101           comment::id
102             .eq(comment_saved::comment_id)
103             .and(comment_saved::person_id.eq(person_id_join)),
104         ),
105       )
106       .left_join(
107         person_block::table.on(
108           comment::creator_id
109             .eq(person_block::target_id)
110             .and(person_block::person_id.eq(person_id_join)),
111         ),
112       )
113       .left_join(
114         comment_like::table.on(
115           comment::id
116             .eq(comment_like::comment_id)
117             .and(comment_like::person_id.eq(person_id_join)),
118         ),
119       )
120       .select((
121         person_mention::all_columns,
122         comment::all_columns,
123         Person::safe_columns_tuple(),
124         post::all_columns,
125         Community::safe_columns_tuple(),
126         person_alias_1.fields(Person::safe_columns_tuple()),
127         comment_aggregates::all_columns,
128         community_person_ban::all_columns.nullable(),
129         community_follower::all_columns.nullable(),
130         comment_saved::all_columns.nullable(),
131         person_block::all_columns.nullable(),
132         comment_like::score.nullable(),
133       ))
134       .first::<PersonMentionViewTuple>(conn)?;
135
136     Ok(PersonMentionView {
137       person_mention,
138       comment,
139       creator,
140       post,
141       community,
142       recipient,
143       counts,
144       creator_banned_from_community: creator_banned_from_community.is_some(),
145       subscribed: CommunityFollower::to_subscribed_type(&follower),
146       saved: saved.is_some(),
147       creator_blocked: creator_blocked.is_some(),
148       my_vote,
149     })
150   }
151
152   /// Gets the number of unread mentions
153   pub fn get_unread_mentions(
154     conn: &mut PgConnection,
155     my_person_id: PersonId,
156   ) -> Result<i64, Error> {
157     use diesel::dsl::*;
158
159     person_mention::table
160       .inner_join(comment::table)
161       .filter(person_mention::recipient_id.eq(my_person_id))
162       .filter(person_mention::read.eq(false))
163       .filter(comment::deleted.eq(false))
164       .filter(comment::removed.eq(false))
165       .select(count(person_mention::id))
166       .first::<i64>(conn)
167   }
168 }
169
170 #[derive(TypedBuilder)]
171 #[builder(field_defaults(default))]
172 pub struct PersonMentionQuery<'a> {
173   #[builder(!default)]
174   conn: &'a mut PgConnection,
175   my_person_id: Option<PersonId>,
176   recipient_id: Option<PersonId>,
177   sort: Option<CommentSortType>,
178   unread_only: Option<bool>,
179   show_bot_accounts: Option<bool>,
180   page: Option<i64>,
181   limit: Option<i64>,
182 }
183
184 impl<'a> PersonMentionQuery<'a> {
185   pub fn list(self) -> Result<Vec<PersonMentionView>, Error> {
186     use diesel::dsl::*;
187
188     let person_alias_1 = diesel::alias!(person as person1);
189
190     // The left join below will return None in this case
191     let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
192
193     let mut query = person_mention::table
194       .inner_join(comment::table)
195       .inner_join(person::table.on(comment::creator_id.eq(person::id)))
196       .inner_join(post::table.on(comment::post_id.eq(post::id)))
197       .inner_join(community::table.on(post::community_id.eq(community::id)))
198       .inner_join(person_alias_1)
199       .inner_join(comment_aggregates::table.on(comment::id.eq(comment_aggregates::comment_id)))
200       .left_join(
201         community_person_ban::table.on(
202           community::id
203             .eq(community_person_ban::community_id)
204             .and(community_person_ban::person_id.eq(comment::creator_id))
205             .and(
206               community_person_ban::expires
207                 .is_null()
208                 .or(community_person_ban::expires.gt(now)),
209             ),
210         ),
211       )
212       .left_join(
213         community_follower::table.on(
214           post::community_id
215             .eq(community_follower::community_id)
216             .and(community_follower::person_id.eq(person_id_join)),
217         ),
218       )
219       .left_join(
220         comment_saved::table.on(
221           comment::id
222             .eq(comment_saved::comment_id)
223             .and(comment_saved::person_id.eq(person_id_join)),
224         ),
225       )
226       .left_join(
227         person_block::table.on(
228           comment::creator_id
229             .eq(person_block::target_id)
230             .and(person_block::person_id.eq(person_id_join)),
231         ),
232       )
233       .left_join(
234         comment_like::table.on(
235           comment::id
236             .eq(comment_like::comment_id)
237             .and(comment_like::person_id.eq(person_id_join)),
238         ),
239       )
240       .select((
241         person_mention::all_columns,
242         comment::all_columns,
243         Person::safe_columns_tuple(),
244         post::all_columns,
245         Community::safe_columns_tuple(),
246         person_alias_1.fields(Person::safe_columns_tuple()),
247         comment_aggregates::all_columns,
248         community_person_ban::all_columns.nullable(),
249         community_follower::all_columns.nullable(),
250         comment_saved::all_columns.nullable(),
251         person_block::all_columns.nullable(),
252         comment_like::score.nullable(),
253       ))
254       .into_boxed();
255
256     if let Some(recipient_id) = self.recipient_id {
257       query = query.filter(person_mention::recipient_id.eq(recipient_id));
258     }
259
260     if self.unread_only.unwrap_or(false) {
261       query = query.filter(person_mention::read.eq(false));
262     }
263
264     if !self.show_bot_accounts.unwrap_or(true) {
265       query = query.filter(person::bot_account.eq(false));
266     };
267
268     query = match self.sort.unwrap_or(CommentSortType::Hot) {
269       CommentSortType::Hot => query
270         .then_order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
271         .then_order_by(comment_aggregates::published.desc()),
272       CommentSortType::New => query.then_order_by(comment::published.desc()),
273       CommentSortType::Old => query.then_order_by(comment::published.asc()),
274       CommentSortType::Top => query.order_by(comment_aggregates::score.desc()),
275     };
276
277     let (limit, offset) = limit_and_offset(self.page, self.limit)?;
278
279     let res = query
280       .limit(limit)
281       .offset(offset)
282       .load::<PersonMentionViewTuple>(self.conn)?;
283
284     Ok(PersonMentionView::from_tuple_to_vec(res))
285   }
286 }
287
288 impl ViewToVec for PersonMentionView {
289   type DbTuple = PersonMentionViewTuple;
290   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
291     items
292       .into_iter()
293       .map(|a| Self {
294         person_mention: a.0,
295         comment: a.1,
296         creator: a.2,
297         post: a.3,
298         community: a.4,
299         recipient: a.5,
300         counts: a.6,
301         creator_banned_from_community: a.7.is_some(),
302         subscribed: CommunityFollower::to_subscribed_type(&a.8),
303         saved: a.9.is_some(),
304         creator_blocked: a.10.is_some(),
305         my_vote: a.11,
306       })
307       .collect::<Vec<Self>>()
308   }
309 }