1 use crate::structs::CommentView;
8 NullableExpressionMethods,
9 PgTextExpressionMethods,
12 use diesel_async::RunQueryDsl;
13 use diesel_ltree::{nlevel, subpath, Ltree, LtreeExtensions};
14 use lemmy_db_schema::{
15 aggregates::structs::CommentAggregates,
16 newtypes::{CommentId, CommunityId, DbUrl, LocalUserId, PersonId, PostId},
32 comment::{Comment, CommentSaved},
33 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
34 local_user::LocalUser,
35 person::{Person, PersonSafe},
36 person_block::PersonBlock,
39 traits::{ToSafe, ViewToVec},
40 utils::{functions::hot_rank, fuzzy_search, get_conn, limit_and_offset_unlimited, DbPool},
44 use typed_builder::TypedBuilder;
46 type CommentViewTuple = (
52 Option<CommunityPersonBan>,
53 Option<CommunityFollower>,
62 comment_id: CommentId,
63 my_person_id: Option<PersonId>,
64 ) -> Result<Self, Error> {
65 let conn = &mut get_conn(pool).await?;
67 // The left join below will return None in this case
68 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
76 creator_banned_from_community,
83 .inner_join(person::table)
84 .inner_join(post::table)
85 .inner_join(community::table.on(post::community_id.eq(community::id)))
86 .inner_join(comment_aggregates::table)
88 community_person_ban::table.on(
90 .eq(community_person_ban::community_id)
91 .and(community_person_ban::person_id.eq(comment::creator_id))
93 community_person_ban::expires
95 .or(community_person_ban::expires.gt(now)),
100 community_follower::table.on(
102 .eq(community_follower::community_id)
103 .and(community_follower::person_id.eq(person_id_join)),
107 comment_saved::table.on(
109 .eq(comment_saved::comment_id)
110 .and(comment_saved::person_id.eq(person_id_join)),
114 person_block::table.on(
116 .eq(person_block::target_id)
117 .and(person_block::person_id.eq(person_id_join)),
121 comment_like::table.on(
123 .eq(comment_like::comment_id)
124 .and(comment_like::person_id.eq(person_id_join)),
128 comment::all_columns,
129 Person::safe_columns_tuple(),
131 Community::safe_columns_tuple(),
132 comment_aggregates::all_columns,
133 community_person_ban::all_columns.nullable(),
134 community_follower::all_columns.nullable(),
135 comment_saved::all_columns.nullable(),
136 person_block::all_columns.nullable(),
137 comment_like::score.nullable(),
139 .first::<CommentViewTuple>(conn)
142 // If a person is given, then my_vote, if None, should be 0, not null
143 // Necessary to differentiate between other person's votes
144 let my_vote = if my_person_id.is_some() && comment_like.is_none() {
156 creator_banned_from_community: creator_banned_from_community.is_some(),
157 subscribed: CommunityFollower::to_subscribed_type(&follower),
158 saved: saved.is_some(),
159 creator_blocked: creator_blocked.is_some(),
165 #[derive(TypedBuilder)]
166 #[builder(field_defaults(default))]
167 pub struct CommentQuery<'a> {
170 listing_type: Option<ListingType>,
171 sort: Option<CommentSortType>,
172 community_id: Option<CommunityId>,
173 community_actor_id: Option<DbUrl>,
174 post_id: Option<PostId>,
175 parent_path: Option<Ltree>,
176 creator_id: Option<PersonId>,
177 local_user: Option<&'a LocalUser>,
178 search_term: Option<String>,
179 saved_only: Option<bool>,
180 show_deleted_and_removed: Option<bool>,
183 max_depth: Option<i32>,
186 impl<'a> CommentQuery<'a> {
187 pub async fn list(self) -> Result<Vec<CommentView>, Error> {
188 let conn = &mut get_conn(self.pool).await?;
190 // The left join below will return None in this case
191 let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1));
192 let local_user_id_join = self.local_user.map(|l| l.id).unwrap_or(LocalUserId(-1));
194 let mut query = comment::table
195 .inner_join(person::table)
196 .inner_join(post::table)
197 .inner_join(community::table.on(post::community_id.eq(community::id)))
198 .inner_join(comment_aggregates::table)
200 community_person_ban::table.on(
202 .eq(community_person_ban::community_id)
203 .and(community_person_ban::person_id.eq(comment::creator_id))
205 community_person_ban::expires
207 .or(community_person_ban::expires.gt(now)),
212 community_follower::table.on(
214 .eq(community_follower::community_id)
215 .and(community_follower::person_id.eq(person_id_join)),
219 comment_saved::table.on(
221 .eq(comment_saved::comment_id)
222 .and(comment_saved::person_id.eq(person_id_join)),
226 person_block::table.on(
228 .eq(person_block::target_id)
229 .and(person_block::person_id.eq(person_id_join)),
233 community_block::table.on(
235 .eq(community_block::community_id)
236 .and(community_block::person_id.eq(person_id_join)),
240 comment_like::table.on(
242 .eq(comment_like::comment_id)
243 .and(comment_like::person_id.eq(person_id_join)),
247 local_user_language::table.on(
249 .eq(local_user_language::language_id)
250 .and(local_user_language::local_user_id.eq(local_user_id_join)),
254 comment::all_columns,
255 Person::safe_columns_tuple(),
257 Community::safe_columns_tuple(),
258 comment_aggregates::all_columns,
259 community_person_ban::all_columns.nullable(),
260 community_follower::all_columns.nullable(),
261 comment_saved::all_columns.nullable(),
262 person_block::all_columns.nullable(),
263 comment_like::score.nullable(),
267 if let Some(creator_id) = self.creator_id {
268 query = query.filter(comment::creator_id.eq(creator_id));
271 if let Some(post_id) = self.post_id {
272 query = query.filter(comment::post_id.eq(post_id));
275 if let Some(parent_path) = self.parent_path.as_ref() {
276 query = query.filter(comment::path.contained_by(parent_path));
279 if let Some(search_term) = self.search_term {
280 query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
283 if let Some(listing_type) = self.listing_type {
285 ListingType::Subscribed => {
286 query = query.filter(community_follower::person_id.is_not_null())
287 } // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
288 ListingType::Local => {
289 query = query.filter(community::local.eq(true)).filter(
292 .or(community_follower::person_id.eq(person_id_join)),
295 ListingType::All => {
296 query = query.filter(
299 .or(community_follower::person_id.eq(person_id_join)),
305 if let Some(community_id) = self.community_id {
306 query = query.filter(post::community_id.eq(community_id));
309 if let Some(community_actor_id) = self.community_actor_id {
310 query = query.filter(community::actor_id.eq(community_actor_id))
313 if self.saved_only.unwrap_or(false) {
314 query = query.filter(comment_saved::id.is_not_null());
317 if !self.show_deleted_and_removed.unwrap_or(true) {
318 query = query.filter(comment::deleted.eq(false));
319 query = query.filter(comment::removed.eq(false));
322 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
323 query = query.filter(person::bot_account.eq(false));
326 if self.local_user.is_some() {
327 // Filter out the rows with missing languages
328 query = query.filter(local_user_language::id.is_not_null());
330 // Don't show blocked communities or persons
331 query = query.filter(community_block::person_id.is_null());
332 query = query.filter(person_block::person_id.is_null());
335 // A Max depth given means its a tree fetch
336 let (limit, offset) = if let Some(max_depth) = self.max_depth {
337 let depth_limit = if let Some(parent_path) = self.parent_path.as_ref() {
338 parent_path.0.split('.').count() as i32 + max_depth
339 // Add one because of root "0"
344 query = query.filter(nlevel(comment::path).le(depth_limit));
346 // Always order by the parent path first
347 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
359 limit_and_offset_unlimited(self.page, self.limit)
362 query = match self.sort.unwrap_or(CommentSortType::Hot) {
363 CommentSortType::Hot => query
364 .then_order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
365 .then_order_by(comment_aggregates::published.desc()),
366 CommentSortType::New => query.then_order_by(comment::published.desc()),
367 CommentSortType::Old => query.then_order_by(comment::published.asc()),
368 CommentSortType::Top => query.order_by(comment_aggregates::score.desc()),
371 // Note: deleted and removed comments are done on the front side
375 .load::<CommentViewTuple>(conn)
378 Ok(CommentView::from_tuple_to_vec(res))
382 impl ViewToVec for CommentView {
383 type DbTuple = CommentViewTuple;
384 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
393 creator_banned_from_community: a.5.is_some(),
394 subscribed: CommunityFollower::to_subscribed_type(&a.6),
395 saved: a.7.is_some(),
396 creator_blocked: a.8.is_some(),
399 .collect::<Vec<Self>>()
405 use crate::comment_view::{
419 use lemmy_db_schema::{
420 aggregates::structs::CommentAggregates,
421 newtypes::LanguageId,
423 actor_language::LocalUserLanguage,
424 comment::{CommentInsertForm, CommentLike, CommentLikeForm},
425 community::CommunityInsertForm,
428 local_user::LocalUserInsertForm,
429 person::PersonInsertForm,
430 person_block::PersonBlockForm,
431 post::PostInsertForm,
433 traits::{Blockable, Crud, Likeable},
434 utils::build_db_pool_for_tests,
437 use serial_test::serial;
440 inserted_instance: Instance,
441 inserted_comment_0: Comment,
442 inserted_comment_1: Comment,
443 inserted_comment_2: Comment,
445 inserted_person: Person,
446 inserted_local_user: LocalUser,
447 inserted_person_2: Person,
448 inserted_community: Community,
451 async fn init_data(pool: &DbPool) -> Data {
452 let inserted_instance = Instance::create(pool, "my_domain.tld").await.unwrap();
454 let new_person = PersonInsertForm::builder()
455 .name("timmy".into())
456 .public_key("pubkey".to_string())
457 .instance_id(inserted_instance.id)
459 let inserted_person = Person::create(pool, &new_person).await.unwrap();
460 let local_user_form = LocalUserInsertForm::builder()
461 .person_id(inserted_person.id)
462 .password_encrypted(String::new())
464 let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
466 let new_person_2 = PersonInsertForm::builder()
468 .public_key("pubkey".to_string())
469 .instance_id(inserted_instance.id)
471 let inserted_person_2 = Person::create(pool, &new_person_2).await.unwrap();
473 let new_community = CommunityInsertForm::builder()
474 .name("test community 5".to_string())
475 .title("nada".to_owned())
476 .public_key("pubkey".to_string())
477 .instance_id(inserted_instance.id)
480 let inserted_community = Community::create(pool, &new_community).await.unwrap();
482 let new_post = PostInsertForm::builder()
483 .name("A test post 2".into())
484 .creator_id(inserted_person.id)
485 .community_id(inserted_community.id)
488 let inserted_post = Post::create(pool, &new_post).await.unwrap();
490 // Create a comment tree with this hierarchy
498 let comment_form_0 = CommentInsertForm::builder()
499 .content("Comment 0".into())
500 .creator_id(inserted_person.id)
501 .post_id(inserted_post.id)
504 let inserted_comment_0 = Comment::create(pool, &comment_form_0, None).await.unwrap();
506 let comment_form_1 = CommentInsertForm::builder()
507 .content("Comment 1, A test blocked comment".into())
508 .creator_id(inserted_person_2.id)
509 .post_id(inserted_post.id)
512 let inserted_comment_1 = Comment::create(pool, &comment_form_1, Some(&inserted_comment_0.path))
516 let finnish_id = Language::read_id_from_code(pool, "fi").await.unwrap();
517 let comment_form_2 = CommentInsertForm::builder()
518 .content("Comment 2".into())
519 .creator_id(inserted_person.id)
520 .post_id(inserted_post.id)
521 .language_id(Some(finnish_id))
524 let inserted_comment_2 = Comment::create(pool, &comment_form_2, Some(&inserted_comment_0.path))
528 let comment_form_3 = CommentInsertForm::builder()
529 .content("Comment 3".into())
530 .creator_id(inserted_person.id)
531 .post_id(inserted_post.id)
534 let _inserted_comment_3 =
535 Comment::create(pool, &comment_form_3, Some(&inserted_comment_1.path))
539 let polish_id = Language::read_id_from_code(pool, "pl").await.unwrap();
540 let comment_form_4 = CommentInsertForm::builder()
541 .content("Comment 4".into())
542 .creator_id(inserted_person.id)
543 .post_id(inserted_post.id)
544 .language_id(Some(polish_id))
547 let inserted_comment_4 = Comment::create(pool, &comment_form_4, Some(&inserted_comment_1.path))
551 let comment_form_5 = CommentInsertForm::builder()
552 .content("Comment 5".into())
553 .creator_id(inserted_person.id)
554 .post_id(inserted_post.id)
557 let _inserted_comment_5 =
558 Comment::create(pool, &comment_form_5, Some(&inserted_comment_4.path))
562 let timmy_blocks_sara_form = PersonBlockForm {
563 person_id: inserted_person.id,
564 target_id: inserted_person_2.id,
567 let inserted_block = PersonBlock::block(pool, &timmy_blocks_sara_form)
571 let expected_block = PersonBlock {
572 id: inserted_block.id,
573 person_id: inserted_person.id,
574 target_id: inserted_person_2.id,
575 published: inserted_block.published,
577 assert_eq!(expected_block, inserted_block);
579 let comment_like_form = CommentLikeForm {
580 comment_id: inserted_comment_0.id,
581 post_id: inserted_post.id,
582 person_id: inserted_person.id,
586 let _inserted_comment_like = CommentLike::like(pool, &comment_like_form).await.unwrap();
603 async fn test_crud() {
604 let pool = &build_db_pool_for_tests().await;
605 let data = init_data(pool).await;
607 let expected_comment_view_no_person = expected_comment_view(&data, pool).await;
609 let mut expected_comment_view_with_person = expected_comment_view_no_person.clone();
610 expected_comment_view_with_person.my_vote = Some(1);
612 let read_comment_views_no_person = CommentQuery::builder()
614 .post_id(Some(data.inserted_post.id))
621 expected_comment_view_no_person,
622 read_comment_views_no_person[0]
625 let read_comment_views_with_person = CommentQuery::builder()
627 .post_id(Some(data.inserted_post.id))
628 .local_user(Some(&data.inserted_local_user))
635 expected_comment_view_with_person,
636 read_comment_views_with_person[0]
639 // Make sure its 1, not showing the blocked comment
640 assert_eq!(5, read_comment_views_with_person.len());
642 let read_comment_from_blocked_person = CommentView::read(
644 data.inserted_comment_1.id,
645 Some(data.inserted_person.id),
650 // Make sure block set the creator blocked
651 assert!(read_comment_from_blocked_person.creator_blocked);
653 cleanup(data, pool).await;
658 async fn test_comment_tree() {
659 let pool = &build_db_pool_for_tests().await;
660 let data = init_data(pool).await;
662 let top_path = data.inserted_comment_0.path.clone();
663 let read_comment_views_top_path = CommentQuery::builder()
665 .post_id(Some(data.inserted_post.id))
666 .parent_path(Some(top_path))
672 let child_path = data.inserted_comment_1.path.clone();
673 let read_comment_views_child_path = CommentQuery::builder()
675 .post_id(Some(data.inserted_post.id))
676 .parent_path(Some(child_path))
682 // Make sure the comment parent-limited fetch is correct
683 assert_eq!(6, read_comment_views_top_path.len());
684 assert_eq!(4, read_comment_views_child_path.len());
686 // Make sure it contains the parent, but not the comment from the other tree
687 let child_comments = read_comment_views_child_path
690 .collect::<Vec<Comment>>();
691 assert!(child_comments.contains(&data.inserted_comment_1));
692 assert!(!child_comments.contains(&data.inserted_comment_2));
694 let read_comment_views_top_max_depth = CommentQuery::builder()
696 .post_id(Some(data.inserted_post.id))
703 // Make sure a depth limited one only has the top comment
705 expected_comment_view(&data, pool).await,
706 read_comment_views_top_max_depth[0]
708 assert_eq!(1, read_comment_views_top_max_depth.len());
710 let child_path = data.inserted_comment_1.path.clone();
711 let read_comment_views_parent_max_depth = CommentQuery::builder()
713 .post_id(Some(data.inserted_post.id))
714 .parent_path(Some(child_path))
716 .sort(Some(CommentSortType::New))
722 // Make sure a depth limited one, and given child comment 1, has 3
723 assert!(read_comment_views_parent_max_depth[2]
727 assert_eq!(3, read_comment_views_parent_max_depth.len());
729 cleanup(data, pool).await;
734 async fn test_languages() {
735 let pool = &build_db_pool_for_tests().await;
736 let data = init_data(pool).await;
738 // by default, user has all languages enabled and should see all comments
739 // (except from blocked user)
740 let all_languages = CommentQuery::builder()
742 .local_user(Some(&data.inserted_local_user))
747 assert_eq!(5, all_languages.len());
749 // change user lang to finnish, should only show single finnish comment
750 let finnish_id = Language::read_id_from_code(pool, "fi").await.unwrap();
751 LocalUserLanguage::update(pool, vec![finnish_id], data.inserted_local_user.id)
754 let finnish_comment = CommentQuery::builder()
756 .local_user(Some(&data.inserted_local_user))
761 assert_eq!(1, finnish_comment.len());
763 data.inserted_comment_2.content,
764 finnish_comment[0].comment.content
766 assert_eq!(finnish_id, finnish_comment[0].comment.language_id);
768 // now show all comments with undetermined language (which is the default value)
769 let undetermined_id = Language::read_id_from_code(pool, "und").await.unwrap();
770 LocalUserLanguage::update(pool, vec![undetermined_id], data.inserted_local_user.id)
773 let undetermined_comment = CommentQuery::builder()
775 .local_user(Some(&data.inserted_local_user))
780 assert_eq!(3, undetermined_comment.len());
782 cleanup(data, pool).await;
785 async fn cleanup(data: Data, pool: &DbPool) {
786 CommentLike::remove(pool, data.inserted_person.id, data.inserted_comment_0.id)
789 Comment::delete(pool, data.inserted_comment_0.id)
792 Comment::delete(pool, data.inserted_comment_1.id)
795 Post::delete(pool, data.inserted_post.id).await.unwrap();
796 Community::delete(pool, data.inserted_community.id)
799 Person::delete(pool, data.inserted_person.id).await.unwrap();
800 Person::delete(pool, data.inserted_person_2.id)
803 Instance::delete(pool, data.inserted_instance.id)
808 async fn expected_comment_view(data: &Data, pool: &DbPool) -> CommentView {
809 let agg = CommentAggregates::read(pool, data.inserted_comment_0.id)
813 creator_banned_from_community: false,
815 subscribed: SubscribedType::NotSubscribed,
817 creator_blocked: false,
819 id: data.inserted_comment_0.id,
820 content: "Comment 0".into(),
821 creator_id: data.inserted_person.id,
822 post_id: data.inserted_post.id,
825 published: data.inserted_comment_0.published,
826 ap_id: data.inserted_comment_0.ap_id.clone(),
829 distinguished: false,
830 path: data.inserted_comment_0.clone().path,
831 language_id: LanguageId(0),
833 creator: PersonSafe {
834 id: data.inserted_person.id,
835 name: "timmy".into(),
837 published: data.inserted_person.published,
839 actor_id: data.inserted_person.actor_id.clone(),
848 inbox_url: data.inserted_person.inbox_url.clone(),
849 shared_inbox_url: None,
850 matrix_user_id: None,
852 instance_id: data.inserted_instance.id,
855 id: data.inserted_post.id,
856 name: data.inserted_post.name.clone(),
857 creator_id: data.inserted_person.id,
860 published: data.inserted_post.published,
862 community_id: data.inserted_community.id,
868 embed_description: None,
869 embed_video_url: None,
871 ap_id: data.inserted_post.ap_id.clone(),
873 language_id: Default::default(),
874 featured_community: false,
875 featured_local: false,
877 community: CommunitySafe {
878 id: data.inserted_community.id,
879 name: "test community 5".to_string(),
884 actor_id: data.inserted_community.actor_id.clone(),
886 title: "nada".to_owned(),
891 posting_restricted_to_mods: false,
892 published: data.inserted_community.published,
893 instance_id: data.inserted_instance.id,
895 counts: CommentAggregates {
897 comment_id: data.inserted_comment_0.id,
901 published: agg.published,