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 local_user::LocalUser,
24 person::{Person, PersonSafe},
25 person_block::PersonBlock,
28 traits::{ToSafe, ViewToVec},
29 utils::{functions::hot_rank, fuzzy_search, limit_and_offset_unlimited},
33 use typed_builder::TypedBuilder;
35 type CommentViewTuple = (
41 Option<CommunityPersonBan>,
42 Option<CommunityFollower>,
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));
63 creator_banned_from_community,
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)
75 community_person_ban::table.on(
77 .eq(community_person_ban::community_id)
78 .and(community_person_ban::person_id.eq(comment::creator_id))
80 community_person_ban::expires
82 .or(community_person_ban::expires.gt(now)),
87 community_follower::table.on(
89 .eq(community_follower::community_id)
90 .and(community_follower::person_id.eq(person_id_join)),
94 comment_saved::table.on(
96 .eq(comment_saved::comment_id)
97 .and(comment_saved::person_id.eq(person_id_join)),
101 person_block::table.on(
103 .eq(person_block::target_id)
104 .and(person_block::person_id.eq(person_id_join)),
108 comment_like::table.on(
110 .eq(comment_like::comment_id)
111 .and(comment_like::person_id.eq(person_id_join)),
115 comment::all_columns,
116 Person::safe_columns_tuple(),
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(),
126 .first::<CommentViewTuple>(conn)?;
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() {
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(),
151 #[derive(TypedBuilder)]
152 #[builder(field_defaults(default))]
153 pub struct CommentQuery<'a> {
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>,
168 max_depth: Option<i32>,
171 impl<'a> CommentQuery<'a> {
172 pub fn list(self) -> Result<Vec<CommentView>, Error> {
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));
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)
184 community_person_ban::table.on(
186 .eq(community_person_ban::community_id)
187 .and(community_person_ban::person_id.eq(comment::creator_id))
189 community_person_ban::expires
191 .or(community_person_ban::expires.gt(now)),
196 community_follower::table.on(
198 .eq(community_follower::community_id)
199 .and(community_follower::person_id.eq(person_id_join)),
203 comment_saved::table.on(
205 .eq(comment_saved::comment_id)
206 .and(comment_saved::person_id.eq(person_id_join)),
210 person_block::table.on(
212 .eq(person_block::target_id)
213 .and(person_block::person_id.eq(person_id_join)),
217 community_block::table.on(
219 .eq(community_block::community_id)
220 .and(community_block::person_id.eq(person_id_join)),
224 comment_like::table.on(
226 .eq(comment_like::comment_id)
227 .and(comment_like::person_id.eq(person_id_join)),
231 comment::all_columns,
232 Person::safe_columns_tuple(),
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(),
244 if let Some(creator_id) = self.creator_id {
245 query = query.filter(comment::creator_id.eq(creator_id));
248 if let Some(post_id) = self.post_id {
249 query = query.filter(comment::post_id.eq(post_id));
252 if let Some(parent_path) = self.parent_path.as_ref() {
253 query = query.filter(comment::path.contained_by(parent_path));
256 if let Some(search_term) = self.search_term {
257 query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
260 if let Some(listing_type) = self.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(
269 .or(community_follower::person_id.eq(person_id_join)),
272 ListingType::All => {
273 query = query.filter(
276 .or(community_follower::person_id.eq(person_id_join)),
282 if let Some(community_id) = self.community_id {
283 query = query.filter(post::community_id.eq(community_id));
286 if let Some(community_actor_id) = self.community_actor_id {
287 query = query.filter(community::actor_id.eq(community_actor_id))
290 if self.saved_only.unwrap_or(false) {
291 query = query.filter(comment_saved::id.is_not_null());
294 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
295 query = query.filter(person::bot_account.eq(false));
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());
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"
313 query = query.filter(nlevel(comment::path).le(depth_limit));
315 // Always order by the parent path first
316 query = query.order_by(subpath(comment::path, 0, -1));
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
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
325 // If a max depth is given, then you know its a tree fetch, and limits should be ignored
328 limit_and_offset_unlimited(self.page, self.limit)
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()),
340 // Note: deleted and removed comments are done on the front side
344 .load::<CommentViewTuple>(self.conn)?;
346 Ok(CommentView::from_tuple_to_vec(res))
350 impl ViewToVec for CommentView {
351 type DbTuple = CommentViewTuple;
352 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
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(),
367 .collect::<Vec<Self>>()
373 use crate::comment_view::*;
374 use lemmy_db_schema::{
375 aggregates::structs::CommentAggregates,
379 local_user::LocalUserForm,
381 person_block::PersonBlockForm,
384 traits::{Blockable, Crud, Likeable},
385 utils::establish_unpooled_connection,
388 use serial_test::serial;
393 let conn = establish_unpooled_connection();
395 let new_person = PersonForm {
396 name: "timmy".into(),
397 public_key: Some("pubkey".to_string()),
398 ..PersonForm::default()
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()),
406 let inserted_local_user = LocalUser::create(&conn, &local_user_form).unwrap();
408 let new_person_2 = PersonForm {
410 public_key: Some("pubkey".to_string()),
411 ..PersonForm::default()
413 let inserted_person_2 = Person::create(&conn, &new_person_2).unwrap();
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()
422 let inserted_community = Community::create(&conn, &new_community).unwrap();
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()
431 let inserted_post = Post::create(&conn, &new_post).unwrap();
433 // Create a comment tree with this hierarchy
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()
448 let inserted_comment_0 = Comment::create(&conn, &comment_form_0, None).unwrap();
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()
457 let inserted_comment_1 =
458 Comment::create(&conn, &comment_form_1, Some(&inserted_comment_0.path)).unwrap();
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()
467 let inserted_comment_2 =
468 Comment::create(&conn, &comment_form_2, Some(&inserted_comment_0.path)).unwrap();
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()
477 let _inserted_comment_3 =
478 Comment::create(&conn, &comment_form_3, Some(&inserted_comment_1.path)).unwrap();
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()
487 let inserted_comment_4 =
488 Comment::create(&conn, &comment_form_4, Some(&inserted_comment_1.path)).unwrap();
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()
497 let _inserted_comment_5 =
498 Comment::create(&conn, &comment_form_5, Some(&inserted_comment_4.path)).unwrap();
500 let timmy_blocks_sara_form = PersonBlockForm {
501 person_id: inserted_person.id,
502 target_id: inserted_person_2.id,
505 let inserted_block = PersonBlock::block(&conn, &timmy_blocks_sara_form).unwrap();
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,
514 assert_eq!(expected_block, inserted_block);
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,
523 let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
525 let agg = CommentAggregates::read(&conn, inserted_comment_0.id).unwrap();
527 let top_path = inserted_comment_0.to_owned().path;
528 let expected_comment_view_no_person = CommentView {
529 creator_banned_from_community: false,
531 subscribed: SubscribedType::NotSubscribed,
533 creator_blocked: false,
535 id: inserted_comment_0.id,
536 content: "Comment 0".into(),
537 creator_id: inserted_person.id,
538 post_id: inserted_post.id,
541 published: inserted_comment_0.published,
542 ap_id: inserted_comment_0.ap_id,
545 distinguished: false,
548 creator: PersonSafe {
549 id: inserted_person.id,
550 name: "timmy".into(),
552 published: inserted_person.published,
554 actor_id: inserted_person.actor_id.to_owned(),
563 inbox_url: inserted_person.inbox_url.to_owned(),
564 shared_inbox_url: None,
565 matrix_user_id: None,
569 id: inserted_post.id,
570 name: inserted_post.name.to_owned(),
571 creator_id: inserted_person.id,
574 published: inserted_post.published,
576 community_id: inserted_community.id,
583 embed_description: None,
584 embed_video_url: None,
586 ap_id: inserted_post.ap_id.to_owned(),
588 language_id: Default::default(),
590 community: CommunitySafe {
591 id: inserted_community.id,
592 name: "test community 5".to_string(),
597 actor_id: inserted_community.actor_id.to_owned(),
599 title: "nada".to_owned(),
604 posting_restricted_to_mods: false,
605 published: inserted_community.published,
607 counts: CommentAggregates {
609 comment_id: inserted_comment_0.id,
613 published: agg.published,
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);
621 let read_comment_views_no_person = CommentQuery::builder()
623 .post_id(Some(inserted_post.id))
629 expected_comment_view_no_person,
630 read_comment_views_no_person[0]
633 let read_comment_views_with_person = CommentQuery::builder()
635 .post_id(Some(inserted_post.id))
636 .local_user(Some(&inserted_local_user))
642 expected_comment_view_with_person,
643 read_comment_views_with_person[0]
646 // Make sure its 1, not showing the blocked comment
647 assert_eq!(5, read_comment_views_with_person.len());
649 let read_comment_from_blocked_person =
650 CommentView::read(&conn, inserted_comment_1.id, Some(inserted_person.id)).unwrap();
652 // Make sure block set the creator blocked
653 assert!(read_comment_from_blocked_person.creator_blocked);
655 let top_path = inserted_comment_0.path;
656 let read_comment_views_top_path = CommentQuery::builder()
658 .post_id(Some(inserted_post.id))
659 .parent_path(Some(top_path))
664 let child_path = inserted_comment_1.to_owned().path;
665 let read_comment_views_child_path = CommentQuery::builder()
667 .post_id(Some(inserted_post.id))
668 .parent_path(Some(child_path))
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());
677 // Make sure it contains the parent, but not the comment from the other tree
678 let child_comments = read_comment_views_child_path
681 .collect::<Vec<Comment>>();
682 assert!(child_comments.contains(&inserted_comment_1));
683 assert!(!child_comments.contains(&inserted_comment_2));
685 let read_comment_views_top_max_depth = CommentQuery::builder()
687 .post_id(Some(inserted_post.id))
693 // Make sure a depth limited one only has the top comment
695 expected_comment_view_no_person,
696 read_comment_views_top_max_depth[0]
698 assert_eq!(1, read_comment_views_top_max_depth.len());
700 let child_path = inserted_comment_1.path;
701 let read_comment_views_parent_max_depth = CommentQuery::builder()
703 .post_id(Some(inserted_post.id))
704 .parent_path(Some(child_path))
706 .sort(Some(CommentSortType::New))
711 // Make sure a depth limited one, and given child comment 1, has 3
712 assert!(read_comment_views_parent_max_depth[2]
716 assert_eq!(3, read_comment_views_parent_max_depth.len());
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();
728 assert_eq!(1, num_deleted);
729 assert_eq!(1, like_removed);