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, LocalUserId, PersonId, PostId},
22 comment::{Comment, CommentSaved},
23 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
24 local_user::LocalUser,
25 person::{Person, PersonSafe},
26 person_block::PersonBlock,
29 traits::{ToSafe, ViewToVec},
30 utils::{functions::hot_rank, fuzzy_search, limit_and_offset_unlimited},
34 use typed_builder::TypedBuilder;
36 type CommentViewTuple = (
42 Option<CommunityPersonBan>,
43 Option<CommunityFollower>,
51 conn: &mut PgConnection,
52 comment_id: CommentId,
53 my_person_id: Option<PersonId>,
54 ) -> Result<Self, Error> {
55 // The left join below will return None in this case
56 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
64 creator_banned_from_community,
71 .inner_join(person::table)
72 .inner_join(post::table)
73 .inner_join(community::table.on(post::community_id.eq(community::id)))
74 .inner_join(comment_aggregates::table)
76 community_person_ban::table.on(
78 .eq(community_person_ban::community_id)
79 .and(community_person_ban::person_id.eq(comment::creator_id))
81 community_person_ban::expires
83 .or(community_person_ban::expires.gt(now)),
88 community_follower::table.on(
90 .eq(community_follower::community_id)
91 .and(community_follower::person_id.eq(person_id_join)),
95 comment_saved::table.on(
97 .eq(comment_saved::comment_id)
98 .and(comment_saved::person_id.eq(person_id_join)),
102 person_block::table.on(
104 .eq(person_block::target_id)
105 .and(person_block::person_id.eq(person_id_join)),
109 comment_like::table.on(
111 .eq(comment_like::comment_id)
112 .and(comment_like::person_id.eq(person_id_join)),
116 comment::all_columns,
117 Person::safe_columns_tuple(),
119 Community::safe_columns_tuple(),
120 comment_aggregates::all_columns,
121 community_person_ban::all_columns.nullable(),
122 community_follower::all_columns.nullable(),
123 comment_saved::all_columns.nullable(),
124 person_block::all_columns.nullable(),
125 comment_like::score.nullable(),
127 .first::<CommentViewTuple>(conn)?;
129 // If a person is given, then my_vote, if None, should be 0, not null
130 // Necessary to differentiate between other person's votes
131 let my_vote = if my_person_id.is_some() && comment_like.is_none() {
143 creator_banned_from_community: creator_banned_from_community.is_some(),
144 subscribed: CommunityFollower::to_subscribed_type(&follower),
145 saved: saved.is_some(),
146 creator_blocked: creator_blocked.is_some(),
152 #[derive(TypedBuilder)]
153 #[builder(field_defaults(default))]
154 pub struct CommentQuery<'a> {
156 conn: &'a mut PgConnection,
157 listing_type: Option<ListingType>,
158 sort: Option<CommentSortType>,
159 community_id: Option<CommunityId>,
160 community_actor_id: Option<DbUrl>,
161 post_id: Option<PostId>,
162 parent_path: Option<Ltree>,
163 creator_id: Option<PersonId>,
164 local_user: Option<&'a LocalUser>,
165 search_term: Option<String>,
166 saved_only: Option<bool>,
167 show_deleted_and_removed: Option<bool>,
170 max_depth: Option<i32>,
173 impl<'a> CommentQuery<'a> {
174 pub fn list(self) -> Result<Vec<CommentView>, Error> {
177 // The left join below will return None in this case
178 let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1));
179 let local_user_id_join = self.local_user.map(|l| l.id).unwrap_or(LocalUserId(-1));
181 let mut query = comment::table
182 .inner_join(person::table)
183 .inner_join(post::table)
184 .inner_join(community::table.on(post::community_id.eq(community::id)))
185 .inner_join(comment_aggregates::table)
187 community_person_ban::table.on(
189 .eq(community_person_ban::community_id)
190 .and(community_person_ban::person_id.eq(comment::creator_id))
192 community_person_ban::expires
194 .or(community_person_ban::expires.gt(now)),
199 community_follower::table.on(
201 .eq(community_follower::community_id)
202 .and(community_follower::person_id.eq(person_id_join)),
206 comment_saved::table.on(
208 .eq(comment_saved::comment_id)
209 .and(comment_saved::person_id.eq(person_id_join)),
213 person_block::table.on(
215 .eq(person_block::target_id)
216 .and(person_block::person_id.eq(person_id_join)),
220 community_block::table.on(
222 .eq(community_block::community_id)
223 .and(community_block::person_id.eq(person_id_join)),
227 comment_like::table.on(
229 .eq(comment_like::comment_id)
230 .and(comment_like::person_id.eq(person_id_join)),
234 local_user_language::table.on(
236 .eq(local_user_language::language_id)
237 .and(local_user_language::local_user_id.eq(local_user_id_join)),
241 comment::all_columns,
242 Person::safe_columns_tuple(),
244 Community::safe_columns_tuple(),
245 comment_aggregates::all_columns,
246 community_person_ban::all_columns.nullable(),
247 community_follower::all_columns.nullable(),
248 comment_saved::all_columns.nullable(),
249 person_block::all_columns.nullable(),
250 comment_like::score.nullable(),
254 if let Some(creator_id) = self.creator_id {
255 query = query.filter(comment::creator_id.eq(creator_id));
258 if let Some(post_id) = self.post_id {
259 query = query.filter(comment::post_id.eq(post_id));
262 if let Some(parent_path) = self.parent_path.as_ref() {
263 query = query.filter(comment::path.contained_by(parent_path));
266 if let Some(search_term) = self.search_term {
267 query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
270 if let Some(listing_type) = self.listing_type {
272 ListingType::Subscribed => {
273 query = query.filter(community_follower::person_id.is_not_null())
274 } // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
275 ListingType::Local => {
276 query = query.filter(community::local.eq(true)).filter(
279 .or(community_follower::person_id.eq(person_id_join)),
282 ListingType::All => {
283 query = query.filter(
286 .or(community_follower::person_id.eq(person_id_join)),
292 if let Some(community_id) = self.community_id {
293 query = query.filter(post::community_id.eq(community_id));
296 if let Some(community_actor_id) = self.community_actor_id {
297 query = query.filter(community::actor_id.eq(community_actor_id))
300 if self.saved_only.unwrap_or(false) {
301 query = query.filter(comment_saved::id.is_not_null());
304 if !self.show_deleted_and_removed.unwrap_or(true) {
305 query = query.filter(comment::deleted.eq(false));
306 query = query.filter(comment::removed.eq(false));
309 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
310 query = query.filter(person::bot_account.eq(false));
313 if self.local_user.is_some() {
314 // Filter out the rows with missing languages
315 query = query.filter(local_user_language::id.is_not_null());
317 // Don't show blocked communities or persons
318 query = query.filter(community_block::person_id.is_null());
319 query = query.filter(person_block::person_id.is_null());
322 // A Max depth given means its a tree fetch
323 let (limit, offset) = if let Some(max_depth) = self.max_depth {
324 let depth_limit = if let Some(parent_path) = self.parent_path.as_ref() {
325 parent_path.0.split('.').count() as i32 + max_depth
326 // Add one because of root "0"
331 query = query.filter(nlevel(comment::path).le(depth_limit));
333 // Always order by the parent path first
334 query = query.order_by(subpath(comment::path, 0, -1));
336 // TODO limit question. Limiting does not work for comment threads ATM, only max_depth
337 // For now, don't do any limiting for tree fetches
338 // https://stackoverflow.com/questions/72983614/postgres-ltree-how-to-limit-the-max-number-of-children-at-any-given-level
340 // Don't use the regular error-checking one, many more comments must ofter be fetched.
341 // This does not work for comment trees, and the limit should be manually set to a high number
343 // If a max depth is given, then you know its a tree fetch, and limits should be ignored
346 limit_and_offset_unlimited(self.page, self.limit)
349 query = match self.sort.unwrap_or(CommentSortType::Hot) {
350 CommentSortType::Hot => query
351 .then_order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
352 .then_order_by(comment_aggregates::published.desc()),
353 CommentSortType::New => query.then_order_by(comment::published.desc()),
354 CommentSortType::Old => query.then_order_by(comment::published.asc()),
355 CommentSortType::Top => query.order_by(comment_aggregates::score.desc()),
358 // Note: deleted and removed comments are done on the front side
362 .load::<CommentViewTuple>(self.conn)?;
364 Ok(CommentView::from_tuple_to_vec(res))
368 impl ViewToVec for CommentView {
369 type DbTuple = CommentViewTuple;
370 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
379 creator_banned_from_community: a.5.is_some(),
380 subscribed: CommunityFollower::to_subscribed_type(&a.6),
381 saved: a.7.is_some(),
382 creator_blocked: a.8.is_some(),
385 .collect::<Vec<Self>>()
391 use crate::comment_view::*;
392 use lemmy_db_schema::{
393 aggregates::structs::CommentAggregates,
394 newtypes::LanguageId,
399 local_user::LocalUserForm,
400 local_user_language::LocalUserLanguage,
402 person_block::PersonBlockForm,
405 traits::{Blockable, Crud, Likeable},
406 utils::establish_unpooled_connection,
409 use serial_test::serial;
412 inserted_comment_0: Comment,
413 inserted_comment_1: Comment,
414 inserted_comment_2: Comment,
416 inserted_person: Person,
417 inserted_local_user: LocalUser,
418 inserted_person_2: Person,
419 inserted_community: Community,
422 fn init_data(conn: &mut PgConnection) -> Data {
423 let new_person = PersonForm {
424 name: "timmy".into(),
425 public_key: Some("pubkey".to_string()),
426 ..PersonForm::default()
428 let inserted_person = Person::create(conn, &new_person).unwrap();
429 let local_user_form = LocalUserForm {
430 person_id: Some(inserted_person.id),
431 password_encrypted: Some("".to_string()),
434 let inserted_local_user = LocalUser::create(conn, &local_user_form).unwrap();
436 let new_person_2 = PersonForm {
438 public_key: Some("pubkey".to_string()),
439 ..PersonForm::default()
441 let inserted_person_2 = Person::create(conn, &new_person_2).unwrap();
443 let new_community = CommunityForm {
444 name: "test community 5".to_string(),
445 title: "nada".to_owned(),
446 public_key: Some("pubkey".to_string()),
447 ..CommunityForm::default()
450 let inserted_community = Community::create(conn, &new_community).unwrap();
452 let new_post = PostForm {
453 name: "A test post 2".into(),
454 creator_id: inserted_person.id,
455 community_id: inserted_community.id,
456 ..PostForm::default()
459 let inserted_post = Post::create(conn, &new_post).unwrap();
461 // Create a comment tree with this hierarchy
469 let comment_form_0 = CommentForm {
470 content: "Comment 0".into(),
471 creator_id: inserted_person.id,
472 post_id: inserted_post.id,
473 ..CommentForm::default()
476 let inserted_comment_0 = Comment::create(conn, &comment_form_0, None).unwrap();
478 let comment_form_1 = CommentForm {
479 content: "Comment 1, A test blocked comment".into(),
480 creator_id: inserted_person_2.id,
481 post_id: inserted_post.id,
482 ..CommentForm::default()
485 let inserted_comment_1 =
486 Comment::create(conn, &comment_form_1, Some(&inserted_comment_0.path)).unwrap();
488 let finnish_id = Language::read_id_from_code(conn, "fi").unwrap();
489 let comment_form_2 = CommentForm {
490 content: "Comment 2".into(),
491 creator_id: inserted_person.id,
492 post_id: inserted_post.id,
493 language_id: Some(finnish_id),
494 ..CommentForm::default()
497 let inserted_comment_2 =
498 Comment::create(conn, &comment_form_2, Some(&inserted_comment_0.path)).unwrap();
500 let comment_form_3 = CommentForm {
501 content: "Comment 3".into(),
502 creator_id: inserted_person.id,
503 post_id: inserted_post.id,
504 ..CommentForm::default()
507 let _inserted_comment_3 =
508 Comment::create(conn, &comment_form_3, Some(&inserted_comment_1.path)).unwrap();
510 let polish_id = Language::read_id_from_code(conn, "pl").unwrap();
511 let comment_form_4 = CommentForm {
512 content: "Comment 4".into(),
513 creator_id: inserted_person.id,
514 post_id: inserted_post.id,
515 language_id: Some(polish_id),
516 ..CommentForm::default()
519 let inserted_comment_4 =
520 Comment::create(conn, &comment_form_4, Some(&inserted_comment_1.path)).unwrap();
522 let comment_form_5 = CommentForm {
523 content: "Comment 5".into(),
524 creator_id: inserted_person.id,
525 post_id: inserted_post.id,
526 ..CommentForm::default()
529 let _inserted_comment_5 =
530 Comment::create(conn, &comment_form_5, Some(&inserted_comment_4.path)).unwrap();
532 let timmy_blocks_sara_form = PersonBlockForm {
533 person_id: inserted_person.id,
534 target_id: inserted_person_2.id,
537 let inserted_block = PersonBlock::block(conn, &timmy_blocks_sara_form).unwrap();
539 let expected_block = PersonBlock {
540 id: inserted_block.id,
541 person_id: inserted_person.id,
542 target_id: inserted_person_2.id,
543 published: inserted_block.published,
545 assert_eq!(expected_block, inserted_block);
547 let comment_like_form = CommentLikeForm {
548 comment_id: inserted_comment_0.id,
549 post_id: inserted_post.id,
550 person_id: inserted_person.id,
554 let _inserted_comment_like = CommentLike::like(conn, &comment_like_form).unwrap();
571 let conn = &mut establish_unpooled_connection();
572 let data = init_data(conn);
574 let expected_comment_view_no_person = expected_comment_view(&data, conn);
576 let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
577 expected_comment_view_with_person.my_vote = Some(1);
579 let read_comment_views_no_person = CommentQuery::builder()
581 .post_id(Some(data.inserted_post.id))
587 expected_comment_view_no_person,
588 read_comment_views_no_person[0]
591 let read_comment_views_with_person = CommentQuery::builder()
593 .post_id(Some(data.inserted_post.id))
594 .local_user(Some(&data.inserted_local_user))
600 expected_comment_view_with_person,
601 read_comment_views_with_person[0]
604 // Make sure its 1, not showing the blocked comment
605 assert_eq!(5, read_comment_views_with_person.len());
607 let read_comment_from_blocked_person = CommentView::read(
609 data.inserted_comment_1.id,
610 Some(data.inserted_person.id),
614 // Make sure block set the creator blocked
615 assert!(read_comment_from_blocked_person.creator_blocked);
622 fn test_comment_tree() {
623 let conn = &mut establish_unpooled_connection();
624 let data = init_data(conn);
626 let top_path = data.inserted_comment_0.path.clone();
627 let read_comment_views_top_path = CommentQuery::builder()
629 .post_id(Some(data.inserted_post.id))
630 .parent_path(Some(top_path))
635 let child_path = data.inserted_comment_1.path.clone();
636 let read_comment_views_child_path = CommentQuery::builder()
638 .post_id(Some(data.inserted_post.id))
639 .parent_path(Some(child_path))
644 // Make sure the comment parent-limited fetch is correct
645 assert_eq!(6, read_comment_views_top_path.len());
646 assert_eq!(4, read_comment_views_child_path.len());
648 // Make sure it contains the parent, but not the comment from the other tree
649 let child_comments = read_comment_views_child_path
652 .collect::<Vec<Comment>>();
653 assert!(child_comments.contains(&data.inserted_comment_1));
654 assert!(!child_comments.contains(&data.inserted_comment_2));
656 let read_comment_views_top_max_depth = CommentQuery::builder()
658 .post_id(Some(data.inserted_post.id))
664 // Make sure a depth limited one only has the top comment
666 expected_comment_view(&data, conn),
667 read_comment_views_top_max_depth[0]
669 assert_eq!(1, read_comment_views_top_max_depth.len());
671 let child_path = data.inserted_comment_1.path.clone();
672 let read_comment_views_parent_max_depth = CommentQuery::builder()
674 .post_id(Some(data.inserted_post.id))
675 .parent_path(Some(child_path))
677 .sort(Some(CommentSortType::New))
682 // Make sure a depth limited one, and given child comment 1, has 3
683 assert!(read_comment_views_parent_max_depth[2]
687 assert_eq!(3, read_comment_views_parent_max_depth.len());
694 fn test_languages() {
695 let conn = &mut establish_unpooled_connection();
696 let data = init_data(conn);
698 // by default, user has all languages enabled and should see all comments
699 // (except from blocked user)
700 let all_languages = CommentQuery::builder()
702 .local_user(Some(&data.inserted_local_user))
706 assert_eq!(5, all_languages.len());
708 // change user lang to finnish, should only show single finnish comment
709 let finnish_id = Language::read_id_from_code(conn, "fi").unwrap();
710 LocalUserLanguage::update_user_languages(
712 Some(vec![finnish_id]),
713 data.inserted_local_user.id,
716 let finnish_comment = CommentQuery::builder()
718 .local_user(Some(&data.inserted_local_user))
722 assert_eq!(1, finnish_comment.len());
724 data.inserted_comment_2.content,
725 finnish_comment[0].comment.content
727 assert_eq!(finnish_id, finnish_comment[0].comment.language_id);
729 // now show all comments with undetermined language (which is the default value)
730 let undetermined_id = Language::read_id_from_code(conn, "und").unwrap();
731 LocalUserLanguage::update_user_languages(
733 Some(vec![undetermined_id]),
734 data.inserted_local_user.id,
737 let undetermined_comment = CommentQuery::builder()
739 .local_user(Some(&data.inserted_local_user))
743 assert_eq!(3, undetermined_comment.len());
748 fn cleanup(data: Data, conn: &mut PgConnection) {
749 CommentLike::remove(conn, data.inserted_person.id, data.inserted_comment_0.id).unwrap();
750 Comment::delete(conn, data.inserted_comment_0.id).unwrap();
751 Comment::delete(conn, data.inserted_comment_1.id).unwrap();
752 Post::delete(conn, data.inserted_post.id).unwrap();
753 Community::delete(conn, data.inserted_community.id).unwrap();
754 Person::delete(conn, data.inserted_person.id).unwrap();
755 Person::delete(conn, data.inserted_person_2.id).unwrap();
758 fn expected_comment_view(data: &Data, conn: &mut PgConnection) -> CommentView {
759 let agg = CommentAggregates::read(conn, data.inserted_comment_0.id).unwrap();
761 creator_banned_from_community: false,
763 subscribed: SubscribedType::NotSubscribed,
765 creator_blocked: false,
767 id: data.inserted_comment_0.id,
768 content: "Comment 0".into(),
769 creator_id: data.inserted_person.id,
770 post_id: data.inserted_post.id,
773 published: data.inserted_comment_0.published,
774 ap_id: data.inserted_comment_0.ap_id.clone(),
777 distinguished: false,
778 path: data.inserted_comment_0.to_owned().path,
779 language_id: LanguageId(0),
781 creator: PersonSafe {
782 id: data.inserted_person.id,
783 name: "timmy".into(),
785 published: data.inserted_person.published,
787 actor_id: data.inserted_person.actor_id.to_owned(),
796 inbox_url: data.inserted_person.inbox_url.to_owned(),
797 shared_inbox_url: None,
798 matrix_user_id: None,
802 id: data.inserted_post.id,
803 name: data.inserted_post.name.to_owned(),
804 creator_id: data.inserted_person.id,
807 published: data.inserted_post.published,
809 community_id: data.inserted_community.id,
816 embed_description: None,
817 embed_video_url: None,
819 ap_id: data.inserted_post.ap_id.to_owned(),
821 language_id: Default::default(),
823 community: CommunitySafe {
824 id: data.inserted_community.id,
825 name: "test community 5".to_string(),
830 actor_id: data.inserted_community.actor_id.to_owned(),
832 title: "nada".to_owned(),
837 posting_restricted_to_mods: false,
838 published: data.inserted_community.published,
840 counts: CommentAggregates {
842 comment_id: data.inserted_comment_0.id,
846 published: agg.published,