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