]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/user_mention_view.rs
Merge pull request #1328 from LemmyNet/move_views_to_diesel
[lemmy.git] / crates / db_views_actor / src / user_mention_view.rs
1 use diesel::{result::Error, *};
2 use lemmy_db_queries::{
3   aggregates::comment_aggregates::CommentAggregates,
4   functions::hot_rank,
5   limit_and_offset,
6   MaybeOptional,
7   SortType,
8   ToSafe,
9   ViewToVec,
10 };
11 use lemmy_db_schema::{
12   schema::{
13     comment,
14     comment_aggregates,
15     comment_like,
16     comment_saved,
17     community,
18     community_follower,
19     community_user_ban,
20     post,
21     user_,
22     user_alias_1,
23     user_mention,
24   },
25   source::{
26     comment::{Comment, CommentSaved},
27     community::{Community, CommunityFollower, CommunitySafe, CommunityUserBan},
28     post::Post,
29     user::{UserAlias1, UserSafe, UserSafeAlias1, User_},
30     user_mention::UserMention,
31   },
32 };
33 use serde::Serialize;
34
35 #[derive(Debug, PartialEq, Serialize, Clone)]
36 pub struct UserMentionView {
37   pub user_mention: UserMention,
38   pub comment: Comment,
39   pub creator: UserSafe,
40   pub post: Post,
41   pub community: CommunitySafe,
42   pub recipient: UserSafeAlias1,
43   pub counts: CommentAggregates,
44   pub creator_banned_from_community: bool, // Left Join to CommunityUserBan
45   pub subscribed: bool,                    // Left join to CommunityFollower
46   pub saved: bool,                         // Left join to CommentSaved
47   pub my_vote: Option<i16>,                // Left join to CommentLike
48 }
49
50 type UserMentionViewTuple = (
51   UserMention,
52   Comment,
53   UserSafe,
54   Post,
55   CommunitySafe,
56   UserSafeAlias1,
57   CommentAggregates,
58   Option<CommunityUserBan>,
59   Option<CommunityFollower>,
60   Option<CommentSaved>,
61   Option<i16>,
62 );
63
64 impl UserMentionView {
65   pub fn read(
66     conn: &PgConnection,
67     user_mention_id: i32,
68     my_user_id: Option<i32>,
69   ) -> Result<Self, Error> {
70     // The left join below will return None in this case
71     let user_id_join = my_user_id.unwrap_or(-1);
72
73     let (
74       user_mention,
75       comment,
76       creator,
77       post,
78       community,
79       recipient,
80       counts,
81       creator_banned_from_community,
82       subscribed,
83       saved,
84       my_vote,
85     ) = user_mention::table
86       .find(user_mention_id)
87       .inner_join(comment::table)
88       .inner_join(user_::table.on(comment::creator_id.eq(user_::id)))
89       .inner_join(post::table.on(comment::post_id.eq(post::id)))
90       .inner_join(community::table.on(post::community_id.eq(community::id)))
91       .inner_join(user_alias_1::table)
92       .inner_join(comment_aggregates::table.on(comment::id.eq(comment_aggregates::comment_id)))
93       .left_join(
94         community_user_ban::table.on(
95           community::id
96             .eq(community_user_ban::community_id)
97             .and(community_user_ban::user_id.eq(comment::creator_id)),
98         ),
99       )
100       .left_join(
101         community_follower::table.on(
102           post::community_id
103             .eq(community_follower::community_id)
104             .and(community_follower::user_id.eq(user_id_join)),
105         ),
106       )
107       .left_join(
108         comment_saved::table.on(
109           comment::id
110             .eq(comment_saved::comment_id)
111             .and(comment_saved::user_id.eq(user_id_join)),
112         ),
113       )
114       .left_join(
115         comment_like::table.on(
116           comment::id
117             .eq(comment_like::comment_id)
118             .and(comment_like::user_id.eq(user_id_join)),
119         ),
120       )
121       .select((
122         user_mention::all_columns,
123         comment::all_columns,
124         User_::safe_columns_tuple(),
125         post::all_columns,
126         Community::safe_columns_tuple(),
127         UserAlias1::safe_columns_tuple(),
128         comment_aggregates::all_columns,
129         community_user_ban::all_columns.nullable(),
130         community_follower::all_columns.nullable(),
131         comment_saved::all_columns.nullable(),
132         comment_like::score.nullable(),
133       ))
134       .first::<UserMentionViewTuple>(conn)?;
135
136     Ok(UserMentionView {
137       user_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: subscribed.is_some(),
146       saved: saved.is_some(),
147       my_vote,
148     })
149   }
150 }
151
152 pub struct UserMentionQueryBuilder<'a> {
153   conn: &'a PgConnection,
154   my_user_id: Option<i32>,
155   recipient_id: Option<i32>,
156   sort: &'a SortType,
157   unread_only: bool,
158   page: Option<i64>,
159   limit: Option<i64>,
160 }
161
162 impl<'a> UserMentionQueryBuilder<'a> {
163   pub fn create(conn: &'a PgConnection) -> Self {
164     UserMentionQueryBuilder {
165       conn,
166       my_user_id: None,
167       recipient_id: None,
168       sort: &SortType::New,
169       unread_only: false,
170       page: None,
171       limit: None,
172     }
173   }
174
175   pub fn sort(mut self, sort: &'a SortType) -> Self {
176     self.sort = sort;
177     self
178   }
179
180   pub fn unread_only(mut self, unread_only: bool) -> Self {
181     self.unread_only = unread_only;
182     self
183   }
184
185   pub fn recipient_id<T: MaybeOptional<i32>>(mut self, recipient_id: T) -> Self {
186     self.recipient_id = recipient_id.get_optional();
187     self
188   }
189
190   pub fn my_user_id<T: MaybeOptional<i32>>(mut self, my_user_id: T) -> Self {
191     self.my_user_id = my_user_id.get_optional();
192     self
193   }
194
195   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
196     self.page = page.get_optional();
197     self
198   }
199
200   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
201     self.limit = limit.get_optional();
202     self
203   }
204
205   pub fn list(self) -> Result<Vec<UserMentionView>, Error> {
206     use diesel::dsl::*;
207
208     // The left join below will return None in this case
209     let user_id_join = self.my_user_id.unwrap_or(-1);
210
211     let mut query = user_mention::table
212       .inner_join(comment::table)
213       .inner_join(user_::table.on(comment::creator_id.eq(user_::id)))
214       .inner_join(post::table.on(comment::post_id.eq(post::id)))
215       .inner_join(community::table.on(post::community_id.eq(community::id)))
216       .inner_join(user_alias_1::table)
217       .inner_join(comment_aggregates::table.on(comment::id.eq(comment_aggregates::comment_id)))
218       .left_join(
219         community_user_ban::table.on(
220           community::id
221             .eq(community_user_ban::community_id)
222             .and(community_user_ban::user_id.eq(comment::creator_id)),
223         ),
224       )
225       .left_join(
226         community_follower::table.on(
227           post::community_id
228             .eq(community_follower::community_id)
229             .and(community_follower::user_id.eq(user_id_join)),
230         ),
231       )
232       .left_join(
233         comment_saved::table.on(
234           comment::id
235             .eq(comment_saved::comment_id)
236             .and(comment_saved::user_id.eq(user_id_join)),
237         ),
238       )
239       .left_join(
240         comment_like::table.on(
241           comment::id
242             .eq(comment_like::comment_id)
243             .and(comment_like::user_id.eq(user_id_join)),
244         ),
245       )
246       .select((
247         user_mention::all_columns,
248         comment::all_columns,
249         User_::safe_columns_tuple(),
250         post::all_columns,
251         Community::safe_columns_tuple(),
252         UserAlias1::safe_columns_tuple(),
253         comment_aggregates::all_columns,
254         community_user_ban::all_columns.nullable(),
255         community_follower::all_columns.nullable(),
256         comment_saved::all_columns.nullable(),
257         comment_like::score.nullable(),
258       ))
259       .into_boxed();
260
261     if let Some(recipient_id) = self.recipient_id {
262       query = query.filter(user_mention::recipient_id.eq(recipient_id));
263     }
264
265     if self.unread_only {
266       query = query.filter(user_mention::read.eq(false));
267     }
268
269     query = match self.sort {
270       SortType::Hot | SortType::Active => query
271         .order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
272         .then_order_by(comment_aggregates::published.desc()),
273       SortType::New => query.order_by(comment::published.desc()),
274       SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
275       SortType::TopYear => query
276         .filter(comment::published.gt(now - 1.years()))
277         .order_by(comment_aggregates::score.desc()),
278       SortType::TopMonth => query
279         .filter(comment::published.gt(now - 1.months()))
280         .order_by(comment_aggregates::score.desc()),
281       SortType::TopWeek => query
282         .filter(comment::published.gt(now - 1.weeks()))
283         .order_by(comment_aggregates::score.desc()),
284       SortType::TopDay => query
285         .filter(comment::published.gt(now - 1.days()))
286         .order_by(comment_aggregates::score.desc()),
287     };
288
289     let (limit, offset) = limit_and_offset(self.page, self.limit);
290
291     let res = query
292       .limit(limit)
293       .offset(offset)
294       .load::<UserMentionViewTuple>(self.conn)?;
295
296     Ok(UserMentionView::from_tuple_to_vec(res))
297   }
298 }
299
300 impl ViewToVec for UserMentionView {
301   type DbTuple = UserMentionViewTuple;
302   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
303     items
304       .iter()
305       .map(|a| Self {
306         user_mention: a.0.to_owned(),
307         comment: a.1.to_owned(),
308         creator: a.2.to_owned(),
309         post: a.3.to_owned(),
310         community: a.4.to_owned(),
311         recipient: a.5.to_owned(),
312         counts: a.6.to_owned(),
313         creator_banned_from_community: a.7.is_some(),
314         subscribed: a.8.is_some(),
315         saved: a.9.is_some(),
316         my_vote: a.10,
317       })
318       .collect::<Vec<Self>>()
319   }
320 }