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