]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/comment_reply_view.rs
Check to make sure comment isnt deleted / removed for unread count. (#2472)
[lemmy.git] / crates / db_views_actor / src / comment_reply_view.rs
1 use crate::structs::CommentReplyView;
2 use diesel::{dsl::*, result::Error, *};
3 use lemmy_db_schema::{
4   aggregates::structs::CommentAggregates,
5   newtypes::{CommentReplyId, PersonId},
6   schema::{
7     comment,
8     comment_aggregates,
9     comment_like,
10     comment_reply,
11     comment_saved,
12     community,
13     community_follower,
14     community_person_ban,
15     person,
16     person_block,
17     post,
18   },
19   source::{
20     comment::{Comment, CommentSaved},
21     comment_reply::CommentReply,
22     community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
23     person::{Person, PersonSafe},
24     person_block::PersonBlock,
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 CommentReplyViewTuple = (
34   CommentReply,
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 CommentReplyView {
49   pub fn read(
50     conn: &mut PgConnection,
51     comment_reply_id: CommentReplyId,
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       comment_reply,
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     ) = comment_reply::table
73       .find(comment_reply_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         comment_reply::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::<CommentReplyViewTuple>(conn)?;
135
136     Ok(CommentReplyView {
137       comment_reply,
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 replies
153   pub fn get_unread_replies(conn: &mut PgConnection, my_person_id: PersonId) -> Result<i64, Error> {
154     use diesel::dsl::*;
155
156     comment_reply::table
157       .inner_join(comment::table)
158       .filter(comment_reply::recipient_id.eq(my_person_id))
159       .filter(comment_reply::read.eq(false))
160       .filter(comment::deleted.eq(false))
161       .filter(comment::removed.eq(false))
162       .select(count(comment_reply::id))
163       .first::<i64>(conn)
164   }
165 }
166
167 #[derive(TypedBuilder)]
168 #[builder(field_defaults(default))]
169 pub struct CommentReplyQuery<'a> {
170   #[builder(!default)]
171   conn: &'a mut PgConnection,
172   my_person_id: Option<PersonId>,
173   recipient_id: Option<PersonId>,
174   sort: Option<CommentSortType>,
175   unread_only: Option<bool>,
176   show_bot_accounts: Option<bool>,
177   page: Option<i64>,
178   limit: Option<i64>,
179 }
180
181 impl<'a> CommentReplyQuery<'a> {
182   pub fn list(self) -> Result<Vec<CommentReplyView>, Error> {
183     use diesel::dsl::*;
184
185     let person_alias_1 = diesel::alias!(person as person1);
186
187     // The left join below will return None in this case
188     let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
189
190     let mut query = comment_reply::table
191       .inner_join(comment::table)
192       .inner_join(person::table.on(comment::creator_id.eq(person::id)))
193       .inner_join(post::table.on(comment::post_id.eq(post::id)))
194       .inner_join(community::table.on(post::community_id.eq(community::id)))
195       .inner_join(person_alias_1)
196       .inner_join(comment_aggregates::table.on(comment::id.eq(comment_aggregates::comment_id)))
197       .left_join(
198         community_person_ban::table.on(
199           community::id
200             .eq(community_person_ban::community_id)
201             .and(community_person_ban::person_id.eq(comment::creator_id))
202             .and(
203               community_person_ban::expires
204                 .is_null()
205                 .or(community_person_ban::expires.gt(now)),
206             ),
207         ),
208       )
209       .left_join(
210         community_follower::table.on(
211           post::community_id
212             .eq(community_follower::community_id)
213             .and(community_follower::person_id.eq(person_id_join)),
214         ),
215       )
216       .left_join(
217         comment_saved::table.on(
218           comment::id
219             .eq(comment_saved::comment_id)
220             .and(comment_saved::person_id.eq(person_id_join)),
221         ),
222       )
223       .left_join(
224         person_block::table.on(
225           comment::creator_id
226             .eq(person_block::target_id)
227             .and(person_block::person_id.eq(person_id_join)),
228         ),
229       )
230       .left_join(
231         comment_like::table.on(
232           comment::id
233             .eq(comment_like::comment_id)
234             .and(comment_like::person_id.eq(person_id_join)),
235         ),
236       )
237       .select((
238         comment_reply::all_columns,
239         comment::all_columns,
240         Person::safe_columns_tuple(),
241         post::all_columns,
242         Community::safe_columns_tuple(),
243         person_alias_1.fields(Person::safe_columns_tuple()),
244         comment_aggregates::all_columns,
245         community_person_ban::all_columns.nullable(),
246         community_follower::all_columns.nullable(),
247         comment_saved::all_columns.nullable(),
248         person_block::all_columns.nullable(),
249         comment_like::score.nullable(),
250       ))
251       .into_boxed();
252
253     if let Some(recipient_id) = self.recipient_id {
254       query = query.filter(comment_reply::recipient_id.eq(recipient_id));
255     }
256
257     if self.unread_only.unwrap_or(false) {
258       query = query.filter(comment_reply::read.eq(false));
259     }
260
261     if !self.show_bot_accounts.unwrap_or(true) {
262       query = query.filter(person::bot_account.eq(false));
263     };
264
265     query = match self.sort.unwrap_or(CommentSortType::Hot) {
266       CommentSortType::Hot => query
267         .then_order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
268         .then_order_by(comment_aggregates::published.desc()),
269       CommentSortType::New => query.then_order_by(comment::published.desc()),
270       CommentSortType::Old => query.then_order_by(comment::published.asc()),
271       CommentSortType::Top => query.order_by(comment_aggregates::score.desc()),
272     };
273
274     let (limit, offset) = limit_and_offset(self.page, self.limit)?;
275
276     let res = query
277       .limit(limit)
278       .offset(offset)
279       .load::<CommentReplyViewTuple>(self.conn)?;
280
281     Ok(CommentReplyView::from_tuple_to_vec(res))
282   }
283 }
284
285 impl ViewToVec for CommentReplyView {
286   type DbTuple = CommentReplyViewTuple;
287   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
288     items
289       .into_iter()
290       .map(|a| Self {
291         comment_reply: a.0,
292         comment: a.1,
293         creator: a.2,
294         post: a.3,
295         community: a.4,
296         recipient: a.5,
297         counts: a.6,
298         creator_banned_from_community: a.7.is_some(),
299         subscribed: CommunityFollower::to_subscribed_type(&a.8),
300         saved: a.9.is_some(),
301         creator_blocked: a.10.is_some(),
302         my_vote: a.11,
303       })
304       .collect::<Vec<Self>>()
305   }
306 }