]> Untitled Git - lemmy.git/blob - crates/db_views/src/comment_view.rs
a7c96b17c5b1349f2ebd48669afe74950db455a7
[lemmy.git] / crates / db_views / src / comment_view.rs
1 use crate::structs::CommentView;
2 use diesel::{dsl::*, result::Error, *};
3 use diesel_ltree::{nlevel, subpath, Ltree, LtreeExtensions};
4 use lemmy_db_schema::{
5   aggregates::structs::CommentAggregates,
6   newtypes::{CommentId, CommunityId, DbUrl, PersonId, PostId},
7   schema::{
8     comment,
9     comment_aggregates,
10     comment_like,
11     comment_saved,
12     community,
13     community_block,
14     community_follower,
15     community_person_ban,
16     person,
17     person_block,
18     post,
19   },
20   source::{
21     comment::{Comment, CommentSaved},
22     community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
23     local_user::LocalUser,
24     person::{Person, PersonSafe},
25     person_block::PersonBlock,
26     post::Post,
27   },
28   traits::{ToSafe, ViewToVec},
29   utils::{functions::hot_rank, fuzzy_search, limit_and_offset_unlimited},
30   CommentSortType,
31   ListingType,
32 };
33 use typed_builder::TypedBuilder;
34
35 type CommentViewTuple = (
36   Comment,
37   PersonSafe,
38   Post,
39   CommunitySafe,
40   CommentAggregates,
41   Option<CommunityPersonBan>,
42   Option<CommunityFollower>,
43   Option<CommentSaved>,
44   Option<PersonBlock>,
45   Option<i16>,
46 );
47
48 impl CommentView {
49   pub fn read(
50     conn: &PgConnection,
51     comment_id: CommentId,
52     my_person_id: Option<PersonId>,
53   ) -> Result<Self, Error> {
54     // The left join below will return None in this case
55     let person_id_join = my_person_id.unwrap_or(PersonId(-1));
56
57     let (
58       comment,
59       creator,
60       post,
61       community,
62       counts,
63       creator_banned_from_community,
64       follower,
65       saved,
66       creator_blocked,
67       comment_like,
68     ) = comment::table
69       .find(comment_id)
70       .inner_join(person::table)
71       .inner_join(post::table)
72       .inner_join(community::table.on(post::community_id.eq(community::id)))
73       .inner_join(comment_aggregates::table)
74       .left_join(
75         community_person_ban::table.on(
76           community::id
77             .eq(community_person_ban::community_id)
78             .and(community_person_ban::person_id.eq(comment::creator_id))
79             .and(
80               community_person_ban::expires
81                 .is_null()
82                 .or(community_person_ban::expires.gt(now)),
83             ),
84         ),
85       )
86       .left_join(
87         community_follower::table.on(
88           post::community_id
89             .eq(community_follower::community_id)
90             .and(community_follower::person_id.eq(person_id_join)),
91         ),
92       )
93       .left_join(
94         comment_saved::table.on(
95           comment::id
96             .eq(comment_saved::comment_id)
97             .and(comment_saved::person_id.eq(person_id_join)),
98         ),
99       )
100       .left_join(
101         person_block::table.on(
102           comment::creator_id
103             .eq(person_block::target_id)
104             .and(person_block::person_id.eq(person_id_join)),
105         ),
106       )
107       .left_join(
108         comment_like::table.on(
109           comment::id
110             .eq(comment_like::comment_id)
111             .and(comment_like::person_id.eq(person_id_join)),
112         ),
113       )
114       .select((
115         comment::all_columns,
116         Person::safe_columns_tuple(),
117         post::all_columns,
118         Community::safe_columns_tuple(),
119         comment_aggregates::all_columns,
120         community_person_ban::all_columns.nullable(),
121         community_follower::all_columns.nullable(),
122         comment_saved::all_columns.nullable(),
123         person_block::all_columns.nullable(),
124         comment_like::score.nullable(),
125       ))
126       .first::<CommentViewTuple>(conn)?;
127
128     // If a person is given, then my_vote, if None, should be 0, not null
129     // Necessary to differentiate between other person's votes
130     let my_vote = if my_person_id.is_some() && comment_like.is_none() {
131       Some(0)
132     } else {
133       comment_like
134     };
135
136     Ok(CommentView {
137       comment,
138       post,
139       creator,
140       community,
141       counts,
142       creator_banned_from_community: creator_banned_from_community.is_some(),
143       subscribed: CommunityFollower::to_subscribed_type(&follower),
144       saved: saved.is_some(),
145       creator_blocked: creator_blocked.is_some(),
146       my_vote,
147     })
148   }
149 }
150
151 #[derive(TypedBuilder)]
152 #[builder(field_defaults(default))]
153 pub struct CommentQuery<'a> {
154   #[builder(!default)]
155   conn: &'a PgConnection,
156   listing_type: Option<ListingType>,
157   sort: Option<CommentSortType>,
158   community_id: Option<CommunityId>,
159   community_actor_id: Option<DbUrl>,
160   post_id: Option<PostId>,
161   parent_path: Option<Ltree>,
162   creator_id: Option<PersonId>,
163   local_user: Option<&'a LocalUser>,
164   search_term: Option<String>,
165   saved_only: Option<bool>,
166   page: Option<i64>,
167   limit: Option<i64>,
168   max_depth: Option<i32>,
169 }
170
171 impl<'a> CommentQuery<'a> {
172   pub fn list(self) -> Result<Vec<CommentView>, Error> {
173     use diesel::dsl::*;
174
175     // The left join below will return None in this case
176     let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1));
177
178     let mut query = comment::table
179       .inner_join(person::table)
180       .inner_join(post::table)
181       .inner_join(community::table.on(post::community_id.eq(community::id)))
182       .inner_join(comment_aggregates::table)
183       .left_join(
184         community_person_ban::table.on(
185           community::id
186             .eq(community_person_ban::community_id)
187             .and(community_person_ban::person_id.eq(comment::creator_id))
188             .and(
189               community_person_ban::expires
190                 .is_null()
191                 .or(community_person_ban::expires.gt(now)),
192             ),
193         ),
194       )
195       .left_join(
196         community_follower::table.on(
197           post::community_id
198             .eq(community_follower::community_id)
199             .and(community_follower::person_id.eq(person_id_join)),
200         ),
201       )
202       .left_join(
203         comment_saved::table.on(
204           comment::id
205             .eq(comment_saved::comment_id)
206             .and(comment_saved::person_id.eq(person_id_join)),
207         ),
208       )
209       .left_join(
210         person_block::table.on(
211           comment::creator_id
212             .eq(person_block::target_id)
213             .and(person_block::person_id.eq(person_id_join)),
214         ),
215       )
216       .left_join(
217         community_block::table.on(
218           community::id
219             .eq(community_block::community_id)
220             .and(community_block::person_id.eq(person_id_join)),
221         ),
222       )
223       .left_join(
224         comment_like::table.on(
225           comment::id
226             .eq(comment_like::comment_id)
227             .and(comment_like::person_id.eq(person_id_join)),
228         ),
229       )
230       .select((
231         comment::all_columns,
232         Person::safe_columns_tuple(),
233         post::all_columns,
234         Community::safe_columns_tuple(),
235         comment_aggregates::all_columns,
236         community_person_ban::all_columns.nullable(),
237         community_follower::all_columns.nullable(),
238         comment_saved::all_columns.nullable(),
239         person_block::all_columns.nullable(),
240         comment_like::score.nullable(),
241       ))
242       .into_boxed();
243
244     if let Some(creator_id) = self.creator_id {
245       query = query.filter(comment::creator_id.eq(creator_id));
246     };
247
248     if let Some(post_id) = self.post_id {
249       query = query.filter(comment::post_id.eq(post_id));
250     };
251
252     if let Some(parent_path) = self.parent_path.as_ref() {
253       query = query.filter(comment::path.contained_by(parent_path));
254     };
255
256     if let Some(search_term) = self.search_term {
257       query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
258     };
259
260     if let Some(listing_type) = self.listing_type {
261       match listing_type {
262         ListingType::Subscribed => {
263           query = query.filter(community_follower::person_id.is_not_null())
264         } // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
265         ListingType::Local => {
266           query = query.filter(community::local.eq(true)).filter(
267             community::hidden
268               .eq(false)
269               .or(community_follower::person_id.eq(person_id_join)),
270           )
271         }
272         ListingType::All => {
273           query = query.filter(
274             community::hidden
275               .eq(false)
276               .or(community_follower::person_id.eq(person_id_join)),
277           )
278         }
279       }
280     };
281
282     if let Some(community_id) = self.community_id {
283       query = query.filter(post::community_id.eq(community_id));
284     }
285
286     if let Some(community_actor_id) = self.community_actor_id {
287       query = query.filter(community::actor_id.eq(community_actor_id))
288     }
289
290     if self.saved_only.unwrap_or(false) {
291       query = query.filter(comment_saved::id.is_not_null());
292     }
293
294     if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
295       query = query.filter(person::bot_account.eq(false));
296     };
297
298     // Don't show blocked communities or persons
299     if self.local_user.is_some() {
300       query = query.filter(community_block::person_id.is_null());
301       query = query.filter(person_block::person_id.is_null());
302     }
303
304     // A Max depth given means its a tree fetch
305     let (limit, offset) = if let Some(max_depth) = self.max_depth {
306       let depth_limit = if let Some(parent_path) = self.parent_path.as_ref() {
307         parent_path.0.split('.').count() as i32 + max_depth
308         // Add one because of root "0"
309       } else {
310         max_depth + 1
311       };
312
313       query = query.filter(nlevel(comment::path).le(depth_limit));
314
315       // Always order by the parent path first
316       query = query.order_by(subpath(comment::path, 0, -1));
317
318       // TODO limit question. Limiting does not work for comment threads ATM, only max_depth
319       // For now, don't do any limiting for tree fetches
320       // https://stackoverflow.com/questions/72983614/postgres-ltree-how-to-limit-the-max-number-of-children-at-any-given-level
321
322       // Don't use the regular error-checking one, many more comments must ofter be fetched.
323       // This does not work for comment trees, and the limit should be manually set to a high number
324       //
325       // If a max depth is given, then you know its a tree fetch, and limits should be ignored
326       (i64::MAX, 0)
327     } else {
328       limit_and_offset_unlimited(self.page, self.limit)
329     };
330
331     query = match self.sort.unwrap_or(CommentSortType::Hot) {
332       CommentSortType::Hot => query
333         .then_order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
334         .then_order_by(comment_aggregates::published.desc()),
335       CommentSortType::New => query.then_order_by(comment::published.desc()),
336       CommentSortType::Old => query.then_order_by(comment::published.asc()),
337       CommentSortType::Top => query.order_by(comment_aggregates::score.desc()),
338     };
339
340     // Note: deleted and removed comments are done on the front side
341     let res = query
342       .limit(limit)
343       .offset(offset)
344       .load::<CommentViewTuple>(self.conn)?;
345
346     Ok(CommentView::from_tuple_to_vec(res))
347   }
348 }
349
350 impl ViewToVec for CommentView {
351   type DbTuple = CommentViewTuple;
352   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
353     items
354       .into_iter()
355       .map(|a| Self {
356         comment: a.0,
357         creator: a.1,
358         post: a.2,
359         community: a.3,
360         counts: a.4,
361         creator_banned_from_community: a.5.is_some(),
362         subscribed: CommunityFollower::to_subscribed_type(&a.6),
363         saved: a.7.is_some(),
364         creator_blocked: a.8.is_some(),
365         my_vote: a.9,
366       })
367       .collect::<Vec<Self>>()
368   }
369 }
370
371 #[cfg(test)]
372 mod tests {
373   use crate::comment_view::*;
374   use lemmy_db_schema::{
375     aggregates::structs::CommentAggregates,
376     source::{
377       comment::*,
378       community::*,
379       local_user::LocalUserForm,
380       person::*,
381       person_block::PersonBlockForm,
382       post::*,
383     },
384     traits::{Blockable, Crud, Likeable},
385     utils::establish_unpooled_connection,
386     SubscribedType,
387   };
388   use serial_test::serial;
389
390   #[test]
391   #[serial]
392   fn test_crud() {
393     let conn = establish_unpooled_connection();
394
395     let new_person = PersonForm {
396       name: "timmy".into(),
397       public_key: Some("pubkey".to_string()),
398       ..PersonForm::default()
399     };
400     let inserted_person = Person::create(&conn, &new_person).unwrap();
401     let local_user_form = LocalUserForm {
402       person_id: Some(inserted_person.id),
403       password_encrypted: Some("".to_string()),
404       ..Default::default()
405     };
406     let inserted_local_user = LocalUser::create(&conn, &local_user_form).unwrap();
407
408     let new_person_2 = PersonForm {
409       name: "sara".into(),
410       public_key: Some("pubkey".to_string()),
411       ..PersonForm::default()
412     };
413     let inserted_person_2 = Person::create(&conn, &new_person_2).unwrap();
414
415     let new_community = CommunityForm {
416       name: "test community 5".to_string(),
417       title: "nada".to_owned(),
418       public_key: Some("pubkey".to_string()),
419       ..CommunityForm::default()
420     };
421
422     let inserted_community = Community::create(&conn, &new_community).unwrap();
423
424     let new_post = PostForm {
425       name: "A test post 2".into(),
426       creator_id: inserted_person.id,
427       community_id: inserted_community.id,
428       ..PostForm::default()
429     };
430
431     let inserted_post = Post::create(&conn, &new_post).unwrap();
432
433     // Create a comment tree with this hierarchy
434     //       0
435     //     \     \
436     //    1      2
437     //    \
438     //  3  4
439     //     \
440     //     5
441     let comment_form_0 = CommentForm {
442       content: "Comment 0".into(),
443       creator_id: inserted_person.id,
444       post_id: inserted_post.id,
445       ..CommentForm::default()
446     };
447
448     let inserted_comment_0 = Comment::create(&conn, &comment_form_0, None).unwrap();
449
450     let comment_form_1 = CommentForm {
451       content: "Comment 1, A test blocked comment".into(),
452       creator_id: inserted_person_2.id,
453       post_id: inserted_post.id,
454       ..CommentForm::default()
455     };
456
457     let inserted_comment_1 =
458       Comment::create(&conn, &comment_form_1, Some(&inserted_comment_0.path)).unwrap();
459
460     let comment_form_2 = CommentForm {
461       content: "Comment 2".into(),
462       creator_id: inserted_person.id,
463       post_id: inserted_post.id,
464       ..CommentForm::default()
465     };
466
467     let inserted_comment_2 =
468       Comment::create(&conn, &comment_form_2, Some(&inserted_comment_0.path)).unwrap();
469
470     let comment_form_3 = CommentForm {
471       content: "Comment 3".into(),
472       creator_id: inserted_person.id,
473       post_id: inserted_post.id,
474       ..CommentForm::default()
475     };
476
477     let _inserted_comment_3 =
478       Comment::create(&conn, &comment_form_3, Some(&inserted_comment_1.path)).unwrap();
479
480     let comment_form_4 = CommentForm {
481       content: "Comment 4".into(),
482       creator_id: inserted_person.id,
483       post_id: inserted_post.id,
484       ..CommentForm::default()
485     };
486
487     let inserted_comment_4 =
488       Comment::create(&conn, &comment_form_4, Some(&inserted_comment_1.path)).unwrap();
489
490     let comment_form_5 = CommentForm {
491       content: "Comment 5".into(),
492       creator_id: inserted_person.id,
493       post_id: inserted_post.id,
494       ..CommentForm::default()
495     };
496
497     let _inserted_comment_5 =
498       Comment::create(&conn, &comment_form_5, Some(&inserted_comment_4.path)).unwrap();
499
500     let timmy_blocks_sara_form = PersonBlockForm {
501       person_id: inserted_person.id,
502       target_id: inserted_person_2.id,
503     };
504
505     let inserted_block = PersonBlock::block(&conn, &timmy_blocks_sara_form).unwrap();
506
507     let expected_block = PersonBlock {
508       id: inserted_block.id,
509       person_id: inserted_person.id,
510       target_id: inserted_person_2.id,
511       published: inserted_block.published,
512     };
513
514     assert_eq!(expected_block, inserted_block);
515
516     let comment_like_form = CommentLikeForm {
517       comment_id: inserted_comment_0.id,
518       post_id: inserted_post.id,
519       person_id: inserted_person.id,
520       score: 1,
521     };
522
523     let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
524
525     let agg = CommentAggregates::read(&conn, inserted_comment_0.id).unwrap();
526
527     let top_path = inserted_comment_0.to_owned().path;
528     let expected_comment_view_no_person = CommentView {
529       creator_banned_from_community: false,
530       my_vote: None,
531       subscribed: SubscribedType::NotSubscribed,
532       saved: false,
533       creator_blocked: false,
534       comment: Comment {
535         id: inserted_comment_0.id,
536         content: "Comment 0".into(),
537         creator_id: inserted_person.id,
538         post_id: inserted_post.id,
539         removed: false,
540         deleted: false,
541         published: inserted_comment_0.published,
542         ap_id: inserted_comment_0.ap_id,
543         updated: None,
544         local: true,
545         distinguished: false,
546         path: top_path,
547       },
548       creator: PersonSafe {
549         id: inserted_person.id,
550         name: "timmy".into(),
551         display_name: None,
552         published: inserted_person.published,
553         avatar: None,
554         actor_id: inserted_person.actor_id.to_owned(),
555         local: true,
556         banned: false,
557         deleted: false,
558         admin: false,
559         bot_account: false,
560         bio: None,
561         banner: None,
562         updated: None,
563         inbox_url: inserted_person.inbox_url.to_owned(),
564         shared_inbox_url: None,
565         matrix_user_id: None,
566         ban_expires: None,
567       },
568       post: Post {
569         id: inserted_post.id,
570         name: inserted_post.name.to_owned(),
571         creator_id: inserted_person.id,
572         url: None,
573         body: None,
574         published: inserted_post.published,
575         updated: None,
576         community_id: inserted_community.id,
577         removed: false,
578         deleted: false,
579         locked: false,
580         stickied: false,
581         nsfw: false,
582         embed_title: None,
583         embed_description: None,
584         embed_video_url: None,
585         thumbnail_url: None,
586         ap_id: inserted_post.ap_id.to_owned(),
587         local: true,
588         language_id: Default::default(),
589       },
590       community: CommunitySafe {
591         id: inserted_community.id,
592         name: "test community 5".to_string(),
593         icon: None,
594         removed: false,
595         deleted: false,
596         nsfw: false,
597         actor_id: inserted_community.actor_id.to_owned(),
598         local: true,
599         title: "nada".to_owned(),
600         description: None,
601         updated: None,
602         banner: None,
603         hidden: false,
604         posting_restricted_to_mods: false,
605         published: inserted_community.published,
606       },
607       counts: CommentAggregates {
608         id: agg.id,
609         comment_id: inserted_comment_0.id,
610         score: 1,
611         upvotes: 1,
612         downvotes: 0,
613         published: agg.published,
614         child_count: 5,
615       },
616     };
617
618     let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
619     expected_comment_view_with_person.my_vote = Some(1);
620
621     let read_comment_views_no_person = CommentQuery::builder()
622       .conn(&conn)
623       .post_id(Some(inserted_post.id))
624       .build()
625       .list()
626       .unwrap();
627
628     assert_eq!(
629       expected_comment_view_no_person,
630       read_comment_views_no_person[0]
631     );
632
633     let read_comment_views_with_person = CommentQuery::builder()
634       .conn(&conn)
635       .post_id(Some(inserted_post.id))
636       .local_user(Some(&inserted_local_user))
637       .build()
638       .list()
639       .unwrap();
640
641     assert_eq!(
642       expected_comment_view_with_person,
643       read_comment_views_with_person[0]
644     );
645
646     // Make sure its 1, not showing the blocked comment
647     assert_eq!(5, read_comment_views_with_person.len());
648
649     let read_comment_from_blocked_person =
650       CommentView::read(&conn, inserted_comment_1.id, Some(inserted_person.id)).unwrap();
651
652     // Make sure block set the creator blocked
653     assert!(read_comment_from_blocked_person.creator_blocked);
654
655     let top_path = inserted_comment_0.path;
656     let read_comment_views_top_path = CommentQuery::builder()
657       .conn(&conn)
658       .post_id(Some(inserted_post.id))
659       .parent_path(Some(top_path))
660       .build()
661       .list()
662       .unwrap();
663
664     let child_path = inserted_comment_1.to_owned().path;
665     let read_comment_views_child_path = CommentQuery::builder()
666       .conn(&conn)
667       .post_id(Some(inserted_post.id))
668       .parent_path(Some(child_path))
669       .build()
670       .list()
671       .unwrap();
672
673     // Make sure the comment parent-limited fetch is correct
674     assert_eq!(6, read_comment_views_top_path.len());
675     assert_eq!(4, read_comment_views_child_path.len());
676
677     // Make sure it contains the parent, but not the comment from the other tree
678     let child_comments = read_comment_views_child_path
679       .into_iter()
680       .map(|c| c.comment)
681       .collect::<Vec<Comment>>();
682     assert!(child_comments.contains(&inserted_comment_1));
683     assert!(!child_comments.contains(&inserted_comment_2));
684
685     let read_comment_views_top_max_depth = CommentQuery::builder()
686       .conn(&conn)
687       .post_id(Some(inserted_post.id))
688       .max_depth(Some(1))
689       .build()
690       .list()
691       .unwrap();
692
693     // Make sure a depth limited one only has the top comment
694     assert_eq!(
695       expected_comment_view_no_person,
696       read_comment_views_top_max_depth[0]
697     );
698     assert_eq!(1, read_comment_views_top_max_depth.len());
699
700     let child_path = inserted_comment_1.path;
701     let read_comment_views_parent_max_depth = CommentQuery::builder()
702       .conn(&conn)
703       .post_id(Some(inserted_post.id))
704       .parent_path(Some(child_path))
705       .max_depth(Some(1))
706       .sort(Some(CommentSortType::New))
707       .build()
708       .list()
709       .unwrap();
710
711     // Make sure a depth limited one, and given child comment 1, has 3
712     assert!(read_comment_views_parent_max_depth[2]
713       .comment
714       .content
715       .eq("Comment 3"));
716     assert_eq!(3, read_comment_views_parent_max_depth.len());
717
718     // Delete everything
719     let like_removed =
720       CommentLike::remove(&conn, inserted_person.id, inserted_comment_0.id).unwrap();
721     let num_deleted = Comment::delete(&conn, inserted_comment_0.id).unwrap();
722     Comment::delete(&conn, inserted_comment_1.id).unwrap();
723     Post::delete(&conn, inserted_post.id).unwrap();
724     Community::delete(&conn, inserted_community.id).unwrap();
725     Person::delete(&conn, inserted_person.id).unwrap();
726     Person::delete(&conn, inserted_person_2.id).unwrap();
727
728     assert_eq!(1, num_deleted);
729     assert_eq!(1, like_removed);
730   }
731 }