1 use crate::structs::CommentView;
4 result::{Error, Error::QueryBuilderError},
8 aggregates::structs::CommentAggregates,
9 newtypes::{CommentId, CommunityId, DbUrl, PersonId, PostId},
26 comment::{Comment, CommentAlias1, CommentSaved},
27 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
28 person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1},
29 person_block::PersonBlock,
32 traits::{MaybeOptional, ToSafe, ViewToVec},
33 utils::{functions::hot_rank, fuzzy_search, limit_and_offset_unlimited},
38 type CommentViewTuple = (
41 Option<CommentAlias1>,
42 Option<PersonSafeAlias1>,
46 Option<CommunityPersonBan>,
47 Option<CommunityFollower>,
56 comment_id: CommentId,
57 my_person_id: Option<PersonId>,
58 ) -> Result<Self, Error> {
59 // The left join below will return None in this case
60 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
70 creator_banned_from_community,
77 .inner_join(person::table)
79 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
80 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
81 .inner_join(post::table)
82 .inner_join(community::table.on(post::community_id.eq(community::id)))
83 .inner_join(comment_aggregates::table)
85 community_person_ban::table.on(
87 .eq(community_person_ban::community_id)
88 .and(community_person_ban::person_id.eq(comment::creator_id))
90 community_person_ban::expires
92 .or(community_person_ban::expires.gt(now)),
97 community_follower::table.on(
99 .eq(community_follower::community_id)
100 .and(community_follower::person_id.eq(person_id_join)),
104 comment_saved::table.on(
106 .eq(comment_saved::comment_id)
107 .and(comment_saved::person_id.eq(person_id_join)),
111 person_block::table.on(
113 .eq(person_block::target_id)
114 .and(person_block::person_id.eq(person_id_join)),
118 comment_like::table.on(
120 .eq(comment_like::comment_id)
121 .and(comment_like::person_id.eq(person_id_join)),
125 comment::all_columns,
126 Person::safe_columns_tuple(),
127 comment_alias_1::all_columns.nullable(),
128 PersonAlias1::safe_columns_tuple().nullable(),
130 Community::safe_columns_tuple(),
131 comment_aggregates::all_columns,
132 community_person_ban::all_columns.nullable(),
133 community_follower::all_columns.nullable(),
134 comment_saved::all_columns.nullable(),
135 person_block::all_columns.nullable(),
136 comment_like::score.nullable(),
138 .first::<CommentViewTuple>(conn)?;
140 // If a person is given, then my_vote, if None, should be 0, not null
141 // Necessary to differentiate between other person's votes
142 let my_vote = if my_person_id.is_some() && comment_like.is_none() {
155 creator_banned_from_community: creator_banned_from_community.is_some(),
156 subscribed: CommunityFollower::to_subscribed_type(&follower),
157 saved: saved.is_some(),
158 creator_blocked: creator_blocked.is_some(),
163 /// Gets the recipient person id.
164 /// If there is no parent comment, its the post creator
165 pub fn get_recipient_id(&self) -> PersonId {
166 match &self.recipient {
167 Some(parent_commenter) => parent_commenter.id,
168 None => self.post.creator_id,
172 /// Gets the number of unread replies
173 pub fn get_unread_replies(conn: &PgConnection, my_person_id: PersonId) -> Result<i64, Error> {
178 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
179 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
180 .inner_join(post::table)
181 .inner_join(community::table.on(post::community_id.eq(community::id)))
183 person_block::table.on(
185 .eq(person_block::target_id)
186 .and(person_block::person_id.eq(my_person_id)),
190 community_block::table.on(
192 .eq(community_block::community_id)
193 .and(community_block::person_id.eq(my_person_id)),
196 .filter(person_alias_1::id.eq(my_person_id)) // Gets the comment replies
200 .and(post::creator_id.eq(my_person_id)),
201 ) // Gets the top level replies
202 .filter(comment::read.eq(false))
203 .filter(comment::deleted.eq(false))
204 .filter(comment::removed.eq(false))
205 // Don't show blocked communities or persons
206 .filter(community_block::person_id.is_null())
207 .filter(person_block::person_id.is_null())
208 .select(count(comment::id))
213 pub struct CommentQueryBuilder<'a> {
214 conn: &'a PgConnection,
215 listing_type: Option<ListingType>,
216 sort: Option<SortType>,
217 community_id: Option<CommunityId>,
218 community_actor_id: Option<DbUrl>,
219 post_id: Option<PostId>,
220 creator_id: Option<PersonId>,
221 recipient_id: Option<PersonId>,
222 my_person_id: Option<PersonId>,
223 search_term: Option<String>,
224 saved_only: Option<bool>,
225 unread_only: Option<bool>,
226 show_bot_accounts: Option<bool>,
231 impl<'a> CommentQueryBuilder<'a> {
232 pub fn create(conn: &'a PgConnection) -> Self {
233 CommentQueryBuilder {
238 community_actor_id: None,
246 show_bot_accounts: None,
252 pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
253 self.listing_type = listing_type.get_optional();
257 pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
258 self.sort = sort.get_optional();
262 pub fn post_id<T: MaybeOptional<PostId>>(mut self, post_id: T) -> Self {
263 self.post_id = post_id.get_optional();
267 pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
268 self.creator_id = creator_id.get_optional();
272 pub fn recipient_id<T: MaybeOptional<PersonId>>(mut self, recipient_id: T) -> Self {
273 self.recipient_id = recipient_id.get_optional();
277 pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
278 self.community_id = community_id.get_optional();
282 pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
283 self.my_person_id = my_person_id.get_optional();
287 pub fn community_actor_id<T: MaybeOptional<DbUrl>>(mut self, community_actor_id: T) -> Self {
288 self.community_actor_id = community_actor_id.get_optional();
292 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
293 self.search_term = search_term.get_optional();
297 pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
298 self.saved_only = saved_only.get_optional();
302 pub fn unread_only<T: MaybeOptional<bool>>(mut self, unread_only: T) -> Self {
303 self.unread_only = unread_only.get_optional();
307 pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
308 self.show_bot_accounts = show_bot_accounts.get_optional();
312 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
313 self.page = page.get_optional();
317 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
318 self.limit = limit.get_optional();
322 pub fn list(self) -> Result<Vec<CommentView>, Error> {
325 // The left join below will return None in this case
326 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
328 let mut query = comment::table
329 .inner_join(person::table)
331 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
332 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
333 .inner_join(post::table)
334 .inner_join(community::table.on(post::community_id.eq(community::id)))
335 .inner_join(comment_aggregates::table)
337 community_person_ban::table.on(
339 .eq(community_person_ban::community_id)
340 .and(community_person_ban::person_id.eq(comment::creator_id))
342 community_person_ban::expires
344 .or(community_person_ban::expires.gt(now)),
349 community_follower::table.on(
351 .eq(community_follower::community_id)
352 .and(community_follower::person_id.eq(person_id_join)),
356 comment_saved::table.on(
358 .eq(comment_saved::comment_id)
359 .and(comment_saved::person_id.eq(person_id_join)),
363 person_block::table.on(
365 .eq(person_block::target_id)
366 .and(person_block::person_id.eq(person_id_join)),
370 community_block::table.on(
372 .eq(community_block::community_id)
373 .and(community_block::person_id.eq(person_id_join)),
377 comment_like::table.on(
379 .eq(comment_like::comment_id)
380 .and(comment_like::person_id.eq(person_id_join)),
384 comment::all_columns,
385 Person::safe_columns_tuple(),
386 comment_alias_1::all_columns.nullable(),
387 PersonAlias1::safe_columns_tuple().nullable(),
389 Community::safe_columns_tuple(),
390 comment_aggregates::all_columns,
391 community_person_ban::all_columns.nullable(),
392 community_follower::all_columns.nullable(),
393 comment_saved::all_columns.nullable(),
394 person_block::all_columns.nullable(),
395 comment_like::score.nullable(),
400 if let Some(recipient_id) = self.recipient_id {
402 // TODO needs lots of testing
403 .filter(person_alias_1::id.eq(recipient_id)) // Gets the comment replies
407 .and(post::creator_id.eq(recipient_id)),
408 ) // Gets the top level replies
409 .filter(comment::deleted.eq(false))
410 .filter(comment::removed.eq(false));
413 if self.unread_only.unwrap_or(false) {
414 query = query.filter(comment::read.eq(false));
417 if let Some(creator_id) = self.creator_id {
418 query = query.filter(comment::creator_id.eq(creator_id));
421 if let Some(post_id) = self.post_id {
422 query = query.filter(comment::post_id.eq(post_id));
425 if let Some(search_term) = self.search_term {
426 query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
429 if let Some(listing_type) = self.listing_type {
431 ListingType::Subscribed => {
432 query = query.filter(community_follower::person_id.is_not_null())
433 } // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
434 ListingType::Local => {
435 query = query.filter(community::local.eq(true)).filter(
438 .or(community_follower::person_id.eq(person_id_join)),
441 ListingType::All => {
442 query = query.filter(
445 .or(community_follower::person_id.eq(person_id_join)),
448 ListingType::Community => {
449 if self.community_actor_id.is_none() && self.community_id.is_none() {
450 return Err(QueryBuilderError("No community actor or id given".into()));
452 if let Some(community_id) = self.community_id {
453 query = query.filter(post::community_id.eq(community_id));
456 if let Some(community_actor_id) = self.community_actor_id {
457 query = query.filter(community::actor_id.eq(community_actor_id))
464 if self.saved_only.unwrap_or(false) {
465 query = query.filter(comment_saved::id.is_not_null());
468 if !self.show_bot_accounts.unwrap_or(true) {
469 query = query.filter(person::bot_account.eq(false));
472 query = match self.sort.unwrap_or(SortType::New) {
473 SortType::Hot | SortType::Active => query
474 .order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
475 .then_order_by(comment_aggregates::published.desc()),
476 SortType::New | SortType::MostComments | SortType::NewComments => {
477 query.order_by(comment::published.desc())
479 SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
480 SortType::TopYear => query
481 .filter(comment::published.gt(now - 1.years()))
482 .order_by(comment_aggregates::score.desc()),
483 SortType::TopMonth => query
484 .filter(comment::published.gt(now - 1.months()))
485 .order_by(comment_aggregates::score.desc()),
486 SortType::TopWeek => query
487 .filter(comment::published.gt(now - 1.weeks()))
488 .order_by(comment_aggregates::score.desc()),
489 SortType::TopDay => query
490 .filter(comment::published.gt(now - 1.days()))
491 .order_by(comment_aggregates::score.desc()),
494 // Don't show blocked communities or persons
495 if self.my_person_id.is_some() {
496 query = query.filter(community_block::person_id.is_null());
497 query = query.filter(person_block::person_id.is_null());
500 // Don't use the regular error-checking one, many more comments must ofter be fetched.
501 let (limit, offset) = limit_and_offset_unlimited(self.page, self.limit);
503 // Note: deleted and removed comments are done on the front side
507 .load::<CommentViewTuple>(self.conn)?;
509 Ok(CommentView::from_tuple_to_vec(res))
513 impl ViewToVec for CommentView {
514 type DbTuple = CommentViewTuple;
515 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
519 comment: a.0.to_owned(),
520 creator: a.1.to_owned(),
521 recipient: a.3.to_owned(),
522 post: a.4.to_owned(),
523 community: a.5.to_owned(),
524 counts: a.6.to_owned(),
525 creator_banned_from_community: a.7.is_some(),
526 subscribed: CommunityFollower::to_subscribed_type(&a.8),
527 saved: a.9.is_some(),
528 creator_blocked: a.10.is_some(),
531 .collect::<Vec<Self>>()
537 use crate::comment_view::*;
538 use lemmy_db_schema::{
539 aggregates::structs::CommentAggregates,
540 source::{comment::*, community::*, person::*, person_block::PersonBlockForm, post::*},
541 traits::{Blockable, Crud, Likeable},
542 utils::establish_unpooled_connection,
545 use serial_test::serial;
550 let conn = establish_unpooled_connection();
552 let new_person = PersonForm {
553 name: "timmy".into(),
554 ..PersonForm::default()
557 let inserted_person = Person::create(&conn, &new_person).unwrap();
559 let new_person_2 = PersonForm {
561 ..PersonForm::default()
564 let inserted_person_2 = Person::create(&conn, &new_person_2).unwrap();
566 let new_community = CommunityForm {
567 name: "test community 5".to_string(),
568 title: "nada".to_owned(),
569 ..CommunityForm::default()
572 let inserted_community = Community::create(&conn, &new_community).unwrap();
574 let new_post = PostForm {
575 name: "A test post 2".into(),
576 creator_id: inserted_person.id,
577 community_id: inserted_community.id,
578 ..PostForm::default()
581 let inserted_post = Post::create(&conn, &new_post).unwrap();
583 let comment_form = CommentForm {
584 content: "A test comment 32".into(),
585 creator_id: inserted_person.id,
586 post_id: inserted_post.id,
587 ..CommentForm::default()
590 let inserted_comment = Comment::create(&conn, &comment_form).unwrap();
592 let comment_form_2 = CommentForm {
593 content: "A test blocked comment".into(),
594 creator_id: inserted_person_2.id,
595 post_id: inserted_post.id,
596 parent_id: Some(inserted_comment.id),
597 ..CommentForm::default()
600 let inserted_comment_2 = Comment::create(&conn, &comment_form_2).unwrap();
602 let timmy_blocks_sara_form = PersonBlockForm {
603 person_id: inserted_person.id,
604 target_id: inserted_person_2.id,
607 let inserted_block = PersonBlock::block(&conn, &timmy_blocks_sara_form).unwrap();
609 let expected_block = PersonBlock {
610 id: inserted_block.id,
611 person_id: inserted_person.id,
612 target_id: inserted_person_2.id,
613 published: inserted_block.published,
616 assert_eq!(expected_block, inserted_block);
618 let comment_like_form = CommentLikeForm {
619 comment_id: inserted_comment.id,
620 post_id: inserted_post.id,
621 person_id: inserted_person.id,
625 let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
627 let agg = CommentAggregates::read(&conn, inserted_comment.id).unwrap();
629 let expected_comment_view_no_person = CommentView {
630 creator_banned_from_community: false,
632 subscribed: SubscribedType::NotSubscribed,
634 creator_blocked: false,
636 id: inserted_comment.id,
637 content: "A test comment 32".into(),
638 creator_id: inserted_person.id,
639 post_id: inserted_post.id,
644 published: inserted_comment.published,
645 ap_id: inserted_comment.ap_id,
649 creator: PersonSafe {
650 id: inserted_person.id,
651 name: "timmy".into(),
653 published: inserted_person.published,
655 actor_id: inserted_person.actor_id.to_owned(),
664 inbox_url: inserted_person.inbox_url.to_owned(),
665 shared_inbox_url: None,
666 matrix_user_id: None,
671 id: inserted_post.id,
672 name: inserted_post.name.to_owned(),
673 creator_id: inserted_person.id,
676 published: inserted_post.published,
678 community_id: inserted_community.id,
685 embed_description: None,
686 embed_video_url: None,
688 ap_id: inserted_post.ap_id.to_owned(),
691 community: CommunitySafe {
692 id: inserted_community.id,
693 name: "test community 5".to_string(),
698 actor_id: inserted_community.actor_id.to_owned(),
700 title: "nada".to_owned(),
705 posting_restricted_to_mods: false,
706 published: inserted_community.published,
708 counts: CommentAggregates {
710 comment_id: inserted_comment.id,
714 published: agg.published,
718 let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
719 expected_comment_view_with_person.my_vote = Some(1);
721 let read_comment_views_no_person = CommentQueryBuilder::create(&conn)
722 .post_id(inserted_post.id)
726 let read_comment_views_with_person = CommentQueryBuilder::create(&conn)
727 .post_id(inserted_post.id)
728 .my_person_id(inserted_person.id)
732 let read_comment_from_blocked_person =
733 CommentView::read(&conn, inserted_comment_2.id, Some(inserted_person.id)).unwrap();
735 let like_removed = CommentLike::remove(&conn, inserted_person.id, inserted_comment.id).unwrap();
736 let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap();
737 Comment::delete(&conn, inserted_comment_2.id).unwrap();
738 Post::delete(&conn, inserted_post.id).unwrap();
739 Community::delete(&conn, inserted_community.id).unwrap();
740 Person::delete(&conn, inserted_person.id).unwrap();
741 Person::delete(&conn, inserted_person_2.id).unwrap();
743 // Make sure its 1, not showing the blocked comment
744 assert_eq!(1, read_comment_views_with_person.len());
747 expected_comment_view_no_person,
748 read_comment_views_no_person[1]
751 expected_comment_view_with_person,
752 read_comment_views_with_person[0]
755 // Make sure block set the creator blocked
756 assert!(read_comment_from_blocked_person.creator_blocked);
758 assert_eq!(1, num_deleted);
759 assert_eq!(1, like_removed);