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},
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: subscribed.is_some(),
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 {
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(community_id) = self.community_id {
418 query = query.filter(post::community_id.eq(community_id));
421 if let Some(community_actor_id) = self.community_actor_id {
422 query = query.filter(community::actor_id.eq(community_actor_id))
425 if let Some(post_id) = self.post_id {
426 query = query.filter(comment::post_id.eq(post_id));
429 if let Some(search_term) = self.search_term {
430 query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
433 if let Some(listing_type) = self.listing_type {
435 ListingType::Subscribed => {
436 query = query.filter(community_follower::person_id.is_not_null())
437 } // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
438 ListingType::Local => {
439 query = query.filter(community::local.eq(true)).filter(
442 .or(community_follower::person_id.eq(person_id_join)),
445 ListingType::All => {
446 query = query.filter(
449 .or(community_follower::person_id.eq(person_id_join)),
452 ListingType::Community => {}
456 if self.saved_only.unwrap_or(false) {
457 query = query.filter(comment_saved::id.is_not_null());
460 if !self.show_bot_accounts.unwrap_or(true) {
461 query = query.filter(person::bot_account.eq(false));
464 query = match self.sort.unwrap_or(SortType::New) {
465 SortType::Hot | SortType::Active => query
466 .order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
467 .then_order_by(comment_aggregates::published.desc()),
468 SortType::New | SortType::MostComments | SortType::NewComments => {
469 query.order_by(comment::published.desc())
471 SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
472 SortType::TopYear => query
473 .filter(comment::published.gt(now - 1.years()))
474 .order_by(comment_aggregates::score.desc()),
475 SortType::TopMonth => query
476 .filter(comment::published.gt(now - 1.months()))
477 .order_by(comment_aggregates::score.desc()),
478 SortType::TopWeek => query
479 .filter(comment::published.gt(now - 1.weeks()))
480 .order_by(comment_aggregates::score.desc()),
481 SortType::TopDay => query
482 .filter(comment::published.gt(now - 1.days()))
483 .order_by(comment_aggregates::score.desc()),
486 // Don't show blocked communities or persons
487 if self.my_person_id.is_some() {
488 query = query.filter(community_block::person_id.is_null());
489 query = query.filter(person_block::person_id.is_null());
492 let (limit, offset) = limit_and_offset(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: a.8.is_some(),
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,
535 use serial_test::serial;
540 let conn = establish_unpooled_connection();
542 let new_person = PersonForm {
543 name: "timmy".into(),
544 ..PersonForm::default()
547 let inserted_person = Person::create(&conn, &new_person).unwrap();
549 let new_person_2 = PersonForm {
551 ..PersonForm::default()
554 let inserted_person_2 = Person::create(&conn, &new_person_2).unwrap();
556 let new_community = CommunityForm {
557 name: "test community 5".to_string(),
558 title: "nada".to_owned(),
559 ..CommunityForm::default()
562 let inserted_community = Community::create(&conn, &new_community).unwrap();
564 let new_post = PostForm {
565 name: "A test post 2".into(),
566 creator_id: inserted_person.id,
567 community_id: inserted_community.id,
568 ..PostForm::default()
571 let inserted_post = Post::create(&conn, &new_post).unwrap();
573 let comment_form = CommentForm {
574 content: "A test comment 32".into(),
575 creator_id: inserted_person.id,
576 post_id: inserted_post.id,
577 ..CommentForm::default()
580 let inserted_comment = Comment::create(&conn, &comment_form).unwrap();
582 let comment_form_2 = CommentForm {
583 content: "A test blocked comment".into(),
584 creator_id: inserted_person_2.id,
585 post_id: inserted_post.id,
586 parent_id: Some(inserted_comment.id),
587 ..CommentForm::default()
590 let inserted_comment_2 = Comment::create(&conn, &comment_form_2).unwrap();
592 let timmy_blocks_sara_form = PersonBlockForm {
593 person_id: inserted_person.id,
594 target_id: inserted_person_2.id,
597 let inserted_block = PersonBlock::block(&conn, &timmy_blocks_sara_form).unwrap();
599 let expected_block = PersonBlock {
600 id: inserted_block.id,
601 person_id: inserted_person.id,
602 target_id: inserted_person_2.id,
603 published: inserted_block.published,
606 assert_eq!(expected_block, inserted_block);
608 let comment_like_form = CommentLikeForm {
609 comment_id: inserted_comment.id,
610 post_id: inserted_post.id,
611 person_id: inserted_person.id,
615 let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
617 let agg = CommentAggregates::read(&conn, inserted_comment.id).unwrap();
619 let expected_comment_view_no_person = CommentView {
620 creator_banned_from_community: false,
624 creator_blocked: false,
626 id: inserted_comment.id,
627 content: "A test comment 32".into(),
628 creator_id: inserted_person.id,
629 post_id: inserted_post.id,
634 published: inserted_comment.published,
635 ap_id: inserted_comment.ap_id,
639 creator: PersonSafe {
640 id: inserted_person.id,
641 name: "timmy".into(),
643 published: inserted_person.published,
645 actor_id: inserted_person.actor_id.to_owned(),
654 inbox_url: inserted_person.inbox_url.to_owned(),
655 shared_inbox_url: None,
656 matrix_user_id: None,
661 id: inserted_post.id,
662 name: inserted_post.name.to_owned(),
663 creator_id: inserted_person.id,
666 published: inserted_post.published,
668 community_id: inserted_community.id,
675 embed_description: None,
678 ap_id: inserted_post.ap_id.to_owned(),
681 community: CommunitySafe {
682 id: inserted_community.id,
683 name: "test community 5".to_string(),
688 actor_id: inserted_community.actor_id.to_owned(),
690 title: "nada".to_owned(),
695 posting_restricted_to_mods: false,
696 published: inserted_community.published,
698 counts: CommentAggregates {
700 comment_id: inserted_comment.id,
704 published: agg.published,
708 let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
709 expected_comment_view_with_person.my_vote = Some(1);
711 let read_comment_views_no_person = CommentQueryBuilder::create(&conn)
712 .post_id(inserted_post.id)
716 let read_comment_views_with_person = CommentQueryBuilder::create(&conn)
717 .post_id(inserted_post.id)
718 .my_person_id(inserted_person.id)
722 let read_comment_from_blocked_person =
723 CommentView::read(&conn, inserted_comment_2.id, Some(inserted_person.id)).unwrap();
725 let like_removed = CommentLike::remove(&conn, inserted_person.id, inserted_comment.id).unwrap();
726 let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap();
727 Comment::delete(&conn, inserted_comment_2.id).unwrap();
728 Post::delete(&conn, inserted_post.id).unwrap();
729 Community::delete(&conn, inserted_community.id).unwrap();
730 Person::delete(&conn, inserted_person.id).unwrap();
731 Person::delete(&conn, inserted_person_2.id).unwrap();
733 // Make sure its 1, not showing the blocked comment
734 assert_eq!(1, read_comment_views_with_person.len());
737 expected_comment_view_no_person,
738 read_comment_views_no_person[1]
741 expected_comment_view_with_person,
742 read_comment_views_with_person[0]
745 // Make sure block set the creator blocked
746 assert!(read_comment_from_blocked_person.creator_blocked);
748 assert_eq!(1, num_deleted);
749 assert_eq!(1, like_removed);