]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/person_mention_view.rs
~80% done
[lemmy.git] / crates / db_views_actor / src / person_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_person_ban,
20     post,
21     person,
22     person_alias_1,
23     person_mention,
24   },
25   source::{
26     comment::{Comment, CommentSaved},
27     community::{Community, CommunityFollower, CommunitySafe, CommunityPersonBan},
28     post::Post,
29     person::{PersonAlias1, PersonSafe, PersonSafeAlias1, Person},
30     person_mention::PersonMention,
31   },
32 };
33 use serde::Serialize;
34
35 #[derive(Debug, PartialEq, Serialize, Clone)]
36 pub struct PersonMentionView {
37   pub person_mention: PersonMention,
38   pub comment: Comment,
39   pub creator: PersonSafe,
40   pub post: Post,
41   pub community: CommunitySafe,
42   pub recipient: PersonSafeAlias1,
43   pub counts: CommentAggregates,
44   pub creator_banned_from_community: bool, // Left Join to CommunityPersonBan
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 PersonMentionViewTuple = (
51   PersonMention,
52   Comment,
53   PersonSafe,
54   Post,
55   CommunitySafe,
56   PersonSafeAlias1,
57   CommentAggregates,
58   Option<CommunityPersonBan>,
59   Option<CommunityFollower>,
60   Option<CommentSaved>,
61   Option<i16>,
62 );
63
64 impl PersonMentionView {
65   pub fn read(
66     conn: &PgConnection,
67     person_mention_id: i32,
68     my_person_id: Option<i32>,
69   ) -> Result<Self, Error> {
70     // The left join below will return None in this case
71     let person_id_join = my_person_id.unwrap_or(-1);
72
73     let (
74       person_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     ) = person_mention::table
86       .find(person_mention_id)
87       .inner_join(comment::table)
88       .inner_join(person::table.on(comment::creator_id.eq(person::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(person_alias_1::table)
92       .inner_join(comment_aggregates::table.on(comment::id.eq(comment_aggregates::comment_id)))
93       .left_join(
94         community_person_ban::table.on(
95           community::id
96             .eq(community_person_ban::community_id)
97             .and(community_person_ban::person_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::person_id.eq(person_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::person_id.eq(person_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::person_id.eq(person_id_join)),
119         ),
120       )
121       .select((
122         person_mention::all_columns,
123         comment::all_columns,
124         Person::safe_columns_tuple(),
125         post::all_columns,
126         Community::safe_columns_tuple(),
127         PersonAlias1::safe_columns_tuple(),
128         comment_aggregates::all_columns,
129         community_person_ban::all_columns.nullable(),
130         community_follower::all_columns.nullable(),
131         comment_saved::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: subscribed.is_some(),
146       saved: saved.is_some(),
147       my_vote,
148     })
149   }
150 }
151
152 pub struct PersonMentionQueryBuilder<'a> {
153   conn: &'a PgConnection,
154   my_person_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> PersonMentionQueryBuilder<'a> {
163   pub fn create(conn: &'a PgConnection) -> Self {
164     PersonMentionQueryBuilder {
165       conn,
166       my_person_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_person_id<T: MaybeOptional<i32>>(mut self, my_person_id: T) -> Self {
191     self.my_person_id = my_person_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<PersonMentionView>, Error> {
206     use diesel::dsl::*;
207
208     // The left join below will return None in this case
209     let person_id_join = self.my_person_id.unwrap_or(-1);
210
211     let mut query = person_mention::table
212       .inner_join(comment::table)
213       .inner_join(person::table.on(comment::creator_id.eq(person::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(person_alias_1::table)
217       .inner_join(comment_aggregates::table.on(comment::id.eq(comment_aggregates::comment_id)))
218       .left_join(
219         community_person_ban::table.on(
220           community::id
221             .eq(community_person_ban::community_id)
222             .and(community_person_ban::person_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::person_id.eq(person_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::person_id.eq(person_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::person_id.eq(person_id_join)),
244         ),
245       )
246       .select((
247         person_mention::all_columns,
248         comment::all_columns,
249         Person::safe_columns_tuple(),
250         post::all_columns,
251         Community::safe_columns_tuple(),
252         PersonAlias1::safe_columns_tuple(),
253         comment_aggregates::all_columns,
254         community_person_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(person_mention::recipient_id.eq(recipient_id));
263     }
264
265     if self.unread_only {
266       query = query.filter(person_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 | SortType::MostComments | SortType::NewComments => {
274         query.order_by(comment::published.desc())
275       }
276       SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
277       SortType::TopYear => query
278         .filter(comment::published.gt(now - 1.years()))
279         .order_by(comment_aggregates::score.desc()),
280       SortType::TopMonth => query
281         .filter(comment::published.gt(now - 1.months()))
282         .order_by(comment_aggregates::score.desc()),
283       SortType::TopWeek => query
284         .filter(comment::published.gt(now - 1.weeks()))
285         .order_by(comment_aggregates::score.desc()),
286       SortType::TopDay => query
287         .filter(comment::published.gt(now - 1.days()))
288         .order_by(comment_aggregates::score.desc()),
289     };
290
291     let (limit, offset) = limit_and_offset(self.page, self.limit);
292
293     let res = query
294       .limit(limit)
295       .offset(offset)
296       .load::<PersonMentionViewTuple>(self.conn)?;
297
298     Ok(PersonMentionView::from_tuple_to_vec(res))
299   }
300 }
301
302 impl ViewToVec for PersonMentionView {
303   type DbTuple = PersonMentionViewTuple;
304   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
305     items
306       .iter()
307       .map(|a| Self {
308         person_mention: a.0.to_owned(),
309         comment: a.1.to_owned(),
310         creator: a.2.to_owned(),
311         post: a.3.to_owned(),
312         community: a.4.to_owned(),
313         recipient: a.5.to_owned(),
314         counts: a.6.to_owned(),
315         creator_banned_from_community: a.7.is_some(),
316         subscribed: a.8.is_some(),
317         saved: a.9.is_some(),
318         my_vote: a.10,
319       })
320       .collect::<Vec<Self>>()
321   }
322 }