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, ListingType, SortType},
32 type CommentViewTuple = (
35 Option<CommentAlias1>,
36 Option<PersonSafeAlias1>,
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));
64 creator_banned_from_community,
71 .inner_join(person::table)
73 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
74 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
75 .inner_join(post::table)
76 .inner_join(community::table.on(post::community_id.eq(community::id)))
77 .inner_join(comment_aggregates::table)
79 community_person_ban::table.on(
81 .eq(community_person_ban::community_id)
82 .and(community_person_ban::person_id.eq(comment::creator_id))
84 community_person_ban::expires
86 .or(community_person_ban::expires.gt(now)),
91 community_follower::table.on(
93 .eq(community_follower::community_id)
94 .and(community_follower::person_id.eq(person_id_join)),
98 comment_saved::table.on(
100 .eq(comment_saved::comment_id)
101 .and(comment_saved::person_id.eq(person_id_join)),
105 person_block::table.on(
107 .eq(person_block::target_id)
108 .and(person_block::person_id.eq(person_id_join)),
112 comment_like::table.on(
114 .eq(comment_like::comment_id)
115 .and(comment_like::person_id.eq(person_id_join)),
119 comment::all_columns,
120 Person::safe_columns_tuple(),
121 comment_alias_1::all_columns.nullable(),
122 PersonAlias1::safe_columns_tuple().nullable(),
124 Community::safe_columns_tuple(),
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)?;
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() {
149 creator_banned_from_community: creator_banned_from_community.is_some(),
150 subscribed: subscribed.is_some(),
151 saved: saved.is_some(),
152 creator_blocked: creator_blocked.is_some(),
157 /// Gets the recipient person id.
158 /// If there is no parent comment, its the post creator
159 pub fn get_recipient_id(&self) -> PersonId {
160 match &self.recipient {
161 Some(parent_commenter) => parent_commenter.id,
162 None => self.post.creator_id,
166 /// Gets the number of unread replies
167 pub fn get_unread_replies(conn: &PgConnection, my_person_id: PersonId) -> Result<i64, Error> {
172 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
173 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
174 .inner_join(post::table)
175 .inner_join(community::table.on(post::community_id.eq(community::id)))
177 person_block::table.on(
179 .eq(person_block::target_id)
180 .and(person_block::person_id.eq(my_person_id)),
184 community_block::table.on(
186 .eq(community_block::community_id)
187 .and(community_block::person_id.eq(my_person_id)),
190 .filter(person_alias_1::id.eq(my_person_id)) // Gets the comment replies
194 .and(post::creator_id.eq(my_person_id)),
195 ) // Gets the top level replies
196 .filter(comment::read.eq(false))
197 .filter(comment::deleted.eq(false))
198 .filter(comment::removed.eq(false))
199 // Don't show blocked communities or persons
200 .filter(community_block::person_id.is_null())
201 .filter(person_block::person_id.is_null())
202 .select(count(comment::id))
207 pub struct CommentQueryBuilder<'a> {
208 conn: &'a PgConnection,
209 listing_type: Option<ListingType>,
210 sort: Option<SortType>,
211 community_id: Option<CommunityId>,
212 community_actor_id: Option<DbUrl>,
213 post_id: Option<PostId>,
214 creator_id: Option<PersonId>,
215 recipient_id: Option<PersonId>,
216 my_person_id: Option<PersonId>,
217 search_term: Option<String>,
218 saved_only: Option<bool>,
219 unread_only: Option<bool>,
220 show_bot_accounts: Option<bool>,
225 impl<'a> CommentQueryBuilder<'a> {
226 pub fn create(conn: &'a PgConnection) -> Self {
227 CommentQueryBuilder {
232 community_actor_id: None,
240 show_bot_accounts: None,
246 pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
247 self.listing_type = listing_type.get_optional();
251 pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
252 self.sort = sort.get_optional();
256 pub fn post_id<T: MaybeOptional<PostId>>(mut self, post_id: T) -> Self {
257 self.post_id = post_id.get_optional();
261 pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
262 self.creator_id = creator_id.get_optional();
266 pub fn recipient_id<T: MaybeOptional<PersonId>>(mut self, recipient_id: T) -> Self {
267 self.recipient_id = recipient_id.get_optional();
271 pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
272 self.community_id = community_id.get_optional();
276 pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
277 self.my_person_id = my_person_id.get_optional();
281 pub fn community_actor_id<T: MaybeOptional<DbUrl>>(mut self, community_actor_id: T) -> Self {
282 self.community_actor_id = community_actor_id.get_optional();
286 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
287 self.search_term = search_term.get_optional();
291 pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
292 self.saved_only = saved_only.get_optional();
296 pub fn unread_only<T: MaybeOptional<bool>>(mut self, unread_only: T) -> Self {
297 self.unread_only = unread_only.get_optional();
301 pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
302 self.show_bot_accounts = show_bot_accounts.get_optional();
306 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
307 self.page = page.get_optional();
311 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
312 self.limit = limit.get_optional();
316 pub fn list(self) -> Result<Vec<CommentView>, Error> {
319 // The left join below will return None in this case
320 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
322 let mut query = comment::table
323 .inner_join(person::table)
325 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
326 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
327 .inner_join(post::table)
328 .inner_join(community::table.on(post::community_id.eq(community::id)))
329 .inner_join(comment_aggregates::table)
331 community_person_ban::table.on(
333 .eq(community_person_ban::community_id)
334 .and(community_person_ban::person_id.eq(comment::creator_id))
336 community_person_ban::expires
338 .or(community_person_ban::expires.gt(now)),
343 community_follower::table.on(
345 .eq(community_follower::community_id)
346 .and(community_follower::person_id.eq(person_id_join)),
350 comment_saved::table.on(
352 .eq(comment_saved::comment_id)
353 .and(comment_saved::person_id.eq(person_id_join)),
357 person_block::table.on(
359 .eq(person_block::target_id)
360 .and(person_block::person_id.eq(person_id_join)),
364 community_block::table.on(
366 .eq(community_block::community_id)
367 .and(community_block::person_id.eq(person_id_join)),
371 comment_like::table.on(
373 .eq(comment_like::comment_id)
374 .and(comment_like::person_id.eq(person_id_join)),
378 comment::all_columns,
379 Person::safe_columns_tuple(),
380 comment_alias_1::all_columns.nullable(),
381 PersonAlias1::safe_columns_tuple().nullable(),
383 Community::safe_columns_tuple(),
384 comment_aggregates::all_columns,
385 community_person_ban::all_columns.nullable(),
386 community_follower::all_columns.nullable(),
387 comment_saved::all_columns.nullable(),
388 person_block::all_columns.nullable(),
389 comment_like::score.nullable(),
394 if let Some(recipient_id) = self.recipient_id {
396 // TODO needs lots of testing
397 .filter(person_alias_1::id.eq(recipient_id)) // Gets the comment replies
401 .and(post::creator_id.eq(recipient_id)),
402 ) // Gets the top level replies
403 .filter(comment::deleted.eq(false))
404 .filter(comment::removed.eq(false));
407 if self.unread_only.unwrap_or(false) {
408 query = query.filter(comment::read.eq(false));
411 if let Some(creator_id) = self.creator_id {
412 query = query.filter(comment::creator_id.eq(creator_id));
415 if let Some(community_id) = self.community_id {
416 query = query.filter(post::community_id.eq(community_id));
419 if let Some(community_actor_id) = self.community_actor_id {
420 query = query.filter(community::actor_id.eq(community_actor_id))
423 if let Some(post_id) = self.post_id {
424 query = query.filter(comment::post_id.eq(post_id));
427 if let Some(search_term) = self.search_term {
428 query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
431 if let Some(listing_type) = self.listing_type {
433 ListingType::Subscribed => {
434 query = query.filter(community_follower::person_id.is_not_null())
435 } // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
436 ListingType::Local => {
437 query = query.filter(community::local.eq(true)).filter(
440 .or(community_follower::person_id.eq(person_id_join)),
443 ListingType::All => {
444 query = query.filter(
447 .or(community_follower::person_id.eq(person_id_join)),
450 ListingType::Community => {}
454 if self.saved_only.unwrap_or(false) {
455 query = query.filter(comment_saved::id.is_not_null());
458 if !self.show_bot_accounts.unwrap_or(true) {
459 query = query.filter(person::bot_account.eq(false));
462 query = match self.sort.unwrap_or(SortType::New) {
463 SortType::Hot | SortType::Active => query
464 .order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
465 .then_order_by(comment_aggregates::published.desc()),
466 SortType::New | SortType::MostComments | SortType::NewComments => {
467 query.order_by(comment::published.desc())
469 SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
470 SortType::TopYear => query
471 .filter(comment::published.gt(now - 1.years()))
472 .order_by(comment_aggregates::score.desc()),
473 SortType::TopMonth => query
474 .filter(comment::published.gt(now - 1.months()))
475 .order_by(comment_aggregates::score.desc()),
476 SortType::TopWeek => query
477 .filter(comment::published.gt(now - 1.weeks()))
478 .order_by(comment_aggregates::score.desc()),
479 SortType::TopDay => query
480 .filter(comment::published.gt(now - 1.days()))
481 .order_by(comment_aggregates::score.desc()),
484 // Don't show blocked communities or persons
485 if self.my_person_id.is_some() {
486 query = query.filter(community_block::person_id.is_null());
487 query = query.filter(person_block::person_id.is_null());
490 let (limit, offset) = limit_and_offset(self.page, self.limit);
492 // Note: deleted and removed comments are done on the front side
496 .load::<CommentViewTuple>(self.conn)?;
498 Ok(CommentView::from_tuple_to_vec(res))
502 impl ViewToVec for CommentView {
503 type DbTuple = CommentViewTuple;
504 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
508 comment: a.0.to_owned(),
509 creator: a.1.to_owned(),
510 recipient: a.3.to_owned(),
511 post: a.4.to_owned(),
512 community: a.5.to_owned(),
513 counts: a.6.to_owned(),
514 creator_banned_from_community: a.7.is_some(),
515 subscribed: a.8.is_some(),
516 saved: a.9.is_some(),
517 creator_blocked: a.10.is_some(),
520 .collect::<Vec<Self>>()
526 use crate::comment_view::*;
527 use lemmy_db_schema::{
528 aggregates::structs::CommentAggregates,
529 source::{comment::*, community::*, person::*, person_block::PersonBlockForm, post::*},
530 traits::{Blockable, Crud, Likeable},
531 utils::establish_unpooled_connection,
533 use serial_test::serial;
538 let conn = establish_unpooled_connection();
540 let new_person = PersonForm {
541 name: "timmy".into(),
542 ..PersonForm::default()
545 let inserted_person = Person::create(&conn, &new_person).unwrap();
547 let new_person_2 = PersonForm {
549 ..PersonForm::default()
552 let inserted_person_2 = Person::create(&conn, &new_person_2).unwrap();
554 let new_community = CommunityForm {
555 name: "test community 5".to_string(),
556 title: "nada".to_owned(),
557 ..CommunityForm::default()
560 let inserted_community = Community::create(&conn, &new_community).unwrap();
562 let new_post = PostForm {
563 name: "A test post 2".into(),
564 creator_id: inserted_person.id,
565 community_id: inserted_community.id,
566 ..PostForm::default()
569 let inserted_post = Post::create(&conn, &new_post).unwrap();
571 let comment_form = CommentForm {
572 content: "A test comment 32".into(),
573 creator_id: inserted_person.id,
574 post_id: inserted_post.id,
575 ..CommentForm::default()
578 let inserted_comment = Comment::create(&conn, &comment_form).unwrap();
580 let comment_form_2 = CommentForm {
581 content: "A test blocked comment".into(),
582 creator_id: inserted_person_2.id,
583 post_id: inserted_post.id,
584 parent_id: Some(inserted_comment.id),
585 ..CommentForm::default()
588 let inserted_comment_2 = Comment::create(&conn, &comment_form_2).unwrap();
590 let timmy_blocks_sara_form = PersonBlockForm {
591 person_id: inserted_person.id,
592 target_id: inserted_person_2.id,
595 let inserted_block = PersonBlock::block(&conn, &timmy_blocks_sara_form).unwrap();
597 let expected_block = PersonBlock {
598 id: inserted_block.id,
599 person_id: inserted_person.id,
600 target_id: inserted_person_2.id,
601 published: inserted_block.published,
604 assert_eq!(expected_block, inserted_block);
606 let comment_like_form = CommentLikeForm {
607 comment_id: inserted_comment.id,
608 post_id: inserted_post.id,
609 person_id: inserted_person.id,
613 let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
615 let agg = CommentAggregates::read(&conn, inserted_comment.id).unwrap();
617 let expected_comment_view_no_person = CommentView {
618 creator_banned_from_community: false,
622 creator_blocked: false,
624 id: inserted_comment.id,
625 content: "A test comment 32".into(),
626 creator_id: inserted_person.id,
627 post_id: inserted_post.id,
632 published: inserted_comment.published,
633 ap_id: inserted_comment.ap_id,
637 creator: PersonSafe {
638 id: inserted_person.id,
639 name: "timmy".into(),
641 published: inserted_person.published,
643 actor_id: inserted_person.actor_id.to_owned(),
652 inbox_url: inserted_person.inbox_url.to_owned(),
653 shared_inbox_url: None,
654 matrix_user_id: None,
659 id: inserted_post.id,
660 name: inserted_post.name.to_owned(),
661 creator_id: inserted_person.id,
664 published: inserted_post.published,
666 community_id: inserted_community.id,
673 embed_description: None,
676 ap_id: inserted_post.ap_id.to_owned(),
679 community: CommunitySafe {
680 id: inserted_community.id,
681 name: "test community 5".to_string(),
686 actor_id: inserted_community.actor_id.to_owned(),
688 title: "nada".to_owned(),
693 posting_restricted_to_mods: false,
694 published: inserted_community.published,
696 counts: CommentAggregates {
698 comment_id: inserted_comment.id,
702 published: agg.published,
706 let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
707 expected_comment_view_with_person.my_vote = Some(1);
709 let read_comment_views_no_person = CommentQueryBuilder::create(&conn)
710 .post_id(inserted_post.id)
714 let read_comment_views_with_person = CommentQueryBuilder::create(&conn)
715 .post_id(inserted_post.id)
716 .my_person_id(inserted_person.id)
720 let read_comment_from_blocked_person =
721 CommentView::read(&conn, inserted_comment_2.id, Some(inserted_person.id)).unwrap();
723 let like_removed = CommentLike::remove(&conn, inserted_person.id, inserted_comment.id).unwrap();
724 let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap();
725 Comment::delete(&conn, inserted_comment_2.id).unwrap();
726 Post::delete(&conn, inserted_post.id).unwrap();
727 Community::delete(&conn, inserted_community.id).unwrap();
728 Person::delete(&conn, inserted_person.id).unwrap();
729 Person::delete(&conn, inserted_person_2.id).unwrap();
731 // Make sure its 1, not showing the blocked comment
732 assert_eq!(1, read_comment_views_with_person.len());
735 expected_comment_view_no_person,
736 read_comment_views_no_person[1]
739 expected_comment_view_with_person,
740 read_comment_views_with_person[0]
743 // Make sure block set the creator blocked
744 assert!(read_comment_from_blocked_person.creator_blocked);
746 assert_eq!(1, num_deleted);
747 assert_eq!(1, like_removed);