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 person::{Person, PersonSafe},
24 person_block::PersonBlock,
27 traits::{ToSafe, ViewToVec},
28 utils::{functions::hot_rank, fuzzy_search, limit_and_offset_unlimited},
32 use typed_builder::TypedBuilder;
34 type CommentViewTuple = (
40 Option<CommunityPersonBan>,
41 Option<CommunityFollower>,
50 comment_id: CommentId,
51 my_person_id: Option<PersonId>,
52 ) -> Result<Self, Error> {
53 // The left join below will return None in this case
54 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
62 creator_banned_from_community,
69 .inner_join(person::table)
70 .inner_join(post::table)
71 .inner_join(community::table.on(post::community_id.eq(community::id)))
72 .inner_join(comment_aggregates::table)
74 community_person_ban::table.on(
76 .eq(community_person_ban::community_id)
77 .and(community_person_ban::person_id.eq(comment::creator_id))
79 community_person_ban::expires
81 .or(community_person_ban::expires.gt(now)),
86 community_follower::table.on(
88 .eq(community_follower::community_id)
89 .and(community_follower::person_id.eq(person_id_join)),
93 comment_saved::table.on(
95 .eq(comment_saved::comment_id)
96 .and(comment_saved::person_id.eq(person_id_join)),
100 person_block::table.on(
102 .eq(person_block::target_id)
103 .and(person_block::person_id.eq(person_id_join)),
107 comment_like::table.on(
109 .eq(comment_like::comment_id)
110 .and(comment_like::person_id.eq(person_id_join)),
114 comment::all_columns,
115 Person::safe_columns_tuple(),
117 Community::safe_columns_tuple(),
118 comment_aggregates::all_columns,
119 community_person_ban::all_columns.nullable(),
120 community_follower::all_columns.nullable(),
121 comment_saved::all_columns.nullable(),
122 person_block::all_columns.nullable(),
123 comment_like::score.nullable(),
125 .first::<CommentViewTuple>(conn)?;
127 // If a person is given, then my_vote, if None, should be 0, not null
128 // Necessary to differentiate between other person's votes
129 let my_vote = if my_person_id.is_some() && comment_like.is_none() {
141 creator_banned_from_community: creator_banned_from_community.is_some(),
142 subscribed: CommunityFollower::to_subscribed_type(&follower),
143 saved: saved.is_some(),
144 creator_blocked: creator_blocked.is_some(),
150 #[derive(TypedBuilder)]
151 #[builder(field_defaults(default))]
152 pub struct CommentQuery<'a> {
154 conn: &'a PgConnection,
155 listing_type: Option<ListingType>,
156 sort: Option<CommentSortType>,
157 community_id: Option<CommunityId>,
158 community_actor_id: Option<DbUrl>,
159 post_id: Option<PostId>,
160 parent_path: Option<Ltree>,
161 creator_id: Option<PersonId>,
162 my_person_id: Option<PersonId>,
163 search_term: Option<String>,
164 saved_only: Option<bool>,
165 show_bot_accounts: 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.my_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.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.my_person_id.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,
376 source::{comment::*, community::*, person::*, person_block::PersonBlockForm, post::*},
377 traits::{Blockable, Crud, Likeable},
378 utils::establish_unpooled_connection,
381 use serial_test::serial;
386 let conn = establish_unpooled_connection();
388 let new_person = PersonForm {
389 name: "timmy".into(),
390 public_key: Some("pubkey".to_string()),
391 ..PersonForm::default()
394 let inserted_person = Person::create(&conn, &new_person).unwrap();
396 let new_person_2 = PersonForm {
398 public_key: Some("pubkey".to_string()),
399 ..PersonForm::default()
402 let inserted_person_2 = Person::create(&conn, &new_person_2).unwrap();
404 let new_community = CommunityForm {
405 name: "test community 5".to_string(),
406 title: "nada".to_owned(),
407 public_key: Some("pubkey".to_string()),
408 ..CommunityForm::default()
411 let inserted_community = Community::create(&conn, &new_community).unwrap();
413 let new_post = PostForm {
414 name: "A test post 2".into(),
415 creator_id: inserted_person.id,
416 community_id: inserted_community.id,
417 ..PostForm::default()
420 let inserted_post = Post::create(&conn, &new_post).unwrap();
422 // Create a comment tree with this hierarchy
430 let comment_form_0 = CommentForm {
431 content: "Comment 0".into(),
432 creator_id: inserted_person.id,
433 post_id: inserted_post.id,
434 ..CommentForm::default()
437 let inserted_comment_0 = Comment::create(&conn, &comment_form_0, None).unwrap();
439 let comment_form_1 = CommentForm {
440 content: "Comment 1, A test blocked comment".into(),
441 creator_id: inserted_person_2.id,
442 post_id: inserted_post.id,
443 ..CommentForm::default()
446 let inserted_comment_1 =
447 Comment::create(&conn, &comment_form_1, Some(&inserted_comment_0.path)).unwrap();
449 let comment_form_2 = CommentForm {
450 content: "Comment 2".into(),
451 creator_id: inserted_person.id,
452 post_id: inserted_post.id,
453 ..CommentForm::default()
456 let inserted_comment_2 =
457 Comment::create(&conn, &comment_form_2, Some(&inserted_comment_0.path)).unwrap();
459 let comment_form_3 = CommentForm {
460 content: "Comment 3".into(),
461 creator_id: inserted_person.id,
462 post_id: inserted_post.id,
463 ..CommentForm::default()
466 let _inserted_comment_3 =
467 Comment::create(&conn, &comment_form_3, Some(&inserted_comment_1.path)).unwrap();
469 let comment_form_4 = CommentForm {
470 content: "Comment 4".into(),
471 creator_id: inserted_person.id,
472 post_id: inserted_post.id,
473 ..CommentForm::default()
476 let inserted_comment_4 =
477 Comment::create(&conn, &comment_form_4, Some(&inserted_comment_1.path)).unwrap();
479 let comment_form_5 = CommentForm {
480 content: "Comment 5".into(),
481 creator_id: inserted_person.id,
482 post_id: inserted_post.id,
483 ..CommentForm::default()
486 let _inserted_comment_5 =
487 Comment::create(&conn, &comment_form_5, Some(&inserted_comment_4.path)).unwrap();
489 let timmy_blocks_sara_form = PersonBlockForm {
490 person_id: inserted_person.id,
491 target_id: inserted_person_2.id,
494 let inserted_block = PersonBlock::block(&conn, &timmy_blocks_sara_form).unwrap();
496 let expected_block = PersonBlock {
497 id: inserted_block.id,
498 person_id: inserted_person.id,
499 target_id: inserted_person_2.id,
500 published: inserted_block.published,
503 assert_eq!(expected_block, inserted_block);
505 let comment_like_form = CommentLikeForm {
506 comment_id: inserted_comment_0.id,
507 post_id: inserted_post.id,
508 person_id: inserted_person.id,
512 let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
514 let agg = CommentAggregates::read(&conn, inserted_comment_0.id).unwrap();
516 let top_path = inserted_comment_0.to_owned().path;
517 let expected_comment_view_no_person = CommentView {
518 creator_banned_from_community: false,
520 subscribed: SubscribedType::NotSubscribed,
522 creator_blocked: false,
524 id: inserted_comment_0.id,
525 content: "Comment 0".into(),
526 creator_id: inserted_person.id,
527 post_id: inserted_post.id,
530 published: inserted_comment_0.published,
531 ap_id: inserted_comment_0.ap_id,
534 distinguished: false,
537 creator: PersonSafe {
538 id: inserted_person.id,
539 name: "timmy".into(),
541 published: inserted_person.published,
543 actor_id: inserted_person.actor_id.to_owned(),
552 inbox_url: inserted_person.inbox_url.to_owned(),
553 shared_inbox_url: None,
554 matrix_user_id: None,
558 id: inserted_post.id,
559 name: inserted_post.name.to_owned(),
560 creator_id: inserted_person.id,
563 published: inserted_post.published,
565 community_id: inserted_community.id,
572 embed_description: None,
573 embed_video_url: None,
575 ap_id: inserted_post.ap_id.to_owned(),
578 community: CommunitySafe {
579 id: inserted_community.id,
580 name: "test community 5".to_string(),
585 actor_id: inserted_community.actor_id.to_owned(),
587 title: "nada".to_owned(),
592 posting_restricted_to_mods: false,
593 published: inserted_community.published,
595 counts: CommentAggregates {
597 comment_id: inserted_comment_0.id,
601 published: agg.published,
606 let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
607 expected_comment_view_with_person.my_vote = Some(1);
609 let read_comment_views_no_person = CommentQuery::builder()
611 .post_id(Some(inserted_post.id))
617 expected_comment_view_no_person,
618 read_comment_views_no_person[0]
621 let read_comment_views_with_person = CommentQuery::builder()
623 .post_id(Some(inserted_post.id))
624 .my_person_id(Some(inserted_person.id))
630 expected_comment_view_with_person,
631 read_comment_views_with_person[0]
634 // Make sure its 1, not showing the blocked comment
635 assert_eq!(5, read_comment_views_with_person.len());
637 let read_comment_from_blocked_person =
638 CommentView::read(&conn, inserted_comment_1.id, Some(inserted_person.id)).unwrap();
640 // Make sure block set the creator blocked
641 assert!(read_comment_from_blocked_person.creator_blocked);
643 let top_path = inserted_comment_0.path;
644 let read_comment_views_top_path = CommentQuery::builder()
646 .post_id(Some(inserted_post.id))
647 .parent_path(Some(top_path))
652 let child_path = inserted_comment_1.to_owned().path;
653 let read_comment_views_child_path = CommentQuery::builder()
655 .post_id(Some(inserted_post.id))
656 .parent_path(Some(child_path))
661 // Make sure the comment parent-limited fetch is correct
662 assert_eq!(6, read_comment_views_top_path.len());
663 assert_eq!(4, read_comment_views_child_path.len());
665 // Make sure it contains the parent, but not the comment from the other tree
666 let child_comments = read_comment_views_child_path
669 .collect::<Vec<Comment>>();
670 assert!(child_comments.contains(&inserted_comment_1));
671 assert!(!child_comments.contains(&inserted_comment_2));
673 let read_comment_views_top_max_depth = CommentQuery::builder()
675 .post_id(Some(inserted_post.id))
681 // Make sure a depth limited one only has the top comment
683 expected_comment_view_no_person,
684 read_comment_views_top_max_depth[0]
686 assert_eq!(1, read_comment_views_top_max_depth.len());
688 let child_path = inserted_comment_1.path;
689 let read_comment_views_parent_max_depth = CommentQuery::builder()
691 .post_id(Some(inserted_post.id))
692 .parent_path(Some(child_path))
694 .sort(Some(CommentSortType::New))
699 // Make sure a depth limited one, and given child comment 1, has 3
700 assert!(read_comment_views_parent_max_depth[2]
704 assert_eq!(3, read_comment_views_parent_max_depth.len());
708 CommentLike::remove(&conn, inserted_person.id, inserted_comment_0.id).unwrap();
709 let num_deleted = Comment::delete(&conn, inserted_comment_0.id).unwrap();
710 Comment::delete(&conn, inserted_comment_1.id).unwrap();
711 Post::delete(&conn, inserted_post.id).unwrap();
712 Community::delete(&conn, inserted_community.id).unwrap();
713 Person::delete(&conn, inserted_person.id).unwrap();
714 Person::delete(&conn, inserted_person_2.id).unwrap();
716 assert_eq!(1, num_deleted);
717 assert_eq!(1, like_removed);