]> Untitled Git - lemmy.git/blob - crates/db_views/src/comment_view.rs
Some formatting
[lemmy.git] / crates / db_views / src / comment_view.rs
1 use diesel::{result::Error, *};
2 use lemmy_db_queries::{
3   aggregates::comment_aggregates::CommentAggregates,
4   functions::hot_rank,
5   fuzzy_search,
6   limit_and_offset,
7   ListingType,
8   MaybeOptional,
9   SortType,
10   ToSafe,
11   ViewToVec,
12 };
13 use lemmy_db_schema::{
14   schema::{
15     comment,
16     comment_aggregates,
17     comment_alias_1,
18     comment_like,
19     comment_saved,
20     community,
21     community_follower,
22     community_person_ban,
23     person,
24     person_alias_1,
25     post,
26   },
27   source::{
28     comment::{Comment, CommentAlias1, CommentSaved},
29     community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
30     person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1},
31     post::Post,
32   },
33   CommentId,
34   CommunityId,
35   PersonId,
36   PostId,
37 };
38 use serde::Serialize;
39
40 #[derive(Debug, PartialEq, Serialize, Clone)]
41 pub struct CommentView {
42   pub comment: Comment,
43   pub creator: PersonSafe,
44   pub recipient: Option<PersonSafeAlias1>, // Left joins to comment and person
45   pub post: Post,
46   pub community: CommunitySafe,
47   pub counts: CommentAggregates,
48   pub creator_banned_from_community: bool, // Left Join to CommunityPersonBan
49   pub subscribed: bool,                    // Left join to CommunityFollower
50   pub saved: bool,                         // Left join to CommentSaved
51   pub my_vote: Option<i16>,                // Left join to CommentLike
52 }
53
54 type CommentViewTuple = (
55   Comment,
56   PersonSafe,
57   Option<CommentAlias1>,
58   Option<PersonSafeAlias1>,
59   Post,
60   CommunitySafe,
61   CommentAggregates,
62   Option<CommunityPersonBan>,
63   Option<CommunityFollower>,
64   Option<CommentSaved>,
65   Option<i16>,
66 );
67
68 impl CommentView {
69   pub fn read(
70     conn: &PgConnection,
71     comment_id: CommentId,
72     my_person_id: Option<PersonId>,
73   ) -> Result<Self, Error> {
74     // The left join below will return None in this case
75     let person_id_join = my_person_id.unwrap_or(PersonId(-1));
76
77     let (
78       comment,
79       creator,
80       _parent_comment,
81       recipient,
82       post,
83       community,
84       counts,
85       creator_banned_from_community,
86       subscribed,
87       saved,
88       comment_like,
89     ) = comment::table
90       .find(comment_id)
91       .inner_join(person::table)
92       // recipient here
93       .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
94       .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
95       .inner_join(post::table)
96       .inner_join(community::table.on(post::community_id.eq(community::id)))
97       .inner_join(comment_aggregates::table)
98       .left_join(
99         community_person_ban::table.on(
100           community::id
101             .eq(community_person_ban::community_id)
102             .and(community_person_ban::person_id.eq(comment::creator_id)),
103         ),
104       )
105       .left_join(
106         community_follower::table.on(
107           post::community_id
108             .eq(community_follower::community_id)
109             .and(community_follower::person_id.eq(person_id_join)),
110         ),
111       )
112       .left_join(
113         comment_saved::table.on(
114           comment::id
115             .eq(comment_saved::comment_id)
116             .and(comment_saved::person_id.eq(person_id_join)),
117         ),
118       )
119       .left_join(
120         comment_like::table.on(
121           comment::id
122             .eq(comment_like::comment_id)
123             .and(comment_like::person_id.eq(person_id_join)),
124         ),
125       )
126       .select((
127         comment::all_columns,
128         Person::safe_columns_tuple(),
129         comment_alias_1::all_columns.nullable(),
130         PersonAlias1::safe_columns_tuple().nullable(),
131         post::all_columns,
132         Community::safe_columns_tuple(),
133         comment_aggregates::all_columns,
134         community_person_ban::all_columns.nullable(),
135         community_follower::all_columns.nullable(),
136         comment_saved::all_columns.nullable(),
137         comment_like::score.nullable(),
138       ))
139       .first::<CommentViewTuple>(conn)?;
140
141     // If a person is given, then my_vote, if None, should be 0, not null
142     // Necessary to differentiate between other person's votes
143     let my_vote = if my_person_id.is_some() && comment_like.is_none() {
144       Some(0)
145     } else {
146       comment_like
147     };
148
149     Ok(CommentView {
150       comment,
151       recipient,
152       post,
153       creator,
154       community,
155       counts,
156       creator_banned_from_community: creator_banned_from_community.is_some(),
157       subscribed: subscribed.is_some(),
158       saved: saved.is_some(),
159       my_vote,
160     })
161   }
162
163   /// Gets the recipient person id.
164   /// If there is no parent comment, its the post creator
165   pub fn get_recipient_id(&self) -> PersonId {
166     match &self.recipient {
167       Some(parent_commenter) => parent_commenter.id,
168       None => self.post.creator_id,
169     }
170   }
171 }
172
173 pub struct CommentQueryBuilder<'a> {
174   conn: &'a PgConnection,
175   listing_type: Option<ListingType>,
176   sort: Option<SortType>,
177   community_id: Option<CommunityId>,
178   community_name: Option<String>,
179   post_id: Option<PostId>,
180   creator_id: Option<PersonId>,
181   recipient_id: Option<PersonId>,
182   my_person_id: Option<PersonId>,
183   search_term: Option<String>,
184   saved_only: Option<bool>,
185   unread_only: Option<bool>,
186   show_bot_accounts: Option<bool>,
187   page: Option<i64>,
188   limit: Option<i64>,
189 }
190
191 impl<'a> CommentQueryBuilder<'a> {
192   pub fn create(conn: &'a PgConnection) -> Self {
193     CommentQueryBuilder {
194       conn,
195       listing_type: None,
196       sort: None,
197       community_id: None,
198       community_name: None,
199       post_id: None,
200       creator_id: None,
201       recipient_id: None,
202       my_person_id: None,
203       search_term: None,
204       saved_only: None,
205       unread_only: None,
206       show_bot_accounts: None,
207       page: None,
208       limit: None,
209     }
210   }
211
212   pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
213     self.listing_type = listing_type.get_optional();
214     self
215   }
216
217   pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
218     self.sort = sort.get_optional();
219     self
220   }
221
222   pub fn post_id<T: MaybeOptional<PostId>>(mut self, post_id: T) -> Self {
223     self.post_id = post_id.get_optional();
224     self
225   }
226
227   pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
228     self.creator_id = creator_id.get_optional();
229     self
230   }
231
232   pub fn recipient_id<T: MaybeOptional<PersonId>>(mut self, recipient_id: T) -> Self {
233     self.recipient_id = recipient_id.get_optional();
234     self
235   }
236
237   pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
238     self.community_id = community_id.get_optional();
239     self
240   }
241
242   pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
243     self.my_person_id = my_person_id.get_optional();
244     self
245   }
246
247   pub fn community_name<T: MaybeOptional<String>>(mut self, community_name: T) -> Self {
248     self.community_name = community_name.get_optional();
249     self
250   }
251
252   pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
253     self.search_term = search_term.get_optional();
254     self
255   }
256
257   pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
258     self.saved_only = saved_only.get_optional();
259     self
260   }
261
262   pub fn unread_only<T: MaybeOptional<bool>>(mut self, unread_only: T) -> Self {
263     self.unread_only = unread_only.get_optional();
264     self
265   }
266
267   pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
268     self.show_bot_accounts = show_bot_accounts.get_optional();
269     self
270   }
271
272   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
273     self.page = page.get_optional();
274     self
275   }
276
277   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
278     self.limit = limit.get_optional();
279     self
280   }
281
282   pub fn list(self) -> Result<Vec<CommentView>, Error> {
283     use diesel::dsl::*;
284
285     // The left join below will return None in this case
286     let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
287
288     let mut query = comment::table
289       .inner_join(person::table)
290       // recipient here
291       .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
292       .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
293       .inner_join(post::table)
294       .inner_join(community::table.on(post::community_id.eq(community::id)))
295       .inner_join(comment_aggregates::table)
296       .left_join(
297         community_person_ban::table.on(
298           community::id
299             .eq(community_person_ban::community_id)
300             .and(community_person_ban::person_id.eq(comment::creator_id)),
301         ),
302       )
303       .left_join(
304         community_follower::table.on(
305           post::community_id
306             .eq(community_follower::community_id)
307             .and(community_follower::person_id.eq(person_id_join)),
308         ),
309       )
310       .left_join(
311         comment_saved::table.on(
312           comment::id
313             .eq(comment_saved::comment_id)
314             .and(comment_saved::person_id.eq(person_id_join)),
315         ),
316       )
317       .left_join(
318         comment_like::table.on(
319           comment::id
320             .eq(comment_like::comment_id)
321             .and(comment_like::person_id.eq(person_id_join)),
322         ),
323       )
324       .select((
325         comment::all_columns,
326         Person::safe_columns_tuple(),
327         comment_alias_1::all_columns.nullable(),
328         PersonAlias1::safe_columns_tuple().nullable(),
329         post::all_columns,
330         Community::safe_columns_tuple(),
331         comment_aggregates::all_columns,
332         community_person_ban::all_columns.nullable(),
333         community_follower::all_columns.nullable(),
334         comment_saved::all_columns.nullable(),
335         comment_like::score.nullable(),
336       ))
337       .into_boxed();
338
339     // The replies
340     if let Some(recipient_id) = self.recipient_id {
341       query = query
342         // TODO needs lots of testing
343         .filter(person_alias_1::id.eq(recipient_id)) // Gets the comment replies
344         .or_filter(
345           comment::parent_id
346             .is_null()
347             .and(post::creator_id.eq(recipient_id)),
348         ) // Gets the top level replies
349         .filter(comment::deleted.eq(false))
350         .filter(comment::removed.eq(false));
351     }
352
353     if self.unread_only.unwrap_or_default() {
354       query = query.filter(comment::read.eq(false));
355     }
356
357     if let Some(creator_id) = self.creator_id {
358       query = query.filter(comment::creator_id.eq(creator_id));
359     };
360
361     if let Some(community_id) = self.community_id {
362       query = query.filter(post::community_id.eq(community_id));
363     }
364
365     if let Some(community_name) = self.community_name {
366       query = query
367         .filter(community::name.eq(community_name))
368         .filter(comment::local.eq(true));
369     }
370
371     if let Some(post_id) = self.post_id {
372       query = query.filter(comment::post_id.eq(post_id));
373     };
374
375     if let Some(search_term) = self.search_term {
376       query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
377     };
378
379     if let Some(listing_type) = self.listing_type {
380       query = match listing_type {
381         // ListingType::Subscribed => query.filter(community_follower::subscribed.eq(true)),
382         ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
383         ListingType::Local => query.filter(community::local.eq(true)),
384         _ => query,
385       };
386     }
387
388     if self.saved_only.unwrap_or_default() {
389       query = query.filter(comment_saved::id.is_not_null());
390     }
391
392     if !self.show_bot_accounts.unwrap_or(true) {
393       query = query.filter(person::bot_account.eq(false));
394     };
395
396     query = match self.sort.unwrap_or(SortType::New) {
397       SortType::Hot | SortType::Active => query
398         .order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
399         .then_order_by(comment_aggregates::published.desc()),
400       SortType::New | SortType::MostComments | SortType::NewComments => {
401         query.order_by(comment::published.desc())
402       }
403       SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
404       SortType::TopYear => query
405         .filter(comment::published.gt(now - 1.years()))
406         .order_by(comment_aggregates::score.desc()),
407       SortType::TopMonth => query
408         .filter(comment::published.gt(now - 1.months()))
409         .order_by(comment_aggregates::score.desc()),
410       SortType::TopWeek => query
411         .filter(comment::published.gt(now - 1.weeks()))
412         .order_by(comment_aggregates::score.desc()),
413       SortType::TopDay => query
414         .filter(comment::published.gt(now - 1.days()))
415         .order_by(comment_aggregates::score.desc()),
416     };
417
418     let (limit, offset) = limit_and_offset(self.page, self.limit);
419
420     // Note: deleted and removed comments are done on the front side
421     let res = query
422       .limit(limit)
423       .offset(offset)
424       .load::<CommentViewTuple>(self.conn)?;
425
426     Ok(CommentView::from_tuple_to_vec(res))
427   }
428 }
429
430 impl ViewToVec for CommentView {
431   type DbTuple = CommentViewTuple;
432   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
433     items
434       .iter()
435       .map(|a| Self {
436         comment: a.0.to_owned(),
437         creator: a.1.to_owned(),
438         recipient: a.3.to_owned(),
439         post: a.4.to_owned(),
440         community: a.5.to_owned(),
441         counts: a.6.to_owned(),
442         creator_banned_from_community: a.7.is_some(),
443         subscribed: a.8.is_some(),
444         saved: a.9.is_some(),
445         my_vote: a.10,
446       })
447       .collect::<Vec<Self>>()
448   }
449 }
450
451 #[cfg(test)]
452 mod tests {
453   use crate::comment_view::*;
454   use lemmy_db_queries::{
455     aggregates::comment_aggregates::CommentAggregates,
456     establish_unpooled_connection,
457     Crud,
458     Likeable,
459   };
460   use lemmy_db_schema::source::{comment::*, community::*, person::*, post::*};
461   use serial_test::serial;
462
463   #[test]
464   #[serial]
465   fn test_crud() {
466     let conn = establish_unpooled_connection();
467
468     let new_person = PersonForm {
469       name: "timmy".into(),
470       ..PersonForm::default()
471     };
472
473     let inserted_person = Person::create(&conn, &new_person).unwrap();
474
475     let new_community = CommunityForm {
476       name: "test community 5".to_string(),
477       title: "nada".to_owned(),
478       ..CommunityForm::default()
479     };
480
481     let inserted_community = Community::create(&conn, &new_community).unwrap();
482
483     let new_post = PostForm {
484       name: "A test post 2".into(),
485       creator_id: inserted_person.id,
486       community_id: inserted_community.id,
487       ..PostForm::default()
488     };
489
490     let inserted_post = Post::create(&conn, &new_post).unwrap();
491
492     let comment_form = CommentForm {
493       content: "A test comment 32".into(),
494       creator_id: inserted_person.id,
495       post_id: inserted_post.id,
496       ..CommentForm::default()
497     };
498
499     let inserted_comment = Comment::create(&conn, &comment_form).unwrap();
500
501     let comment_like_form = CommentLikeForm {
502       comment_id: inserted_comment.id,
503       post_id: inserted_post.id,
504       person_id: inserted_person.id,
505       score: 1,
506     };
507
508     let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
509
510     let agg = CommentAggregates::read(&conn, inserted_comment.id).unwrap();
511
512     let expected_comment_view_no_person = CommentView {
513       creator_banned_from_community: false,
514       my_vote: None,
515       subscribed: false,
516       saved: false,
517       comment: Comment {
518         id: inserted_comment.id,
519         content: "A test comment 32".into(),
520         creator_id: inserted_person.id,
521         post_id: inserted_post.id,
522         parent_id: None,
523         removed: false,
524         deleted: false,
525         read: false,
526         published: inserted_comment.published,
527         ap_id: inserted_comment.ap_id,
528         updated: None,
529         local: true,
530       },
531       creator: PersonSafe {
532         id: inserted_person.id,
533         name: "timmy".into(),
534         display_name: None,
535         published: inserted_person.published,
536         avatar: None,
537         actor_id: inserted_person.actor_id.to_owned(),
538         local: true,
539         banned: false,
540         deleted: false,
541         admin: false,
542         bot_account: false,
543         bio: None,
544         banner: None,
545         updated: None,
546         inbox_url: inserted_person.inbox_url.to_owned(),
547         shared_inbox_url: None,
548         matrix_user_id: None,
549       },
550       recipient: None,
551       post: Post {
552         id: inserted_post.id,
553         name: inserted_post.name.to_owned(),
554         creator_id: inserted_person.id,
555         url: None,
556         body: None,
557         published: inserted_post.published,
558         updated: None,
559         community_id: inserted_community.id,
560         removed: false,
561         deleted: false,
562         locked: false,
563         stickied: false,
564         nsfw: false,
565         embed_title: None,
566         embed_description: None,
567         embed_html: None,
568         thumbnail_url: None,
569         ap_id: inserted_post.ap_id.to_owned(),
570         local: true,
571       },
572       community: CommunitySafe {
573         id: inserted_community.id,
574         name: "test community 5".to_string(),
575         icon: None,
576         removed: false,
577         deleted: false,
578         nsfw: false,
579         actor_id: inserted_community.actor_id.to_owned(),
580         local: true,
581         title: "nada".to_owned(),
582         description: None,
583         updated: None,
584         banner: None,
585         published: inserted_community.published,
586       },
587       counts: CommentAggregates {
588         id: agg.id,
589         comment_id: inserted_comment.id,
590         score: 1,
591         upvotes: 1,
592         downvotes: 0,
593         published: agg.published,
594       },
595     };
596
597     let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
598     expected_comment_view_with_person.my_vote = Some(1);
599
600     let read_comment_views_no_person = CommentQueryBuilder::create(&conn)
601       .post_id(inserted_post.id)
602       .list()
603       .unwrap();
604
605     let read_comment_views_with_person = CommentQueryBuilder::create(&conn)
606       .post_id(inserted_post.id)
607       .my_person_id(inserted_person.id)
608       .list()
609       .unwrap();
610
611     let like_removed = CommentLike::remove(&conn, inserted_person.id, inserted_comment.id).unwrap();
612     let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap();
613     Post::delete(&conn, inserted_post.id).unwrap();
614     Community::delete(&conn, inserted_community.id).unwrap();
615     Person::delete(&conn, inserted_person.id).unwrap();
616
617     assert_eq!(
618       expected_comment_view_no_person,
619       read_comment_views_no_person[0]
620     );
621     assert_eq!(
622       expected_comment_view_with_person,
623       read_comment_views_with_person[0]
624     );
625     assert_eq!(1, num_deleted);
626     assert_eq!(1, like_removed);
627   }
628 }