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