1 use crate::structs::CommentView;
2 use diesel::{dsl::*, result::Error, *};
3 use diesel_ltree::{nlevel, subpath, Ltree, LtreeExtensions};
5 aggregates::structs::CommentAggregates,
6 newtypes::{CommentId, CommunityId, DbUrl, PersonId, PostId},
21 comment::{Comment, CommentSaved},
22 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
23 person::{Person, PersonSafe},
24 person_block::PersonBlock,
27 traits::{MaybeOptional, ToSafe, ViewToVec},
28 utils::{functions::hot_rank, fuzzy_search, limit_and_offset_unlimited},
33 type CommentViewTuple = (
39 Option<CommunityPersonBan>,
40 Option<CommunityFollower>,
49 comment_id: CommentId,
50 my_person_id: Option<PersonId>,
51 ) -> Result<Self, Error> {
52 // The left join below will return None in this case
53 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
61 creator_banned_from_community,
68 .inner_join(person::table)
69 .inner_join(post::table)
70 .inner_join(community::table.on(post::community_id.eq(community::id)))
71 .inner_join(comment_aggregates::table)
73 community_person_ban::table.on(
75 .eq(community_person_ban::community_id)
76 .and(community_person_ban::person_id.eq(comment::creator_id))
78 community_person_ban::expires
80 .or(community_person_ban::expires.gt(now)),
85 community_follower::table.on(
87 .eq(community_follower::community_id)
88 .and(community_follower::person_id.eq(person_id_join)),
92 comment_saved::table.on(
94 .eq(comment_saved::comment_id)
95 .and(comment_saved::person_id.eq(person_id_join)),
99 person_block::table.on(
101 .eq(person_block::target_id)
102 .and(person_block::person_id.eq(person_id_join)),
106 comment_like::table.on(
108 .eq(comment_like::comment_id)
109 .and(comment_like::person_id.eq(person_id_join)),
113 comment::all_columns,
114 Person::safe_columns_tuple(),
116 Community::safe_columns_tuple(),
117 comment_aggregates::all_columns,
118 community_person_ban::all_columns.nullable(),
119 community_follower::all_columns.nullable(),
120 comment_saved::all_columns.nullable(),
121 person_block::all_columns.nullable(),
122 comment_like::score.nullable(),
124 .first::<CommentViewTuple>(conn)?;
126 // If a person is given, then my_vote, if None, should be 0, not null
127 // Necessary to differentiate between other person's votes
128 let my_vote = if my_person_id.is_some() && comment_like.is_none() {
140 creator_banned_from_community: creator_banned_from_community.is_some(),
141 subscribed: CommunityFollower::to_subscribed_type(&follower),
142 saved: saved.is_some(),
143 creator_blocked: creator_blocked.is_some(),
149 pub struct CommentQueryBuilder<'a> {
150 conn: &'a PgConnection,
151 listing_type: Option<ListingType>,
152 sort: Option<CommentSortType>,
153 community_id: Option<CommunityId>,
154 community_actor_id: Option<DbUrl>,
155 post_id: Option<PostId>,
156 parent_path: Option<Ltree>,
157 creator_id: Option<PersonId>,
158 my_person_id: Option<PersonId>,
159 search_term: Option<String>,
160 saved_only: Option<bool>,
161 show_bot_accounts: Option<bool>,
164 max_depth: Option<i32>,
167 impl<'a> CommentQueryBuilder<'a> {
168 pub fn create(conn: &'a PgConnection) -> Self {
169 CommentQueryBuilder {
171 listing_type: Some(ListingType::All),
174 community_actor_id: None,
181 show_bot_accounts: None,
188 pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
189 self.listing_type = listing_type.get_optional();
193 pub fn sort<T: MaybeOptional<CommentSortType>>(mut self, sort: T) -> Self {
194 self.sort = sort.get_optional();
198 pub fn post_id<T: MaybeOptional<PostId>>(mut self, post_id: T) -> Self {
199 self.post_id = post_id.get_optional();
203 pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
204 self.creator_id = creator_id.get_optional();
208 pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
209 self.community_id = community_id.get_optional();
213 pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
214 self.my_person_id = my_person_id.get_optional();
218 pub fn community_actor_id<T: MaybeOptional<DbUrl>>(mut self, community_actor_id: T) -> Self {
219 self.community_actor_id = community_actor_id.get_optional();
223 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
224 self.search_term = search_term.get_optional();
228 pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
229 self.saved_only = saved_only.get_optional();
233 pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
234 self.show_bot_accounts = show_bot_accounts.get_optional();
238 pub fn parent_path<T: MaybeOptional<Ltree>>(mut self, parent_path: T) -> Self {
239 self.parent_path = parent_path.get_optional();
243 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
244 self.page = page.get_optional();
248 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
249 self.limit = limit.get_optional();
253 pub fn max_depth<T: MaybeOptional<i32>>(mut self, max_depth: T) -> Self {
254 self.max_depth = max_depth.get_optional();
258 pub fn list(self) -> Result<Vec<CommentView>, Error> {
261 // The left join below will return None in this case
262 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
264 let mut query = comment::table
265 .inner_join(person::table)
266 .inner_join(post::table)
267 .inner_join(community::table.on(post::community_id.eq(community::id)))
268 .inner_join(comment_aggregates::table)
270 community_person_ban::table.on(
272 .eq(community_person_ban::community_id)
273 .and(community_person_ban::person_id.eq(comment::creator_id))
275 community_person_ban::expires
277 .or(community_person_ban::expires.gt(now)),
282 community_follower::table.on(
284 .eq(community_follower::community_id)
285 .and(community_follower::person_id.eq(person_id_join)),
289 comment_saved::table.on(
291 .eq(comment_saved::comment_id)
292 .and(comment_saved::person_id.eq(person_id_join)),
296 person_block::table.on(
298 .eq(person_block::target_id)
299 .and(person_block::person_id.eq(person_id_join)),
303 community_block::table.on(
305 .eq(community_block::community_id)
306 .and(community_block::person_id.eq(person_id_join)),
310 comment_like::table.on(
312 .eq(comment_like::comment_id)
313 .and(comment_like::person_id.eq(person_id_join)),
317 comment::all_columns,
318 Person::safe_columns_tuple(),
320 Community::safe_columns_tuple(),
321 comment_aggregates::all_columns,
322 community_person_ban::all_columns.nullable(),
323 community_follower::all_columns.nullable(),
324 comment_saved::all_columns.nullable(),
325 person_block::all_columns.nullable(),
326 comment_like::score.nullable(),
330 if let Some(creator_id) = self.creator_id {
331 query = query.filter(comment::creator_id.eq(creator_id));
334 if let Some(post_id) = self.post_id {
335 query = query.filter(comment::post_id.eq(post_id));
338 if let Some(parent_path) = self.parent_path.as_ref() {
339 query = query.filter(comment::path.contained_by(parent_path));
342 if let Some(search_term) = self.search_term {
343 query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
346 if let Some(listing_type) = self.listing_type {
348 ListingType::Subscribed => {
349 query = query.filter(community_follower::person_id.is_not_null())
350 } // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
351 ListingType::Local => {
352 query = query.filter(community::local.eq(true)).filter(
355 .or(community_follower::person_id.eq(person_id_join)),
358 ListingType::All => {
359 query = query.filter(
362 .or(community_follower::person_id.eq(person_id_join)),
368 if let Some(community_id) = self.community_id {
369 query = query.filter(post::community_id.eq(community_id));
372 if let Some(community_actor_id) = self.community_actor_id {
373 query = query.filter(community::actor_id.eq(community_actor_id))
376 if self.saved_only.unwrap_or(false) {
377 query = query.filter(comment_saved::id.is_not_null());
380 if !self.show_bot_accounts.unwrap_or(true) {
381 query = query.filter(person::bot_account.eq(false));
384 // Don't show blocked communities or persons
385 if self.my_person_id.is_some() {
386 query = query.filter(community_block::person_id.is_null());
387 query = query.filter(person_block::person_id.is_null());
390 // A Max depth given means its a tree fetch
391 let (limit, offset) = if let Some(max_depth) = self.max_depth {
392 let depth_limit = if let Some(parent_path) = self.parent_path.as_ref() {
393 parent_path.0.split('.').count() as i32 + max_depth
394 // Add one because of root "0"
399 query = query.filter(nlevel(comment::path).le(depth_limit));
401 // Always order by the parent path first
402 query = query.order_by(subpath(comment::path, 0, -1));
404 // TODO limit question. Limiting does not work for comment threads ATM, only max_depth
405 // For now, don't do any limiting for tree fetches
406 // https://stackoverflow.com/questions/72983614/postgres-ltree-how-to-limit-the-max-number-of-children-at-any-given-level
408 // Don't use the regular error-checking one, many more comments must ofter be fetched.
409 // This does not work for comment trees, and the limit should be manually set to a high number
411 // If a max depth is given, then you know its a tree fetch, and limits should be ignored
414 limit_and_offset_unlimited(self.page, self.limit)
417 query = match self.sort.unwrap_or(CommentSortType::Hot) {
418 CommentSortType::Hot => query
419 .then_order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
420 .then_order_by(comment_aggregates::published.desc()),
421 CommentSortType::New => query.then_order_by(comment::published.desc()),
422 CommentSortType::Old => query.then_order_by(comment::published.asc()),
423 CommentSortType::Top => query.order_by(comment_aggregates::score.desc()),
426 // Note: deleted and removed comments are done on the front side
430 .load::<CommentViewTuple>(self.conn)?;
432 Ok(CommentView::from_tuple_to_vec(res))
436 impl ViewToVec for CommentView {
437 type DbTuple = CommentViewTuple;
438 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
442 comment: a.0.to_owned(),
443 creator: a.1.to_owned(),
444 post: a.2.to_owned(),
445 community: a.3.to_owned(),
446 counts: a.4.to_owned(),
447 creator_banned_from_community: a.5.is_some(),
448 subscribed: CommunityFollower::to_subscribed_type(&a.6),
449 saved: a.7.is_some(),
450 creator_blocked: a.8.is_some(),
453 .collect::<Vec<Self>>()
459 use crate::comment_view::*;
460 use lemmy_db_schema::{
461 aggregates::structs::CommentAggregates,
462 source::{comment::*, community::*, person::*, person_block::PersonBlockForm, post::*},
463 traits::{Blockable, Crud, Likeable},
464 utils::establish_unpooled_connection,
467 use serial_test::serial;
472 let conn = establish_unpooled_connection();
474 let new_person = PersonForm {
475 name: "timmy".into(),
476 public_key: Some("pubkey".to_string()),
477 ..PersonForm::default()
480 let inserted_person = Person::create(&conn, &new_person).unwrap();
482 let new_person_2 = PersonForm {
484 public_key: Some("pubkey".to_string()),
485 ..PersonForm::default()
488 let inserted_person_2 = Person::create(&conn, &new_person_2).unwrap();
490 let new_community = CommunityForm {
491 name: "test community 5".to_string(),
492 title: "nada".to_owned(),
493 public_key: Some("pubkey".to_string()),
494 ..CommunityForm::default()
497 let inserted_community = Community::create(&conn, &new_community).unwrap();
499 let new_post = PostForm {
500 name: "A test post 2".into(),
501 creator_id: inserted_person.id,
502 community_id: inserted_community.id,
503 ..PostForm::default()
506 let inserted_post = Post::create(&conn, &new_post).unwrap();
508 // Create a comment tree with this hierarchy
516 let comment_form_0 = CommentForm {
517 content: "Comment 0".into(),
518 creator_id: inserted_person.id,
519 post_id: inserted_post.id,
520 ..CommentForm::default()
523 let inserted_comment_0 = Comment::create(&conn, &comment_form_0, None).unwrap();
525 let comment_form_1 = CommentForm {
526 content: "Comment 1, A test blocked comment".into(),
527 creator_id: inserted_person_2.id,
528 post_id: inserted_post.id,
529 ..CommentForm::default()
532 let inserted_comment_1 =
533 Comment::create(&conn, &comment_form_1, Some(&inserted_comment_0.path)).unwrap();
535 let comment_form_2 = CommentForm {
536 content: "Comment 2".into(),
537 creator_id: inserted_person.id,
538 post_id: inserted_post.id,
539 ..CommentForm::default()
542 let inserted_comment_2 =
543 Comment::create(&conn, &comment_form_2, Some(&inserted_comment_0.path)).unwrap();
545 let comment_form_3 = CommentForm {
546 content: "Comment 3".into(),
547 creator_id: inserted_person.id,
548 post_id: inserted_post.id,
549 ..CommentForm::default()
552 let _inserted_comment_3 =
553 Comment::create(&conn, &comment_form_3, Some(&inserted_comment_1.path)).unwrap();
555 let comment_form_4 = CommentForm {
556 content: "Comment 4".into(),
557 creator_id: inserted_person.id,
558 post_id: inserted_post.id,
559 ..CommentForm::default()
562 let inserted_comment_4 =
563 Comment::create(&conn, &comment_form_4, Some(&inserted_comment_1.path)).unwrap();
565 let comment_form_5 = CommentForm {
566 content: "Comment 5".into(),
567 creator_id: inserted_person.id,
568 post_id: inserted_post.id,
569 ..CommentForm::default()
572 let _inserted_comment_5 =
573 Comment::create(&conn, &comment_form_5, Some(&inserted_comment_4.path)).unwrap();
575 let timmy_blocks_sara_form = PersonBlockForm {
576 person_id: inserted_person.id,
577 target_id: inserted_person_2.id,
580 let inserted_block = PersonBlock::block(&conn, &timmy_blocks_sara_form).unwrap();
582 let expected_block = PersonBlock {
583 id: inserted_block.id,
584 person_id: inserted_person.id,
585 target_id: inserted_person_2.id,
586 published: inserted_block.published,
589 assert_eq!(expected_block, inserted_block);
591 let comment_like_form = CommentLikeForm {
592 comment_id: inserted_comment_0.id,
593 post_id: inserted_post.id,
594 person_id: inserted_person.id,
598 let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
600 let agg = CommentAggregates::read(&conn, inserted_comment_0.id).unwrap();
602 let top_path = inserted_comment_0.to_owned().path;
603 let expected_comment_view_no_person = CommentView {
604 creator_banned_from_community: false,
606 subscribed: SubscribedType::NotSubscribed,
608 creator_blocked: false,
610 id: inserted_comment_0.id,
611 content: "Comment 0".into(),
612 creator_id: inserted_person.id,
613 post_id: inserted_post.id,
616 published: inserted_comment_0.published,
617 ap_id: inserted_comment_0.ap_id,
622 creator: PersonSafe {
623 id: inserted_person.id,
624 name: "timmy".into(),
626 published: inserted_person.published,
628 actor_id: inserted_person.actor_id.to_owned(),
637 inbox_url: inserted_person.inbox_url.to_owned(),
638 shared_inbox_url: None,
639 matrix_user_id: None,
643 id: inserted_post.id,
644 name: inserted_post.name.to_owned(),
645 creator_id: inserted_person.id,
648 published: inserted_post.published,
650 community_id: inserted_community.id,
657 embed_description: None,
658 embed_video_url: None,
660 ap_id: inserted_post.ap_id.to_owned(),
663 community: CommunitySafe {
664 id: inserted_community.id,
665 name: "test community 5".to_string(),
670 actor_id: inserted_community.actor_id.to_owned(),
672 title: "nada".to_owned(),
677 posting_restricted_to_mods: false,
678 published: inserted_community.published,
680 counts: CommentAggregates {
682 comment_id: inserted_comment_0.id,
686 published: agg.published,
691 let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
692 expected_comment_view_with_person.my_vote = Some(1);
694 let read_comment_views_no_person = CommentQueryBuilder::create(&conn)
695 .post_id(inserted_post.id)
700 expected_comment_view_no_person,
701 read_comment_views_no_person[0]
704 let read_comment_views_with_person = CommentQueryBuilder::create(&conn)
705 .post_id(inserted_post.id)
706 .my_person_id(inserted_person.id)
711 expected_comment_view_with_person,
712 read_comment_views_with_person[0]
715 // Make sure its 1, not showing the blocked comment
716 assert_eq!(5, read_comment_views_with_person.len());
718 let read_comment_from_blocked_person =
719 CommentView::read(&conn, inserted_comment_1.id, Some(inserted_person.id)).unwrap();
721 // Make sure block set the creator blocked
722 assert!(read_comment_from_blocked_person.creator_blocked);
724 let top_path = inserted_comment_0.path;
725 let read_comment_views_top_path = CommentQueryBuilder::create(&conn)
726 .post_id(inserted_post.id)
727 .parent_path(top_path)
731 let child_path = inserted_comment_1.to_owned().path;
732 let read_comment_views_child_path = CommentQueryBuilder::create(&conn)
733 .post_id(inserted_post.id)
734 .parent_path(child_path)
738 // Make sure the comment parent-limited fetch is correct
739 assert_eq!(6, read_comment_views_top_path.len());
740 assert_eq!(4, read_comment_views_child_path.len());
742 // Make sure it contains the parent, but not the comment from the other tree
743 let child_comments = read_comment_views_child_path
746 .collect::<Vec<Comment>>();
747 assert!(child_comments.contains(&inserted_comment_1));
748 assert!(!child_comments.contains(&inserted_comment_2));
750 let read_comment_views_top_max_depth = CommentQueryBuilder::create(&conn)
751 .post_id(inserted_post.id)
756 // Make sure a depth limited one only has the top comment
758 expected_comment_view_no_person,
759 read_comment_views_top_max_depth[0]
761 assert_eq!(1, read_comment_views_top_max_depth.len());
763 let child_path = inserted_comment_1.path;
764 let read_comment_views_parent_max_depth = CommentQueryBuilder::create(&conn)
765 .post_id(inserted_post.id)
766 .parent_path(child_path)
768 .sort(CommentSortType::New)
772 // Make sure a depth limited one, and given child comment 1, has 3
773 assert!(read_comment_views_parent_max_depth[2]
777 assert_eq!(3, read_comment_views_parent_max_depth.len());
781 CommentLike::remove(&conn, inserted_person.id, inserted_comment_0.id).unwrap();
782 let num_deleted = Comment::delete(&conn, inserted_comment_0.id).unwrap();
783 Comment::delete(&conn, inserted_comment_1.id).unwrap();
784 Post::delete(&conn, inserted_post.id).unwrap();
785 Community::delete(&conn, inserted_community.id).unwrap();
786 Person::delete(&conn, inserted_person.id).unwrap();
787 Person::delete(&conn, inserted_person_2.id).unwrap();
789 assert_eq!(1, num_deleted);
790 assert_eq!(1, like_removed);