1 use crate::structs::{CommentView, LocalUserView};
7 NullableExpressionMethods,
8 PgTextExpressionMethods,
11 use diesel_async::RunQueryDsl;
12 use diesel_ltree::{nlevel, subpath, Ltree, LtreeExtensions};
13 use lemmy_db_schema::{
14 aggregates::structs::CommentAggregates,
15 newtypes::{CommentId, CommunityId, LocalUserId, PersonId, PostId},
31 comment::{Comment, CommentSaved},
32 community::{Community, CommunityFollower, CommunityPersonBan},
34 person_block::PersonBlock,
38 utils::{fuzzy_search, get_conn, limit_and_offset, DbPool},
43 type CommentViewTuple = (
49 Option<CommunityPersonBan>,
50 Option<CommunityFollower>,
58 pool: &mut DbPool<'_>,
59 comment_id: CommentId,
60 my_person_id: Option<PersonId>,
61 ) -> Result<Self, Error> {
62 let conn = &mut get_conn(pool).await?;
64 // The left join below will return None in this case
65 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
73 creator_banned_from_community,
80 .inner_join(person::table)
81 .inner_join(post::table)
82 .inner_join(community::table.on(post::community_id.eq(community::id)))
83 .inner_join(comment_aggregates::table)
85 community_person_ban::table.on(
87 .eq(community_person_ban::community_id)
88 .and(community_person_ban::person_id.eq(comment::creator_id)),
92 community_follower::table.on(
94 .eq(community_follower::community_id)
95 .and(community_follower::person_id.eq(person_id_join)),
99 comment_saved::table.on(
101 .eq(comment_saved::comment_id)
102 .and(comment_saved::person_id.eq(person_id_join)),
106 person_block::table.on(
108 .eq(person_block::target_id)
109 .and(person_block::person_id.eq(person_id_join)),
113 comment_like::table.on(
115 .eq(comment_like::comment_id)
116 .and(comment_like::person_id.eq(person_id_join)),
120 comment::all_columns,
123 community::all_columns,
124 comment_aggregates::all_columns,
125 community_person_ban::all_columns.nullable(),
126 community_follower::all_columns.nullable(),
127 comment_saved::all_columns.nullable(),
128 person_block::all_columns.nullable(),
129 comment_like::score.nullable(),
131 .first::<CommentViewTuple>(conn)
134 // If a person is given, then my_vote, if None, should be 0, not null
135 // Necessary to differentiate between other person's votes
136 let my_vote = if my_person_id.is_some() && comment_like.is_none() {
148 creator_banned_from_community: creator_banned_from_community.is_some(),
149 subscribed: CommunityFollower::to_subscribed_type(&follower),
150 saved: saved.is_some(),
151 creator_blocked: creator_blocked.is_some(),
158 pub struct CommentQuery<'a> {
159 pub listing_type: Option<ListingType>,
160 pub sort: Option<CommentSortType>,
161 pub community_id: Option<CommunityId>,
162 pub post_id: Option<PostId>,
163 pub parent_path: Option<Ltree>,
164 pub creator_id: Option<PersonId>,
165 pub local_user: Option<&'a LocalUserView>,
166 pub search_term: Option<String>,
167 pub saved_only: Option<bool>,
168 pub is_profile_view: Option<bool>,
169 pub show_deleted_and_removed: Option<bool>,
170 pub page: Option<i64>,
171 pub limit: Option<i64>,
172 pub max_depth: Option<i32>,
175 impl<'a> CommentQuery<'a> {
176 pub async fn list(self, pool: &mut DbPool<'_>) -> Result<Vec<CommentView>, Error> {
177 let conn = &mut get_conn(pool).await?;
179 // The left join below will return None in this case
180 let person_id_join = self.local_user.map(|l| l.person.id).unwrap_or(PersonId(-1));
181 let local_user_id_join = self
183 .map(|l| l.local_user.id)
184 .unwrap_or(LocalUserId(-1));
186 let mut query = comment::table
187 .inner_join(person::table)
188 .inner_join(post::table)
189 .inner_join(community::table.on(post::community_id.eq(community::id)))
190 .inner_join(comment_aggregates::table)
192 community_person_ban::table.on(
194 .eq(community_person_ban::community_id)
195 .and(community_person_ban::person_id.eq(comment::creator_id)),
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,
244 community::all_columns,
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(community_id) = self.community_id {
271 query = query.filter(post::community_id.eq(community_id));
274 if let Some(listing_type) = self.listing_type {
276 ListingType::Subscribed => {
277 query = query.filter(community_follower::person_id.is_not_null())
278 } // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
279 ListingType::Local => {
280 query = query.filter(community::local.eq(true)).filter(
283 .or(community_follower::person_id.eq(person_id_join)),
286 ListingType::All => {
287 query = query.filter(
290 .or(community_follower::person_id.eq(person_id_join)),
296 if self.saved_only.unwrap_or(false) {
297 query = query.filter(comment_saved::comment_id.is_not_null());
300 let is_profile_view = self.is_profile_view.unwrap_or(false);
301 let is_creator = self.creator_id == self.local_user.map(|l| l.person.id);
302 // only show deleted comments to creator
304 query = query.filter(comment::deleted.eq(false));
307 let is_admin = self.local_user.map(|l| l.person.admin).unwrap_or(false);
308 // only show removed comments to admin when viewing user profile
309 if !(is_profile_view && is_admin) {
310 query = query.filter(comment::removed.eq(false));
315 .map(|l| l.local_user.show_bot_accounts)
318 query = query.filter(person::bot_account.eq(false));
321 if self.local_user.is_some() {
322 // Filter out the rows with missing languages
323 query = query.filter(local_user_language::language_id.is_not_null());
325 // Don't show blocked communities or persons
326 if self.post_id.is_none() {
327 query = query.filter(community_block::person_id.is_null());
329 query = query.filter(person_block::person_id.is_null());
332 // A Max depth given means its a tree fetch
333 let (limit, offset) = if let Some(max_depth) = self.max_depth {
334 let depth_limit = if let Some(parent_path) = self.parent_path.as_ref() {
335 parent_path.0.split('.').count() as i32 + max_depth
336 // Add one because of root "0"
341 query = query.filter(nlevel(comment::path).le(depth_limit));
343 // only order if filtering by a post id. DOS potential otherwise and max_depth + !post_id isn't used anyways (afaik)
344 if self.post_id.is_some() {
345 // Always order by the parent path first
346 query = query.order_by(subpath(comment::path, 0, -1));
349 // TODO limit question. Limiting does not work for comment threads ATM, only max_depth
350 // For now, don't do any limiting for tree fetches
351 // https://stackoverflow.com/questions/72983614/postgres-ltree-how-to-limit-the-max-number-of-children-at-any-given-level
353 // Don't use the regular error-checking one, many more comments must ofter be fetched.
354 // This does not work for comment trees, and the limit should be manually set to a high number
356 // If a max depth is given, then you know its a tree fetch, and limits should be ignored
357 // TODO a kludge to prevent attacks. Limit comments to 300 for now.
361 // limit_and_offset_unlimited(self.page, self.limit)
362 limit_and_offset(self.page, self.limit)?
365 query = match self.sort.unwrap_or(CommentSortType::Hot) {
366 CommentSortType::Hot => query
367 .then_order_by(comment_aggregates::hot_rank.desc())
368 .then_order_by(comment_aggregates::score.desc()),
369 CommentSortType::New => query.then_order_by(comment::published.desc()),
370 CommentSortType::Old => query.then_order_by(comment::published.asc()),
371 CommentSortType::Top => query.order_by(comment_aggregates::score.desc()),
374 // Note: deleted and removed comments are done on the front side
378 .load::<CommentViewTuple>(conn)
381 Ok(res.into_iter().map(CommentView::from_tuple).collect())
385 impl JoinView for CommentView {
386 type JoinTuple = CommentViewTuple;
387 fn from_tuple(a: Self::JoinTuple) -> Self {
394 creator_banned_from_community: a.5.is_some(),
395 subscribed: CommunityFollower::to_subscribed_type(&a.6),
396 saved: a.7.is_some(),
397 creator_blocked: a.8.is_some(),
405 #![allow(clippy::unwrap_used)]
406 #![allow(clippy::indexing_slicing)]
420 structs::LocalUserView,
422 use lemmy_db_schema::{
423 aggregates::structs::CommentAggregates,
424 impls::actor_language::UNDETERMINED_ID,
425 newtypes::LanguageId,
427 actor_language::LocalUserLanguage,
428 comment::{CommentInsertForm, CommentLike, CommentLikeForm},
429 community::CommunityInsertForm,
432 local_user::{LocalUser, LocalUserInsertForm},
433 person::PersonInsertForm,
434 person_block::PersonBlockForm,
435 post::PostInsertForm,
437 traits::{Blockable, Crud, Likeable},
438 utils::build_db_pool_for_tests,
441 use serial_test::serial;
444 inserted_instance: Instance,
445 inserted_comment_0: Comment,
446 inserted_comment_1: Comment,
447 inserted_comment_2: Comment,
449 local_user_view: LocalUserView,
450 inserted_person_2: Person,
451 inserted_community: Community,
454 async fn init_data(pool: &mut DbPool<'_>) -> Data {
455 let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
459 let new_person = PersonInsertForm::builder()
460 .name("timmy".into())
461 .public_key("pubkey".to_string())
462 .instance_id(inserted_instance.id)
464 let inserted_person = Person::create(pool, &new_person).await.unwrap();
465 let local_user_form = LocalUserInsertForm::builder()
466 .person_id(inserted_person.id)
467 .password_encrypted(String::new())
469 let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
471 let new_person_2 = PersonInsertForm::builder()
473 .public_key("pubkey".to_string())
474 .instance_id(inserted_instance.id)
476 let inserted_person_2 = Person::create(pool, &new_person_2).await.unwrap();
478 let new_community = CommunityInsertForm::builder()
479 .name("test community 5".to_string())
480 .title("nada".to_owned())
481 .public_key("pubkey".to_string())
482 .instance_id(inserted_instance.id)
485 let inserted_community = Community::create(pool, &new_community).await.unwrap();
487 let new_post = PostInsertForm::builder()
488 .name("A test post 2".into())
489 .creator_id(inserted_person.id)
490 .community_id(inserted_community.id)
493 let inserted_post = Post::create(pool, &new_post).await.unwrap();
494 let english_id = Language::read_id_from_code(pool, Some("en")).await.unwrap();
496 // Create a comment tree with this hierarchy
504 let comment_form_0 = CommentInsertForm::builder()
505 .content("Comment 0".into())
506 .creator_id(inserted_person.id)
507 .post_id(inserted_post.id)
508 .language_id(english_id)
511 let inserted_comment_0 = Comment::create(pool, &comment_form_0, None).await.unwrap();
513 let comment_form_1 = CommentInsertForm::builder()
514 .content("Comment 1, A test blocked comment".into())
515 .creator_id(inserted_person_2.id)
516 .post_id(inserted_post.id)
517 .language_id(english_id)
520 let inserted_comment_1 = Comment::create(pool, &comment_form_1, Some(&inserted_comment_0.path))
524 let finnish_id = Language::read_id_from_code(pool, Some("fi")).await.unwrap();
525 let comment_form_2 = CommentInsertForm::builder()
526 .content("Comment 2".into())
527 .creator_id(inserted_person.id)
528 .post_id(inserted_post.id)
529 .language_id(finnish_id)
532 let inserted_comment_2 = Comment::create(pool, &comment_form_2, Some(&inserted_comment_0.path))
536 let comment_form_3 = CommentInsertForm::builder()
537 .content("Comment 3".into())
538 .creator_id(inserted_person.id)
539 .post_id(inserted_post.id)
540 .language_id(english_id)
543 let _inserted_comment_3 =
544 Comment::create(pool, &comment_form_3, Some(&inserted_comment_1.path))
548 let polish_id = Language::read_id_from_code(pool, Some("pl"))
552 let comment_form_4 = CommentInsertForm::builder()
553 .content("Comment 4".into())
554 .creator_id(inserted_person.id)
555 .post_id(inserted_post.id)
556 .language_id(Some(polish_id))
559 let inserted_comment_4 = Comment::create(pool, &comment_form_4, Some(&inserted_comment_1.path))
563 let comment_form_5 = CommentInsertForm::builder()
564 .content("Comment 5".into())
565 .creator_id(inserted_person.id)
566 .post_id(inserted_post.id)
569 let _inserted_comment_5 =
570 Comment::create(pool, &comment_form_5, Some(&inserted_comment_4.path))
574 let timmy_blocks_sara_form = PersonBlockForm {
575 person_id: inserted_person.id,
576 target_id: inserted_person_2.id,
579 let inserted_block = PersonBlock::block(pool, &timmy_blocks_sara_form)
583 let expected_block = PersonBlock {
584 id: inserted_block.id,
585 person_id: inserted_person.id,
586 target_id: inserted_person_2.id,
587 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(pool, &comment_like_form).await.unwrap();
600 let local_user_view = LocalUserView {
601 local_user: inserted_local_user.clone(),
602 person: inserted_person.clone(),
603 counts: Default::default(),
619 async fn test_crud() {
620 let pool = &build_db_pool_for_tests().await;
621 let pool = &mut pool.into();
622 let data = init_data(pool).await;
624 let expected_comment_view_no_person = expected_comment_view(&data, pool).await;
626 let mut expected_comment_view_with_person = expected_comment_view_no_person.clone();
627 expected_comment_view_with_person.my_vote = Some(1);
629 let read_comment_views_no_person = CommentQuery {
630 sort: (Some(CommentSortType::Old)),
631 post_id: (Some(data.inserted_post.id)),
639 expected_comment_view_no_person,
640 read_comment_views_no_person[0]
643 let read_comment_views_with_person = CommentQuery {
644 sort: (Some(CommentSortType::Old)),
645 post_id: (Some(data.inserted_post.id)),
646 local_user: (Some(&data.local_user_view)),
654 expected_comment_view_with_person,
655 read_comment_views_with_person[0]
658 // Make sure its 1, not showing the blocked comment
659 assert_eq!(5, read_comment_views_with_person.len());
661 let read_comment_from_blocked_person = CommentView::read(
663 data.inserted_comment_1.id,
664 Some(data.local_user_view.person.id),
669 // Make sure block set the creator blocked
670 assert!(read_comment_from_blocked_person.creator_blocked);
672 cleanup(data, pool).await;
677 async fn test_comment_tree() {
678 let pool = &build_db_pool_for_tests().await;
679 let pool = &mut pool.into();
680 let data = init_data(pool).await;
682 let top_path = data.inserted_comment_0.path.clone();
683 let read_comment_views_top_path = CommentQuery {
684 post_id: (Some(data.inserted_post.id)),
685 parent_path: (Some(top_path)),
692 let child_path = data.inserted_comment_1.path.clone();
693 let read_comment_views_child_path = CommentQuery {
694 post_id: (Some(data.inserted_post.id)),
695 parent_path: (Some(child_path)),
702 // Make sure the comment parent-limited fetch is correct
703 assert_eq!(6, read_comment_views_top_path.len());
704 assert_eq!(4, read_comment_views_child_path.len());
706 // Make sure it contains the parent, but not the comment from the other tree
707 let child_comments = read_comment_views_child_path
710 .collect::<Vec<Comment>>();
711 assert!(child_comments.contains(&data.inserted_comment_1));
712 assert!(!child_comments.contains(&data.inserted_comment_2));
714 let read_comment_views_top_max_depth = CommentQuery {
715 post_id: (Some(data.inserted_post.id)),
716 max_depth: (Some(1)),
723 // Make sure a depth limited one only has the top comment
725 expected_comment_view(&data, pool).await,
726 read_comment_views_top_max_depth[0]
728 assert_eq!(1, read_comment_views_top_max_depth.len());
730 let child_path = data.inserted_comment_1.path.clone();
731 let read_comment_views_parent_max_depth = CommentQuery {
732 post_id: (Some(data.inserted_post.id)),
733 parent_path: (Some(child_path)),
734 max_depth: (Some(1)),
735 sort: (Some(CommentSortType::New)),
742 // Make sure a depth limited one, and given child comment 1, has 3
743 assert!(read_comment_views_parent_max_depth[2]
747 assert_eq!(3, read_comment_views_parent_max_depth.len());
749 cleanup(data, pool).await;
754 async fn test_languages() {
755 let pool = &build_db_pool_for_tests().await;
756 let pool = &mut pool.into();
757 let data = init_data(pool).await;
759 // by default, user has all languages enabled and should see all comments
760 // (except from blocked user)
761 let all_languages = CommentQuery {
762 local_user: (Some(&data.local_user_view)),
768 assert_eq!(5, all_languages.len());
770 // change user lang to finnish, should only show one post in finnish and one undetermined
771 let finnish_id = Language::read_id_from_code(pool, Some("fi"))
775 LocalUserLanguage::update(pool, vec![finnish_id], data.local_user_view.local_user.id)
778 let finnish_comments = CommentQuery {
779 local_user: (Some(&data.local_user_view)),
785 assert_eq!(2, finnish_comments.len());
786 let finnish_comment = finnish_comments
788 .find(|c| c.comment.language_id == finnish_id);
789 assert!(finnish_comment.is_some());
791 data.inserted_comment_2.content,
792 finnish_comment.unwrap().comment.content
795 // now show all comments with undetermined language (which is the default value)
796 LocalUserLanguage::update(
798 vec![UNDETERMINED_ID],
799 data.local_user_view.local_user.id,
803 let undetermined_comment = CommentQuery {
804 local_user: (Some(&data.local_user_view)),
810 assert_eq!(1, undetermined_comment.len());
812 cleanup(data, pool).await;
815 async fn cleanup(data: Data, pool: &mut DbPool<'_>) {
818 data.local_user_view.person.id,
819 data.inserted_comment_0.id,
823 Comment::delete(pool, data.inserted_comment_0.id)
826 Comment::delete(pool, data.inserted_comment_1.id)
829 Post::delete(pool, data.inserted_post.id).await.unwrap();
830 Community::delete(pool, data.inserted_community.id)
833 Person::delete(pool, data.local_user_view.person.id)
836 Person::delete(pool, data.inserted_person_2.id)
839 Instance::delete(pool, data.inserted_instance.id)
844 async fn expected_comment_view(data: &Data, pool: &mut DbPool<'_>) -> CommentView {
845 let agg = CommentAggregates::read(pool, data.inserted_comment_0.id)
849 creator_banned_from_community: false,
851 subscribed: SubscribedType::NotSubscribed,
853 creator_blocked: false,
855 id: data.inserted_comment_0.id,
856 content: "Comment 0".into(),
857 creator_id: data.local_user_view.person.id,
858 post_id: data.inserted_post.id,
861 published: data.inserted_comment_0.published,
862 ap_id: data.inserted_comment_0.ap_id.clone(),
865 distinguished: false,
866 path: data.inserted_comment_0.clone().path,
867 language_id: LanguageId(37),
870 id: data.local_user_view.person.id,
871 name: "timmy".into(),
873 published: data.local_user_view.person.published,
875 actor_id: data.local_user_view.person.actor_id.clone(),
884 inbox_url: data.local_user_view.person.inbox_url.clone(),
885 shared_inbox_url: None,
886 matrix_user_id: None,
888 instance_id: data.inserted_instance.id,
889 private_key: data.local_user_view.person.private_key.clone(),
890 public_key: data.local_user_view.person.public_key.clone(),
891 last_refreshed_at: data.local_user_view.person.last_refreshed_at,
894 id: data.inserted_post.id,
895 name: data.inserted_post.name.clone(),
896 creator_id: data.local_user_view.person.id,
899 published: data.inserted_post.published,
901 community_id: data.inserted_community.id,
907 embed_description: None,
908 embed_video_url: None,
910 ap_id: data.inserted_post.ap_id.clone(),
912 language_id: Default::default(),
913 featured_community: false,
914 featured_local: false,
916 community: Community {
917 id: data.inserted_community.id,
918 name: "test community 5".to_string(),
923 actor_id: data.inserted_community.actor_id.clone(),
925 title: "nada".to_owned(),
930 posting_restricted_to_mods: false,
931 published: data.inserted_community.published,
932 instance_id: data.inserted_instance.id,
933 private_key: data.inserted_community.private_key.clone(),
934 public_key: data.inserted_community.public_key.clone(),
935 last_refreshed_at: data.inserted_community.last_refreshed_at,
936 followers_url: data.inserted_community.followers_url.clone(),
937 inbox_url: data.inserted_community.inbox_url.clone(),
938 shared_inbox_url: data.inserted_community.shared_inbox_url.clone(),
939 moderators_url: data.inserted_community.moderators_url.clone(),
940 featured_url: data.inserted_community.featured_url.clone(),
942 counts: CommentAggregates {
944 comment_id: data.inserted_comment_0.id,
948 published: agg.published,