1 use crate::structs::CommentView;
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},
33 local_user::LocalUser,
35 person_block::PersonBlock,
39 utils::{fuzzy_search, get_conn, limit_and_offset, DbPool},
44 type CommentViewTuple = (
50 Option<CommunityPersonBan>,
51 Option<CommunityFollower>,
59 pool: &mut DbPool<'_>,
60 comment_id: CommentId,
61 my_person_id: Option<PersonId>,
62 ) -> Result<Self, Error> {
63 let conn = &mut get_conn(pool).await?;
65 // The left join below will return None in this case
66 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
74 creator_banned_from_community,
81 .inner_join(person::table)
82 .inner_join(post::table)
83 .inner_join(community::table.on(post::community_id.eq(community::id)))
84 .inner_join(comment_aggregates::table)
86 community_person_ban::table.on(
88 .eq(community_person_ban::community_id)
89 .and(community_person_ban::person_id.eq(comment::creator_id)),
93 community_follower::table.on(
95 .eq(community_follower::community_id)
96 .and(community_follower::person_id.eq(person_id_join)),
100 comment_saved::table.on(
102 .eq(comment_saved::comment_id)
103 .and(comment_saved::person_id.eq(person_id_join)),
107 person_block::table.on(
109 .eq(person_block::target_id)
110 .and(person_block::person_id.eq(person_id_join)),
114 comment_like::table.on(
116 .eq(comment_like::comment_id)
117 .and(comment_like::person_id.eq(person_id_join)),
121 comment::all_columns,
124 community::all_columns,
125 comment_aggregates::all_columns,
126 community_person_ban::all_columns.nullable(),
127 community_follower::all_columns.nullable(),
128 comment_saved::all_columns.nullable(),
129 person_block::all_columns.nullable(),
130 comment_like::score.nullable(),
132 .first::<CommentViewTuple>(conn)
135 // If a person is given, then my_vote, if None, should be 0, not null
136 // Necessary to differentiate between other person's votes
137 let my_vote = if my_person_id.is_some() && comment_like.is_none() {
149 creator_banned_from_community: creator_banned_from_community.is_some(),
150 subscribed: CommunityFollower::to_subscribed_type(&follower),
151 saved: saved.is_some(),
152 creator_blocked: creator_blocked.is_some(),
159 pub struct CommentQuery<'a> {
160 pub listing_type: Option<ListingType>,
161 pub sort: Option<CommentSortType>,
162 pub community_id: Option<CommunityId>,
163 pub post_id: Option<PostId>,
164 pub parent_path: Option<Ltree>,
165 pub creator_id: Option<PersonId>,
166 pub local_user: Option<&'a LocalUser>,
167 pub search_term: Option<String>,
168 pub saved_only: 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.local_user.map(|l| l.id).unwrap_or(LocalUserId(-1));
183 let mut query = comment::table
184 .inner_join(person::table)
185 .inner_join(post::table)
186 .inner_join(community::table.on(post::community_id.eq(community::id)))
187 .inner_join(comment_aggregates::table)
189 community_person_ban::table.on(
191 .eq(community_person_ban::community_id)
192 .and(community_person_ban::person_id.eq(comment::creator_id)),
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 local_user_language::table.on(
233 .eq(local_user_language::language_id)
234 .and(local_user_language::local_user_id.eq(local_user_id_join)),
238 comment::all_columns,
241 community::all_columns,
242 comment_aggregates::all_columns,
243 community_person_ban::all_columns.nullable(),
244 community_follower::all_columns.nullable(),
245 comment_saved::all_columns.nullable(),
246 person_block::all_columns.nullable(),
247 comment_like::score.nullable(),
251 if let Some(creator_id) = self.creator_id {
252 query = query.filter(comment::creator_id.eq(creator_id));
255 if let Some(post_id) = self.post_id {
256 query = query.filter(comment::post_id.eq(post_id));
259 if let Some(parent_path) = self.parent_path.as_ref() {
260 query = query.filter(comment::path.contained_by(parent_path));
263 if let Some(search_term) = self.search_term {
264 query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
267 if let Some(community_id) = self.community_id {
268 query = query.filter(post::community_id.eq(community_id));
271 if let Some(listing_type) = self.listing_type {
273 ListingType::Subscribed => {
274 query = query.filter(community_follower::person_id.is_not_null())
275 } // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
276 ListingType::Local => {
277 query = query.filter(community::local.eq(true)).filter(
280 .or(community_follower::person_id.eq(person_id_join)),
283 ListingType::All => {
284 query = query.filter(
287 .or(community_follower::person_id.eq(person_id_join)),
293 if self.saved_only.unwrap_or(false) {
294 query = query.filter(comment_saved::comment_id.is_not_null());
297 if !self.show_deleted_and_removed.unwrap_or(true) {
298 query = query.filter(comment::deleted.eq(false));
299 query = query.filter(comment::removed.eq(false));
302 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
303 query = query.filter(person::bot_account.eq(false));
306 if self.local_user.is_some() {
307 // Filter out the rows with missing languages
308 query = query.filter(local_user_language::language_id.is_not_null());
310 // Don't show blocked communities or persons
311 if self.post_id.is_none() {
312 query = query.filter(community_block::person_id.is_null());
314 query = query.filter(person_block::person_id.is_null());
317 // A Max depth given means its a tree fetch
318 let (limit, offset) = if let Some(max_depth) = self.max_depth {
319 let depth_limit = if let Some(parent_path) = self.parent_path.as_ref() {
320 parent_path.0.split('.').count() as i32 + max_depth
321 // Add one because of root "0"
326 query = query.filter(nlevel(comment::path).le(depth_limit));
328 // Always order by the parent path first
329 query = query.order_by(subpath(comment::path, 0, -1));
331 // TODO limit question. Limiting does not work for comment threads ATM, only max_depth
332 // For now, don't do any limiting for tree fetches
333 // https://stackoverflow.com/questions/72983614/postgres-ltree-how-to-limit-the-max-number-of-children-at-any-given-level
335 // Don't use the regular error-checking one, many more comments must ofter be fetched.
336 // This does not work for comment trees, and the limit should be manually set to a high number
338 // If a max depth is given, then you know its a tree fetch, and limits should be ignored
339 // TODO a kludge to prevent attacks. Limit comments to 300 for now.
343 // limit_and_offset_unlimited(self.page, self.limit)
344 limit_and_offset(self.page, self.limit)?
347 query = match self.sort.unwrap_or(CommentSortType::Hot) {
348 CommentSortType::Hot => query.then_order_by(comment_aggregates::hot_rank.desc()),
349 CommentSortType::New => query.then_order_by(comment::published.desc()),
350 CommentSortType::Old => query.then_order_by(comment::published.asc()),
351 CommentSortType::Top => query.order_by(comment_aggregates::score.desc()),
354 // Note: deleted and removed comments are done on the front side
358 .load::<CommentViewTuple>(conn)
361 Ok(res.into_iter().map(CommentView::from_tuple).collect())
365 impl JoinView for CommentView {
366 type JoinTuple = CommentViewTuple;
367 fn from_tuple(a: Self::JoinTuple) -> Self {
374 creator_banned_from_community: a.5.is_some(),
375 subscribed: CommunityFollower::to_subscribed_type(&a.6),
376 saved: a.7.is_some(),
377 creator_blocked: a.8.is_some(),
385 use crate::comment_view::{
397 use lemmy_db_schema::{
398 aggregates::structs::CommentAggregates,
399 impls::actor_language::UNDETERMINED_ID,
400 newtypes::LanguageId,
402 actor_language::LocalUserLanguage,
403 comment::{CommentInsertForm, CommentLike, CommentLikeForm},
404 community::CommunityInsertForm,
407 local_user::LocalUserInsertForm,
408 person::PersonInsertForm,
409 person_block::PersonBlockForm,
410 post::PostInsertForm,
412 traits::{Blockable, Crud, Likeable},
413 utils::build_db_pool_for_tests,
416 use serial_test::serial;
419 inserted_instance: Instance,
420 inserted_comment_0: Comment,
421 inserted_comment_1: Comment,
422 inserted_comment_2: Comment,
424 inserted_person: Person,
425 inserted_local_user: LocalUser,
426 inserted_person_2: Person,
427 inserted_community: Community,
430 async fn init_data(pool: &mut DbPool<'_>) -> Data {
431 let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
435 let new_person = PersonInsertForm::builder()
436 .name("timmy".into())
437 .public_key("pubkey".to_string())
438 .instance_id(inserted_instance.id)
440 let inserted_person = Person::create(pool, &new_person).await.unwrap();
441 let local_user_form = LocalUserInsertForm::builder()
442 .person_id(inserted_person.id)
443 .password_encrypted(String::new())
445 let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
447 let new_person_2 = PersonInsertForm::builder()
449 .public_key("pubkey".to_string())
450 .instance_id(inserted_instance.id)
452 let inserted_person_2 = Person::create(pool, &new_person_2).await.unwrap();
454 let new_community = CommunityInsertForm::builder()
455 .name("test community 5".to_string())
456 .title("nada".to_owned())
457 .public_key("pubkey".to_string())
458 .instance_id(inserted_instance.id)
461 let inserted_community = Community::create(pool, &new_community).await.unwrap();
463 let new_post = PostInsertForm::builder()
464 .name("A test post 2".into())
465 .creator_id(inserted_person.id)
466 .community_id(inserted_community.id)
469 let inserted_post = Post::create(pool, &new_post).await.unwrap();
470 let english_id = Language::read_id_from_code(pool, Some("en")).await.unwrap();
472 // Create a comment tree with this hierarchy
480 let comment_form_0 = CommentInsertForm::builder()
481 .content("Comment 0".into())
482 .creator_id(inserted_person.id)
483 .post_id(inserted_post.id)
484 .language_id(english_id)
487 let inserted_comment_0 = Comment::create(pool, &comment_form_0, None).await.unwrap();
489 let comment_form_1 = CommentInsertForm::builder()
490 .content("Comment 1, A test blocked comment".into())
491 .creator_id(inserted_person_2.id)
492 .post_id(inserted_post.id)
493 .language_id(english_id)
496 let inserted_comment_1 = Comment::create(pool, &comment_form_1, Some(&inserted_comment_0.path))
500 let finnish_id = Language::read_id_from_code(pool, Some("fi")).await.unwrap();
501 let comment_form_2 = CommentInsertForm::builder()
502 .content("Comment 2".into())
503 .creator_id(inserted_person.id)
504 .post_id(inserted_post.id)
505 .language_id(finnish_id)
508 let inserted_comment_2 = Comment::create(pool, &comment_form_2, Some(&inserted_comment_0.path))
512 let comment_form_3 = CommentInsertForm::builder()
513 .content("Comment 3".into())
514 .creator_id(inserted_person.id)
515 .post_id(inserted_post.id)
516 .language_id(english_id)
519 let _inserted_comment_3 =
520 Comment::create(pool, &comment_form_3, Some(&inserted_comment_1.path))
524 let polish_id = Language::read_id_from_code(pool, Some("pl"))
528 let comment_form_4 = CommentInsertForm::builder()
529 .content("Comment 4".into())
530 .creator_id(inserted_person.id)
531 .post_id(inserted_post.id)
532 .language_id(Some(polish_id))
535 let inserted_comment_4 = Comment::create(pool, &comment_form_4, Some(&inserted_comment_1.path))
539 let comment_form_5 = CommentInsertForm::builder()
540 .content("Comment 5".into())
541 .creator_id(inserted_person.id)
542 .post_id(inserted_post.id)
545 let _inserted_comment_5 =
546 Comment::create(pool, &comment_form_5, Some(&inserted_comment_4.path))
550 let timmy_blocks_sara_form = PersonBlockForm {
551 person_id: inserted_person.id,
552 target_id: inserted_person_2.id,
555 let inserted_block = PersonBlock::block(pool, &timmy_blocks_sara_form)
559 let expected_block = PersonBlock {
560 id: inserted_block.id,
561 person_id: inserted_person.id,
562 target_id: inserted_person_2.id,
563 published: inserted_block.published,
565 assert_eq!(expected_block, inserted_block);
567 let comment_like_form = CommentLikeForm {
568 comment_id: inserted_comment_0.id,
569 post_id: inserted_post.id,
570 person_id: inserted_person.id,
574 let _inserted_comment_like = CommentLike::like(pool, &comment_like_form).await.unwrap();
591 async fn test_crud() {
592 let pool = &build_db_pool_for_tests().await;
593 let pool = &mut pool.into();
594 let data = init_data(pool).await;
596 let expected_comment_view_no_person = expected_comment_view(&data, pool).await;
598 let mut expected_comment_view_with_person = expected_comment_view_no_person.clone();
599 expected_comment_view_with_person.my_vote = Some(1);
601 let read_comment_views_no_person = CommentQuery {
602 sort: (Some(CommentSortType::Old)),
603 post_id: (Some(data.inserted_post.id)),
611 expected_comment_view_no_person,
612 read_comment_views_no_person[0]
615 let read_comment_views_with_person = CommentQuery {
616 sort: (Some(CommentSortType::Old)),
617 post_id: (Some(data.inserted_post.id)),
618 local_user: (Some(&data.inserted_local_user)),
626 expected_comment_view_with_person,
627 read_comment_views_with_person[0]
630 // Make sure its 1, not showing the blocked comment
631 assert_eq!(5, read_comment_views_with_person.len());
633 let read_comment_from_blocked_person = CommentView::read(
635 data.inserted_comment_1.id,
636 Some(data.inserted_person.id),
641 // Make sure block set the creator blocked
642 assert!(read_comment_from_blocked_person.creator_blocked);
644 cleanup(data, pool).await;
649 async fn test_comment_tree() {
650 let pool = &build_db_pool_for_tests().await;
651 let pool = &mut pool.into();
652 let data = init_data(pool).await;
654 let top_path = data.inserted_comment_0.path.clone();
655 let read_comment_views_top_path = CommentQuery {
656 post_id: (Some(data.inserted_post.id)),
657 parent_path: (Some(top_path)),
664 let child_path = data.inserted_comment_1.path.clone();
665 let read_comment_views_child_path = CommentQuery {
666 post_id: (Some(data.inserted_post.id)),
667 parent_path: (Some(child_path)),
674 // Make sure the comment parent-limited fetch is correct
675 assert_eq!(6, read_comment_views_top_path.len());
676 assert_eq!(4, read_comment_views_child_path.len());
678 // Make sure it contains the parent, but not the comment from the other tree
679 let child_comments = read_comment_views_child_path
682 .collect::<Vec<Comment>>();
683 assert!(child_comments.contains(&data.inserted_comment_1));
684 assert!(!child_comments.contains(&data.inserted_comment_2));
686 let read_comment_views_top_max_depth = CommentQuery {
687 post_id: (Some(data.inserted_post.id)),
688 max_depth: (Some(1)),
695 // Make sure a depth limited one only has the top comment
697 expected_comment_view(&data, pool).await,
698 read_comment_views_top_max_depth[0]
700 assert_eq!(1, read_comment_views_top_max_depth.len());
702 let child_path = data.inserted_comment_1.path.clone();
703 let read_comment_views_parent_max_depth = CommentQuery {
704 post_id: (Some(data.inserted_post.id)),
705 parent_path: (Some(child_path)),
706 max_depth: (Some(1)),
707 sort: (Some(CommentSortType::New)),
714 // Make sure a depth limited one, and given child comment 1, has 3
715 assert!(read_comment_views_parent_max_depth[2]
719 assert_eq!(3, read_comment_views_parent_max_depth.len());
721 cleanup(data, pool).await;
726 async fn test_languages() {
727 let pool = &build_db_pool_for_tests().await;
728 let pool = &mut pool.into();
729 let data = init_data(pool).await;
731 // by default, user has all languages enabled and should see all comments
732 // (except from blocked user)
733 let all_languages = CommentQuery {
734 local_user: (Some(&data.inserted_local_user)),
740 assert_eq!(5, all_languages.len());
742 // change user lang to finnish, should only show one post in finnish and one undetermined
743 let finnish_id = Language::read_id_from_code(pool, Some("fi"))
747 LocalUserLanguage::update(pool, vec![finnish_id], data.inserted_local_user.id)
750 let finnish_comments = CommentQuery {
751 local_user: (Some(&data.inserted_local_user)),
757 assert_eq!(2, finnish_comments.len());
758 let finnish_comment = finnish_comments
760 .find(|c| c.comment.language_id == finnish_id);
761 assert!(finnish_comment.is_some());
763 data.inserted_comment_2.content,
764 finnish_comment.unwrap().comment.content
767 // now show all comments with undetermined language (which is the default value)
768 LocalUserLanguage::update(pool, vec![UNDETERMINED_ID], data.inserted_local_user.id)
771 let undetermined_comment = CommentQuery {
772 local_user: (Some(&data.inserted_local_user)),
778 assert_eq!(1, undetermined_comment.len());
780 cleanup(data, pool).await;
783 async fn cleanup(data: Data, pool: &mut DbPool<'_>) {
784 CommentLike::remove(pool, data.inserted_person.id, data.inserted_comment_0.id)
787 Comment::delete(pool, data.inserted_comment_0.id)
790 Comment::delete(pool, data.inserted_comment_1.id)
793 Post::delete(pool, data.inserted_post.id).await.unwrap();
794 Community::delete(pool, data.inserted_community.id)
797 Person::delete(pool, data.inserted_person.id).await.unwrap();
798 Person::delete(pool, data.inserted_person_2.id)
801 Instance::delete(pool, data.inserted_instance.id)
806 async fn expected_comment_view(data: &Data, pool: &mut DbPool<'_>) -> CommentView {
807 let agg = CommentAggregates::read(pool, data.inserted_comment_0.id)
811 creator_banned_from_community: false,
813 subscribed: SubscribedType::NotSubscribed,
815 creator_blocked: false,
817 id: data.inserted_comment_0.id,
818 content: "Comment 0".into(),
819 creator_id: data.inserted_person.id,
820 post_id: data.inserted_post.id,
823 published: data.inserted_comment_0.published,
824 ap_id: data.inserted_comment_0.ap_id.clone(),
827 distinguished: false,
828 path: data.inserted_comment_0.clone().path,
829 language_id: LanguageId(37),
832 id: data.inserted_person.id,
833 name: "timmy".into(),
835 published: data.inserted_person.published,
837 actor_id: data.inserted_person.actor_id.clone(),
846 inbox_url: data.inserted_person.inbox_url.clone(),
847 shared_inbox_url: None,
848 matrix_user_id: None,
850 instance_id: data.inserted_instance.id,
851 private_key: data.inserted_person.private_key.clone(),
852 public_key: data.inserted_person.public_key.clone(),
853 last_refreshed_at: data.inserted_person.last_refreshed_at,
856 id: data.inserted_post.id,
857 name: data.inserted_post.name.clone(),
858 creator_id: data.inserted_person.id,
861 published: data.inserted_post.published,
863 community_id: data.inserted_community.id,
869 embed_description: None,
870 embed_video_url: None,
872 ap_id: data.inserted_post.ap_id.clone(),
874 language_id: Default::default(),
875 featured_community: false,
876 featured_local: false,
878 community: Community {
879 id: data.inserted_community.id,
880 name: "test community 5".to_string(),
885 actor_id: data.inserted_community.actor_id.clone(),
887 title: "nada".to_owned(),
892 posting_restricted_to_mods: false,
893 published: data.inserted_community.published,
894 instance_id: data.inserted_instance.id,
895 private_key: data.inserted_community.private_key.clone(),
896 public_key: data.inserted_community.public_key.clone(),
897 last_refreshed_at: data.inserted_community.last_refreshed_at,
898 followers_url: data.inserted_community.followers_url.clone(),
899 inbox_url: data.inserted_community.inbox_url.clone(),
900 shared_inbox_url: data.inserted_community.shared_inbox_url.clone(),
901 moderators_url: data.inserted_community.moderators_url.clone(),
902 featured_url: data.inserted_community.featured_url.clone(),
904 counts: CommentAggregates {
906 comment_id: data.inserted_comment_0.id,
910 published: agg.published,