1 use crate::structs::CommentView;
2 use diesel::{dsl::*, result::Error, *};
4 aggregates::structs::CommentAggregates,
5 newtypes::{CommentId, CommunityId, DbUrl, PersonId, PostId},
22 comment::{Comment, CommentAlias1, CommentSaved},
23 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
24 person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1},
25 person_block::PersonBlock,
28 traits::{MaybeOptional, ToSafe, ViewToVec},
29 utils::{functions::hot_rank, fuzzy_search, limit_and_offset_unlimited},
34 type CommentViewTuple = (
37 Option<CommentAlias1>,
38 Option<PersonSafeAlias1>,
42 Option<CommunityPersonBan>,
43 Option<CommunityFollower>,
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));
66 creator_banned_from_community,
73 .inner_join(person::table)
75 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
76 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
77 .inner_join(post::table)
78 .inner_join(community::table.on(post::community_id.eq(community::id)))
79 .inner_join(comment_aggregates::table)
81 community_person_ban::table.on(
83 .eq(community_person_ban::community_id)
84 .and(community_person_ban::person_id.eq(comment::creator_id))
86 community_person_ban::expires
88 .or(community_person_ban::expires.gt(now)),
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,
122 Person::safe_columns_tuple(),
123 comment_alias_1::all_columns.nullable(),
124 PersonAlias1::safe_columns_tuple().nullable(),
126 Community::safe_columns_tuple(),
127 comment_aggregates::all_columns,
128 community_person_ban::all_columns.nullable(),
129 community_follower::all_columns.nullable(),
130 comment_saved::all_columns.nullable(),
131 person_block::all_columns.nullable(),
132 comment_like::score.nullable(),
134 .first::<CommentViewTuple>(conn)?;
136 // If a person is given, then my_vote, if None, should be 0, not null
137 // Necessary to differentiate between other person's votes
138 let my_vote = if my_person_id.is_some() && comment_like.is_none() {
151 creator_banned_from_community: creator_banned_from_community.is_some(),
152 subscribed: CommunityFollower::to_subscribed_type(&follower),
153 saved: saved.is_some(),
154 creator_blocked: creator_blocked.is_some(),
159 /// Gets the recipient person id.
160 /// If there is no parent comment, its the post creator
161 pub fn get_recipient_id(&self) -> PersonId {
162 match &self.recipient {
163 Some(parent_commenter) => parent_commenter.id,
164 None => self.post.creator_id,
168 /// Gets the number of unread replies
169 pub fn get_unread_replies(conn: &PgConnection, my_person_id: PersonId) -> Result<i64, Error> {
174 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
175 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
176 .inner_join(post::table)
177 .inner_join(community::table.on(post::community_id.eq(community::id)))
179 person_block::table.on(
181 .eq(person_block::target_id)
182 .and(person_block::person_id.eq(my_person_id)),
186 community_block::table.on(
188 .eq(community_block::community_id)
189 .and(community_block::person_id.eq(my_person_id)),
192 .filter(person_alias_1::id.eq(my_person_id)) // Gets the comment replies
196 .and(post::creator_id.eq(my_person_id)),
197 ) // Gets the top level replies
198 .filter(comment::read.eq(false))
199 .filter(comment::deleted.eq(false))
200 .filter(comment::removed.eq(false))
201 // Don't show blocked communities or persons
202 .filter(community_block::person_id.is_null())
203 .filter(person_block::person_id.is_null())
204 .select(count(comment::id))
209 pub struct CommentQueryBuilder<'a> {
210 conn: &'a PgConnection,
211 listing_type: Option<ListingType>,
212 sort: Option<SortType>,
213 community_id: Option<CommunityId>,
214 community_actor_id: Option<DbUrl>,
215 post_id: Option<PostId>,
216 creator_id: Option<PersonId>,
217 recipient_id: Option<PersonId>,
218 my_person_id: Option<PersonId>,
219 search_term: Option<String>,
220 saved_only: Option<bool>,
221 unread_only: Option<bool>,
222 show_bot_accounts: Option<bool>,
227 impl<'a> CommentQueryBuilder<'a> {
228 pub fn create(conn: &'a PgConnection) -> Self {
229 CommentQueryBuilder {
231 listing_type: Some(ListingType::All),
234 community_actor_id: None,
242 show_bot_accounts: None,
248 pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
249 self.listing_type = listing_type.get_optional();
253 pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
254 self.sort = sort.get_optional();
258 pub fn post_id<T: MaybeOptional<PostId>>(mut self, post_id: T) -> Self {
259 self.post_id = post_id.get_optional();
263 pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
264 self.creator_id = creator_id.get_optional();
268 pub fn recipient_id<T: MaybeOptional<PersonId>>(mut self, recipient_id: T) -> Self {
269 self.recipient_id = recipient_id.get_optional();
273 pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
274 self.community_id = community_id.get_optional();
278 pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
279 self.my_person_id = my_person_id.get_optional();
283 pub fn community_actor_id<T: MaybeOptional<DbUrl>>(mut self, community_actor_id: T) -> Self {
284 self.community_actor_id = community_actor_id.get_optional();
288 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
289 self.search_term = search_term.get_optional();
293 pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
294 self.saved_only = saved_only.get_optional();
298 pub fn unread_only<T: MaybeOptional<bool>>(mut self, unread_only: T) -> Self {
299 self.unread_only = unread_only.get_optional();
303 pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
304 self.show_bot_accounts = show_bot_accounts.get_optional();
308 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
309 self.page = page.get_optional();
313 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
314 self.limit = limit.get_optional();
318 pub fn list(self) -> Result<Vec<CommentView>, Error> {
321 // The left join below will return None in this case
322 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
324 let mut query = comment::table
325 .inner_join(person::table)
327 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
328 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
329 .inner_join(post::table)
330 .inner_join(community::table.on(post::community_id.eq(community::id)))
331 .inner_join(comment_aggregates::table)
333 community_person_ban::table.on(
335 .eq(community_person_ban::community_id)
336 .and(community_person_ban::person_id.eq(comment::creator_id))
338 community_person_ban::expires
340 .or(community_person_ban::expires.gt(now)),
345 community_follower::table.on(
347 .eq(community_follower::community_id)
348 .and(community_follower::person_id.eq(person_id_join)),
352 comment_saved::table.on(
354 .eq(comment_saved::comment_id)
355 .and(comment_saved::person_id.eq(person_id_join)),
359 person_block::table.on(
361 .eq(person_block::target_id)
362 .and(person_block::person_id.eq(person_id_join)),
366 community_block::table.on(
368 .eq(community_block::community_id)
369 .and(community_block::person_id.eq(person_id_join)),
373 comment_like::table.on(
375 .eq(comment_like::comment_id)
376 .and(comment_like::person_id.eq(person_id_join)),
380 comment::all_columns,
381 Person::safe_columns_tuple(),
382 comment_alias_1::all_columns.nullable(),
383 PersonAlias1::safe_columns_tuple().nullable(),
385 Community::safe_columns_tuple(),
386 comment_aggregates::all_columns,
387 community_person_ban::all_columns.nullable(),
388 community_follower::all_columns.nullable(),
389 comment_saved::all_columns.nullable(),
390 person_block::all_columns.nullable(),
391 comment_like::score.nullable(),
396 if let Some(recipient_id) = self.recipient_id {
398 // TODO needs lots of testing
399 .filter(person_alias_1::id.eq(recipient_id)) // Gets the comment replies
403 .and(post::creator_id.eq(recipient_id)),
404 ) // Gets the top level replies
405 .filter(comment::deleted.eq(false))
406 .filter(comment::removed.eq(false));
409 if self.unread_only.unwrap_or(false) {
410 query = query.filter(comment::read.eq(false));
413 if let Some(creator_id) = self.creator_id {
414 query = query.filter(comment::creator_id.eq(creator_id));
417 if let Some(post_id) = self.post_id {
418 query = query.filter(comment::post_id.eq(post_id));
421 if let Some(search_term) = self.search_term {
422 query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
425 if let Some(listing_type) = self.listing_type {
427 ListingType::Subscribed => {
428 query = query.filter(community_follower::person_id.is_not_null())
429 } // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
430 ListingType::Local => {
431 query = query.filter(community::local.eq(true)).filter(
434 .or(community_follower::person_id.eq(person_id_join)),
437 ListingType::All => {
438 query = query.filter(
441 .or(community_follower::person_id.eq(person_id_join)),
447 if let Some(community_id) = self.community_id {
448 query = query.filter(post::community_id.eq(community_id));
451 if let Some(community_actor_id) = self.community_actor_id {
452 query = query.filter(community::actor_id.eq(community_actor_id))
455 if self.saved_only.unwrap_or(false) {
456 query = query.filter(comment_saved::id.is_not_null());
459 if !self.show_bot_accounts.unwrap_or(true) {
460 query = query.filter(person::bot_account.eq(false));
463 query = match self.sort.unwrap_or(SortType::New) {
464 SortType::Hot | SortType::Active => query
465 .order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
466 .then_order_by(comment_aggregates::published.desc()),
467 SortType::New | SortType::MostComments | SortType::NewComments => {
468 query.order_by(comment::published.desc())
470 SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
471 SortType::TopYear => query
472 .filter(comment::published.gt(now - 1.years()))
473 .order_by(comment_aggregates::score.desc()),
474 SortType::TopMonth => query
475 .filter(comment::published.gt(now - 1.months()))
476 .order_by(comment_aggregates::score.desc()),
477 SortType::TopWeek => query
478 .filter(comment::published.gt(now - 1.weeks()))
479 .order_by(comment_aggregates::score.desc()),
480 SortType::TopDay => query
481 .filter(comment::published.gt(now - 1.days()))
482 .order_by(comment_aggregates::score.desc()),
485 // Don't show blocked communities or persons
486 if self.my_person_id.is_some() {
487 query = query.filter(community_block::person_id.is_null());
488 query = query.filter(person_block::person_id.is_null());
491 // Don't use the regular error-checking one, many more comments must ofter be fetched.
492 let (limit, offset) = limit_and_offset_unlimited(self.page, self.limit);
494 // Note: deleted and removed comments are done on the front side
498 .load::<CommentViewTuple>(self.conn)?;
500 Ok(CommentView::from_tuple_to_vec(res))
504 impl ViewToVec for CommentView {
505 type DbTuple = CommentViewTuple;
506 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
510 comment: a.0.to_owned(),
511 creator: a.1.to_owned(),
512 recipient: a.3.to_owned(),
513 post: a.4.to_owned(),
514 community: a.5.to_owned(),
515 counts: a.6.to_owned(),
516 creator_banned_from_community: a.7.is_some(),
517 subscribed: CommunityFollower::to_subscribed_type(&a.8),
518 saved: a.9.is_some(),
519 creator_blocked: a.10.is_some(),
522 .collect::<Vec<Self>>()
528 use crate::comment_view::*;
529 use lemmy_db_schema::{
530 aggregates::structs::CommentAggregates,
531 source::{comment::*, community::*, person::*, person_block::PersonBlockForm, post::*},
532 traits::{Blockable, Crud, Likeable},
533 utils::establish_unpooled_connection,
536 use serial_test::serial;
541 let conn = establish_unpooled_connection();
543 let new_person = PersonForm {
544 name: "timmy".into(),
545 public_key: Some("pubkey".to_string()),
546 ..PersonForm::default()
549 let inserted_person = Person::create(&conn, &new_person).unwrap();
551 let new_person_2 = PersonForm {
553 public_key: Some("pubkey".to_string()),
554 ..PersonForm::default()
557 let inserted_person_2 = Person::create(&conn, &new_person_2).unwrap();
559 let new_community = CommunityForm {
560 name: "test community 5".to_string(),
561 title: "nada".to_owned(),
562 public_key: Some("pubkey".to_string()),
563 ..CommunityForm::default()
566 let inserted_community = Community::create(&conn, &new_community).unwrap();
568 let new_post = PostForm {
569 name: "A test post 2".into(),
570 creator_id: inserted_person.id,
571 community_id: inserted_community.id,
572 ..PostForm::default()
575 let inserted_post = Post::create(&conn, &new_post).unwrap();
577 let comment_form = CommentForm {
578 content: "A test comment 32".into(),
579 creator_id: inserted_person.id,
580 post_id: inserted_post.id,
581 ..CommentForm::default()
584 let inserted_comment = Comment::create(&conn, &comment_form).unwrap();
586 let comment_form_2 = CommentForm {
587 content: "A test blocked comment".into(),
588 creator_id: inserted_person_2.id,
589 post_id: inserted_post.id,
590 parent_id: Some(inserted_comment.id),
591 ..CommentForm::default()
594 let inserted_comment_2 = Comment::create(&conn, &comment_form_2).unwrap();
596 let timmy_blocks_sara_form = PersonBlockForm {
597 person_id: inserted_person.id,
598 target_id: inserted_person_2.id,
601 let inserted_block = PersonBlock::block(&conn, &timmy_blocks_sara_form).unwrap();
603 let expected_block = PersonBlock {
604 id: inserted_block.id,
605 person_id: inserted_person.id,
606 target_id: inserted_person_2.id,
607 published: inserted_block.published,
610 assert_eq!(expected_block, inserted_block);
612 let comment_like_form = CommentLikeForm {
613 comment_id: inserted_comment.id,
614 post_id: inserted_post.id,
615 person_id: inserted_person.id,
619 let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
621 let agg = CommentAggregates::read(&conn, inserted_comment.id).unwrap();
623 let expected_comment_view_no_person = CommentView {
624 creator_banned_from_community: false,
626 subscribed: SubscribedType::NotSubscribed,
628 creator_blocked: false,
630 id: inserted_comment.id,
631 content: "A test comment 32".into(),
632 creator_id: inserted_person.id,
633 post_id: inserted_post.id,
638 published: inserted_comment.published,
639 ap_id: inserted_comment.ap_id,
643 creator: PersonSafe {
644 id: inserted_person.id,
645 name: "timmy".into(),
647 published: inserted_person.published,
649 actor_id: inserted_person.actor_id.to_owned(),
658 inbox_url: inserted_person.inbox_url.to_owned(),
659 shared_inbox_url: None,
660 matrix_user_id: None,
665 id: inserted_post.id,
666 name: inserted_post.name.to_owned(),
667 creator_id: inserted_person.id,
670 published: inserted_post.published,
672 community_id: inserted_community.id,
679 embed_description: None,
680 embed_video_url: None,
682 ap_id: inserted_post.ap_id.to_owned(),
685 community: CommunitySafe {
686 id: inserted_community.id,
687 name: "test community 5".to_string(),
692 actor_id: inserted_community.actor_id.to_owned(),
694 title: "nada".to_owned(),
699 posting_restricted_to_mods: false,
700 published: inserted_community.published,
702 counts: CommentAggregates {
704 comment_id: inserted_comment.id,
708 published: agg.published,
712 let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
713 expected_comment_view_with_person.my_vote = Some(1);
715 let read_comment_views_no_person = CommentQueryBuilder::create(&conn)
716 .post_id(inserted_post.id)
720 let read_comment_views_with_person = CommentQueryBuilder::create(&conn)
721 .post_id(inserted_post.id)
722 .my_person_id(inserted_person.id)
726 let read_comment_from_blocked_person =
727 CommentView::read(&conn, inserted_comment_2.id, Some(inserted_person.id)).unwrap();
729 let like_removed = CommentLike::remove(&conn, inserted_person.id, inserted_comment.id).unwrap();
730 let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap();
731 Comment::delete(&conn, inserted_comment_2.id).unwrap();
732 Post::delete(&conn, inserted_post.id).unwrap();
733 Community::delete(&conn, inserted_community.id).unwrap();
734 Person::delete(&conn, inserted_person.id).unwrap();
735 Person::delete(&conn, inserted_person_2.id).unwrap();
737 // Make sure its 1, not showing the blocked comment
738 assert_eq!(1, read_comment_views_with_person.len());
741 expected_comment_view_no_person,
742 read_comment_views_no_person[1]
745 expected_comment_view_with_person,
746 read_comment_views_with_person[0]
749 // Make sure block set the creator blocked
750 assert!(read_comment_from_blocked_person.creator_blocked);
752 assert_eq!(1, num_deleted);
753 assert_eq!(1, like_removed);