]> Untitled Git - lemmy.git/blob - crates/db_views/src/comment_view.rs
Adding distinguish comment. Fixes #2002 (#2391)
[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     person::{Person, PersonSafe},
24     person_block::PersonBlock,
25     post::Post,
26   },
27   traits::{ToSafe, ViewToVec},
28   utils::{functions::hot_rank, fuzzy_search, limit_and_offset_unlimited},
29   CommentSortType,
30   ListingType,
31 };
32 use typed_builder::TypedBuilder;
33
34 type CommentViewTuple = (
35   Comment,
36   PersonSafe,
37   Post,
38   CommunitySafe,
39   CommentAggregates,
40   Option<CommunityPersonBan>,
41   Option<CommunityFollower>,
42   Option<CommentSaved>,
43   Option<PersonBlock>,
44   Option<i16>,
45 );
46
47 impl CommentView {
48   pub fn read(
49     conn: &PgConnection,
50     comment_id: CommentId,
51     my_person_id: Option<PersonId>,
52   ) -> Result<Self, Error> {
53     // The left join below will return None in this case
54     let person_id_join = my_person_id.unwrap_or(PersonId(-1));
55
56     let (
57       comment,
58       creator,
59       post,
60       community,
61       counts,
62       creator_banned_from_community,
63       follower,
64       saved,
65       creator_blocked,
66       comment_like,
67     ) = comment::table
68       .find(comment_id)
69       .inner_join(person::table)
70       .inner_join(post::table)
71       .inner_join(community::table.on(post::community_id.eq(community::id)))
72       .inner_join(comment_aggregates::table)
73       .left_join(
74         community_person_ban::table.on(
75           community::id
76             .eq(community_person_ban::community_id)
77             .and(community_person_ban::person_id.eq(comment::creator_id))
78             .and(
79               community_person_ban::expires
80                 .is_null()
81                 .or(community_person_ban::expires.gt(now)),
82             ),
83         ),
84       )
85       .left_join(
86         community_follower::table.on(
87           post::community_id
88             .eq(community_follower::community_id)
89             .and(community_follower::person_id.eq(person_id_join)),
90         ),
91       )
92       .left_join(
93         comment_saved::table.on(
94           comment::id
95             .eq(comment_saved::comment_id)
96             .and(comment_saved::person_id.eq(person_id_join)),
97         ),
98       )
99       .left_join(
100         person_block::table.on(
101           comment::creator_id
102             .eq(person_block::target_id)
103             .and(person_block::person_id.eq(person_id_join)),
104         ),
105       )
106       .left_join(
107         comment_like::table.on(
108           comment::id
109             .eq(comment_like::comment_id)
110             .and(comment_like::person_id.eq(person_id_join)),
111         ),
112       )
113       .select((
114         comment::all_columns,
115         Person::safe_columns_tuple(),
116         post::all_columns,
117         Community::safe_columns_tuple(),
118         comment_aggregates::all_columns,
119         community_person_ban::all_columns.nullable(),
120         community_follower::all_columns.nullable(),
121         comment_saved::all_columns.nullable(),
122         person_block::all_columns.nullable(),
123         comment_like::score.nullable(),
124       ))
125       .first::<CommentViewTuple>(conn)?;
126
127     // If a person is given, then my_vote, if None, should be 0, not null
128     // Necessary to differentiate between other person's votes
129     let my_vote = if my_person_id.is_some() && comment_like.is_none() {
130       Some(0)
131     } else {
132       comment_like
133     };
134
135     Ok(CommentView {
136       comment,
137       post,
138       creator,
139       community,
140       counts,
141       creator_banned_from_community: creator_banned_from_community.is_some(),
142       subscribed: CommunityFollower::to_subscribed_type(&follower),
143       saved: saved.is_some(),
144       creator_blocked: creator_blocked.is_some(),
145       my_vote,
146     })
147   }
148 }
149
150 #[derive(TypedBuilder)]
151 #[builder(field_defaults(default))]
152 pub struct CommentQuery<'a> {
153   #[builder(!default)]
154   conn: &'a PgConnection,
155   listing_type: Option<ListingType>,
156   sort: Option<CommentSortType>,
157   community_id: Option<CommunityId>,
158   community_actor_id: Option<DbUrl>,
159   post_id: Option<PostId>,
160   parent_path: Option<Ltree>,
161   creator_id: Option<PersonId>,
162   my_person_id: Option<PersonId>,
163   search_term: Option<String>,
164   saved_only: Option<bool>,
165   show_bot_accounts: 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.my_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.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.my_person_id.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::{comment::*, community::*, person::*, person_block::PersonBlockForm, post::*},
377     traits::{Blockable, Crud, Likeable},
378     utils::establish_unpooled_connection,
379     SubscribedType,
380   };
381   use serial_test::serial;
382
383   #[test]
384   #[serial]
385   fn test_crud() {
386     let conn = establish_unpooled_connection();
387
388     let new_person = PersonForm {
389       name: "timmy".into(),
390       public_key: Some("pubkey".to_string()),
391       ..PersonForm::default()
392     };
393
394     let inserted_person = Person::create(&conn, &new_person).unwrap();
395
396     let new_person_2 = PersonForm {
397       name: "sara".into(),
398       public_key: Some("pubkey".to_string()),
399       ..PersonForm::default()
400     };
401
402     let inserted_person_2 = Person::create(&conn, &new_person_2).unwrap();
403
404     let new_community = CommunityForm {
405       name: "test community 5".to_string(),
406       title: "nada".to_owned(),
407       public_key: Some("pubkey".to_string()),
408       ..CommunityForm::default()
409     };
410
411     let inserted_community = Community::create(&conn, &new_community).unwrap();
412
413     let new_post = PostForm {
414       name: "A test post 2".into(),
415       creator_id: inserted_person.id,
416       community_id: inserted_community.id,
417       ..PostForm::default()
418     };
419
420     let inserted_post = Post::create(&conn, &new_post).unwrap();
421
422     // Create a comment tree with this hierarchy
423     //       0
424     //     \     \
425     //    1      2
426     //    \
427     //  3  4
428     //     \
429     //     5
430     let comment_form_0 = CommentForm {
431       content: "Comment 0".into(),
432       creator_id: inserted_person.id,
433       post_id: inserted_post.id,
434       ..CommentForm::default()
435     };
436
437     let inserted_comment_0 = Comment::create(&conn, &comment_form_0, None).unwrap();
438
439     let comment_form_1 = CommentForm {
440       content: "Comment 1, A test blocked comment".into(),
441       creator_id: inserted_person_2.id,
442       post_id: inserted_post.id,
443       ..CommentForm::default()
444     };
445
446     let inserted_comment_1 =
447       Comment::create(&conn, &comment_form_1, Some(&inserted_comment_0.path)).unwrap();
448
449     let comment_form_2 = CommentForm {
450       content: "Comment 2".into(),
451       creator_id: inserted_person.id,
452       post_id: inserted_post.id,
453       ..CommentForm::default()
454     };
455
456     let inserted_comment_2 =
457       Comment::create(&conn, &comment_form_2, Some(&inserted_comment_0.path)).unwrap();
458
459     let comment_form_3 = CommentForm {
460       content: "Comment 3".into(),
461       creator_id: inserted_person.id,
462       post_id: inserted_post.id,
463       ..CommentForm::default()
464     };
465
466     let _inserted_comment_3 =
467       Comment::create(&conn, &comment_form_3, Some(&inserted_comment_1.path)).unwrap();
468
469     let comment_form_4 = CommentForm {
470       content: "Comment 4".into(),
471       creator_id: inserted_person.id,
472       post_id: inserted_post.id,
473       ..CommentForm::default()
474     };
475
476     let inserted_comment_4 =
477       Comment::create(&conn, &comment_form_4, Some(&inserted_comment_1.path)).unwrap();
478
479     let comment_form_5 = CommentForm {
480       content: "Comment 5".into(),
481       creator_id: inserted_person.id,
482       post_id: inserted_post.id,
483       ..CommentForm::default()
484     };
485
486     let _inserted_comment_5 =
487       Comment::create(&conn, &comment_form_5, Some(&inserted_comment_4.path)).unwrap();
488
489     let timmy_blocks_sara_form = PersonBlockForm {
490       person_id: inserted_person.id,
491       target_id: inserted_person_2.id,
492     };
493
494     let inserted_block = PersonBlock::block(&conn, &timmy_blocks_sara_form).unwrap();
495
496     let expected_block = PersonBlock {
497       id: inserted_block.id,
498       person_id: inserted_person.id,
499       target_id: inserted_person_2.id,
500       published: inserted_block.published,
501     };
502
503     assert_eq!(expected_block, inserted_block);
504
505     let comment_like_form = CommentLikeForm {
506       comment_id: inserted_comment_0.id,
507       post_id: inserted_post.id,
508       person_id: inserted_person.id,
509       score: 1,
510     };
511
512     let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
513
514     let agg = CommentAggregates::read(&conn, inserted_comment_0.id).unwrap();
515
516     let top_path = inserted_comment_0.to_owned().path;
517     let expected_comment_view_no_person = CommentView {
518       creator_banned_from_community: false,
519       my_vote: None,
520       subscribed: SubscribedType::NotSubscribed,
521       saved: false,
522       creator_blocked: false,
523       comment: Comment {
524         id: inserted_comment_0.id,
525         content: "Comment 0".into(),
526         creator_id: inserted_person.id,
527         post_id: inserted_post.id,
528         removed: false,
529         deleted: false,
530         published: inserted_comment_0.published,
531         ap_id: inserted_comment_0.ap_id,
532         updated: None,
533         local: true,
534         distinguished: false,
535         path: top_path,
536       },
537       creator: PersonSafe {
538         id: inserted_person.id,
539         name: "timmy".into(),
540         display_name: None,
541         published: inserted_person.published,
542         avatar: None,
543         actor_id: inserted_person.actor_id.to_owned(),
544         local: true,
545         banned: false,
546         deleted: false,
547         admin: false,
548         bot_account: false,
549         bio: None,
550         banner: None,
551         updated: None,
552         inbox_url: inserted_person.inbox_url.to_owned(),
553         shared_inbox_url: None,
554         matrix_user_id: None,
555         ban_expires: None,
556       },
557       post: Post {
558         id: inserted_post.id,
559         name: inserted_post.name.to_owned(),
560         creator_id: inserted_person.id,
561         url: None,
562         body: None,
563         published: inserted_post.published,
564         updated: None,
565         community_id: inserted_community.id,
566         removed: false,
567         deleted: false,
568         locked: false,
569         stickied: false,
570         nsfw: false,
571         embed_title: None,
572         embed_description: None,
573         embed_video_url: None,
574         thumbnail_url: None,
575         ap_id: inserted_post.ap_id.to_owned(),
576         local: true,
577       },
578       community: CommunitySafe {
579         id: inserted_community.id,
580         name: "test community 5".to_string(),
581         icon: None,
582         removed: false,
583         deleted: false,
584         nsfw: false,
585         actor_id: inserted_community.actor_id.to_owned(),
586         local: true,
587         title: "nada".to_owned(),
588         description: None,
589         updated: None,
590         banner: None,
591         hidden: false,
592         posting_restricted_to_mods: false,
593         published: inserted_community.published,
594       },
595       counts: CommentAggregates {
596         id: agg.id,
597         comment_id: inserted_comment_0.id,
598         score: 1,
599         upvotes: 1,
600         downvotes: 0,
601         published: agg.published,
602         child_count: 5,
603       },
604     };
605
606     let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
607     expected_comment_view_with_person.my_vote = Some(1);
608
609     let read_comment_views_no_person = CommentQuery::builder()
610       .conn(&conn)
611       .post_id(Some(inserted_post.id))
612       .build()
613       .list()
614       .unwrap();
615
616     assert_eq!(
617       expected_comment_view_no_person,
618       read_comment_views_no_person[0]
619     );
620
621     let read_comment_views_with_person = CommentQuery::builder()
622       .conn(&conn)
623       .post_id(Some(inserted_post.id))
624       .my_person_id(Some(inserted_person.id))
625       .build()
626       .list()
627       .unwrap();
628
629     assert_eq!(
630       expected_comment_view_with_person,
631       read_comment_views_with_person[0]
632     );
633
634     // Make sure its 1, not showing the blocked comment
635     assert_eq!(5, read_comment_views_with_person.len());
636
637     let read_comment_from_blocked_person =
638       CommentView::read(&conn, inserted_comment_1.id, Some(inserted_person.id)).unwrap();
639
640     // Make sure block set the creator blocked
641     assert!(read_comment_from_blocked_person.creator_blocked);
642
643     let top_path = inserted_comment_0.path;
644     let read_comment_views_top_path = CommentQuery::builder()
645       .conn(&conn)
646       .post_id(Some(inserted_post.id))
647       .parent_path(Some(top_path))
648       .build()
649       .list()
650       .unwrap();
651
652     let child_path = inserted_comment_1.to_owned().path;
653     let read_comment_views_child_path = CommentQuery::builder()
654       .conn(&conn)
655       .post_id(Some(inserted_post.id))
656       .parent_path(Some(child_path))
657       .build()
658       .list()
659       .unwrap();
660
661     // Make sure the comment parent-limited fetch is correct
662     assert_eq!(6, read_comment_views_top_path.len());
663     assert_eq!(4, read_comment_views_child_path.len());
664
665     // Make sure it contains the parent, but not the comment from the other tree
666     let child_comments = read_comment_views_child_path
667       .into_iter()
668       .map(|c| c.comment)
669       .collect::<Vec<Comment>>();
670     assert!(child_comments.contains(&inserted_comment_1));
671     assert!(!child_comments.contains(&inserted_comment_2));
672
673     let read_comment_views_top_max_depth = CommentQuery::builder()
674       .conn(&conn)
675       .post_id(Some(inserted_post.id))
676       .max_depth(Some(1))
677       .build()
678       .list()
679       .unwrap();
680
681     // Make sure a depth limited one only has the top comment
682     assert_eq!(
683       expected_comment_view_no_person,
684       read_comment_views_top_max_depth[0]
685     );
686     assert_eq!(1, read_comment_views_top_max_depth.len());
687
688     let child_path = inserted_comment_1.path;
689     let read_comment_views_parent_max_depth = CommentQuery::builder()
690       .conn(&conn)
691       .post_id(Some(inserted_post.id))
692       .parent_path(Some(child_path))
693       .max_depth(Some(1))
694       .sort(Some(CommentSortType::New))
695       .build()
696       .list()
697       .unwrap();
698
699     // Make sure a depth limited one, and given child comment 1, has 3
700     assert!(read_comment_views_parent_max_depth[2]
701       .comment
702       .content
703       .eq("Comment 3"));
704     assert_eq!(3, read_comment_views_parent_max_depth.len());
705
706     // Delete everything
707     let like_removed =
708       CommentLike::remove(&conn, inserted_person.id, inserted_comment_0.id).unwrap();
709     let num_deleted = Comment::delete(&conn, inserted_comment_0.id).unwrap();
710     Comment::delete(&conn, inserted_comment_1.id).unwrap();
711     Post::delete(&conn, inserted_post.id).unwrap();
712     Community::delete(&conn, inserted_community.id).unwrap();
713     Person::delete(&conn, inserted_person.id).unwrap();
714     Person::delete(&conn, inserted_person_2.id).unwrap();
715
716     assert_eq!(1, num_deleted);
717     assert_eq!(1, like_removed);
718   }
719 }