1 use diesel::{result::Error, *};
2 use lemmy_db_queries::{
3 aggregates::comment_aggregates::CommentAggregates,
13 use lemmy_db_schema::{
28 comment::{Comment, CommentAlias1, CommentSaved},
29 community::{Community, CommunityFollower, CommunitySafe, CommunityPersonBan},
31 person::{PersonAlias1, PersonSafe, PersonSafeAlias1, Person},
36 #[derive(Debug, PartialEq, Serialize, Clone)]
37 pub struct CommentView {
39 pub creator: PersonSafe,
40 pub recipient: Option<PersonSafeAlias1>, // Left joins to comment and person
42 pub community: CommunitySafe,
43 pub counts: CommentAggregates,
44 pub creator_banned_from_community: bool, // Left Join to CommunityPersonBan
45 pub subscribed: bool, // Left join to CommunityFollower
46 pub saved: bool, // Left join to CommentSaved
47 pub my_vote: Option<i16>, // Left join to CommentLike
50 type CommentViewTuple = (
53 Option<CommentAlias1>,
54 Option<PersonSafeAlias1>,
58 Option<CommunityPersonBan>,
59 Option<CommunityFollower>,
68 my_person_id: Option<i32>,
69 ) -> Result<Self, Error> {
70 // The left join below will return None in this case
71 let person_id_join = my_person_id.unwrap_or(-1);
81 creator_banned_from_community,
87 .inner_join(person::table)
89 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
90 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
91 .inner_join(post::table)
92 .inner_join(community::table.on(post::community_id.eq(community::id)))
93 .inner_join(comment_aggregates::table)
95 community_person_ban::table.on(
97 .eq(community_person_ban::community_id)
98 .and(community_person_ban::person_id.eq(comment::creator_id)),
102 community_follower::table.on(
104 .eq(community_follower::community_id)
105 .and(community_follower::person_id.eq(person_id_join)),
109 comment_saved::table.on(
111 .eq(comment_saved::comment_id)
112 .and(comment_saved::person_id.eq(person_id_join)),
116 comment_like::table.on(
118 .eq(comment_like::comment_id)
119 .and(comment_like::person_id.eq(person_id_join)),
123 comment::all_columns,
124 Person::safe_columns_tuple(),
125 comment_alias_1::all_columns.nullable(),
126 PersonAlias1::safe_columns_tuple().nullable(),
128 Community::safe_columns_tuple(),
129 comment_aggregates::all_columns,
130 community_person_ban::all_columns.nullable(),
131 community_follower::all_columns.nullable(),
132 comment_saved::all_columns.nullable(),
133 comment_like::score.nullable(),
135 .first::<CommentViewTuple>(conn)?;
137 // If a person is given, then my_vote, if None, should be 0, not null
138 // Necessary to differentiate between other person's votes
139 let my_vote = if my_person_id.is_some() && comment_like.is_none() {
152 creator_banned_from_community: creator_banned_from_community.is_some(),
153 subscribed: subscribed.is_some(),
154 saved: saved.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) -> i32 {
162 match &self.recipient {
163 Some(parent_commenter) => parent_commenter.id,
164 None => self.post.creator_id,
169 pub struct CommentQueryBuilder<'a> {
170 conn: &'a PgConnection,
171 listing_type: ListingType,
173 community_id: Option<i32>,
174 community_name: Option<String>,
175 post_id: Option<i32>,
176 creator_id: Option<i32>,
177 recipient_id: Option<i32>,
178 my_person_id: Option<i32>,
179 search_term: Option<String>,
186 impl<'a> CommentQueryBuilder<'a> {
187 pub fn create(conn: &'a PgConnection) -> Self {
188 CommentQueryBuilder {
190 listing_type: ListingType::All,
191 sort: &SortType::New,
193 community_name: None,
206 pub fn listing_type(mut self, listing_type: ListingType) -> Self {
207 self.listing_type = listing_type;
211 pub fn sort(mut self, sort: &'a SortType) -> Self {
216 pub fn post_id<T: MaybeOptional<i32>>(mut self, post_id: T) -> Self {
217 self.post_id = post_id.get_optional();
221 pub fn creator_id<T: MaybeOptional<i32>>(mut self, creator_id: T) -> Self {
222 self.creator_id = creator_id.get_optional();
226 pub fn recipient_id<T: MaybeOptional<i32>>(mut self, recipient_id: T) -> Self {
227 self.recipient_id = recipient_id.get_optional();
231 pub fn community_id<T: MaybeOptional<i32>>(mut self, community_id: T) -> Self {
232 self.community_id = community_id.get_optional();
236 pub fn my_person_id<T: MaybeOptional<i32>>(mut self, my_person_id: T) -> Self {
237 self.my_person_id = my_person_id.get_optional();
241 pub fn community_name<T: MaybeOptional<String>>(mut self, community_name: T) -> Self {
242 self.community_name = community_name.get_optional();
246 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
247 self.search_term = search_term.get_optional();
251 pub fn saved_only(mut self, saved_only: bool) -> Self {
252 self.saved_only = saved_only;
256 pub fn unread_only(mut self, unread_only: bool) -> Self {
257 self.unread_only = unread_only;
261 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
262 self.page = page.get_optional();
266 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
267 self.limit = limit.get_optional();
271 pub fn list(self) -> Result<Vec<CommentView>, Error> {
274 // The left join below will return None in this case
275 let person_id_join = self.my_person_id.unwrap_or(-1);
277 let mut query = comment::table
278 .inner_join(person::table)
280 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
281 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
282 .inner_join(post::table)
283 .inner_join(community::table.on(post::community_id.eq(community::id)))
284 .inner_join(comment_aggregates::table)
286 community_person_ban::table.on(
288 .eq(community_person_ban::community_id)
289 .and(community_person_ban::person_id.eq(comment::creator_id)),
293 community_follower::table.on(
295 .eq(community_follower::community_id)
296 .and(community_follower::person_id.eq(person_id_join)),
300 comment_saved::table.on(
302 .eq(comment_saved::comment_id)
303 .and(comment_saved::person_id.eq(person_id_join)),
307 comment_like::table.on(
309 .eq(comment_like::comment_id)
310 .and(comment_like::person_id.eq(person_id_join)),
314 comment::all_columns,
315 Person::safe_columns_tuple(),
316 comment_alias_1::all_columns.nullable(),
317 PersonAlias1::safe_columns_tuple().nullable(),
319 Community::safe_columns_tuple(),
320 comment_aggregates::all_columns,
321 community_person_ban::all_columns.nullable(),
322 community_follower::all_columns.nullable(),
323 comment_saved::all_columns.nullable(),
324 comment_like::score.nullable(),
329 if let Some(recipient_id) = self.recipient_id {
331 // TODO needs lots of testing
332 .filter(person_alias_1::id.eq(recipient_id)) // Gets the comment replies
336 .and(post::creator_id.eq(recipient_id)),
337 ) // Gets the top level replies
338 .filter(comment::deleted.eq(false))
339 .filter(comment::removed.eq(false));
342 if self.unread_only {
343 query = query.filter(comment::read.eq(false));
346 if let Some(creator_id) = self.creator_id {
347 query = query.filter(comment::creator_id.eq(creator_id));
350 if let Some(community_id) = self.community_id {
351 query = query.filter(post::community_id.eq(community_id));
354 if let Some(community_name) = self.community_name {
356 .filter(community::name.eq(community_name))
357 .filter(comment::local.eq(true));
360 if let Some(post_id) = self.post_id {
361 query = query.filter(comment::post_id.eq(post_id));
364 if let Some(search_term) = self.search_term {
365 query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
368 query = match self.listing_type {
369 // ListingType::Subscribed => query.filter(community_follower::subscribed.eq(true)),
370 ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::user_id.eq(user_id_join)),
371 ListingType::Local => query.filter(community::local.eq(true)),
376 query = query.filter(comment_saved::id.is_not_null());
379 query = match self.sort {
380 SortType::Hot | SortType::Active => query
381 .order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
382 .then_order_by(comment_aggregates::published.desc()),
383 SortType::New | SortType::MostComments | SortType::NewComments => {
384 query.order_by(comment::published.desc())
386 SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
387 SortType::TopYear => query
388 .filter(comment::published.gt(now - 1.years()))
389 .order_by(comment_aggregates::score.desc()),
390 SortType::TopMonth => query
391 .filter(comment::published.gt(now - 1.months()))
392 .order_by(comment_aggregates::score.desc()),
393 SortType::TopWeek => query
394 .filter(comment::published.gt(now - 1.weeks()))
395 .order_by(comment_aggregates::score.desc()),
396 SortType::TopDay => query
397 .filter(comment::published.gt(now - 1.days()))
398 .order_by(comment_aggregates::score.desc()),
401 let (limit, offset) = limit_and_offset(self.page, self.limit);
403 // Note: deleted and removed comments are done on the front side
407 .load::<CommentViewTuple>(self.conn)?;
409 Ok(CommentView::from_tuple_to_vec(res))
413 impl ViewToVec for CommentView {
414 type DbTuple = CommentViewTuple;
415 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
419 comment: a.0.to_owned(),
420 creator: a.1.to_owned(),
421 recipient: a.3.to_owned(),
422 post: a.4.to_owned(),
423 community: a.5.to_owned(),
424 counts: a.6.to_owned(),
425 creator_banned_from_community: a.7.is_some(),
426 subscribed: a.8.is_some(),
427 saved: a.9.is_some(),
430 .collect::<Vec<Self>>()
436 use crate::comment_view::*;
437 use lemmy_db_queries::{
438 aggregates::comment_aggregates::CommentAggregates,
439 establish_unpooled_connection,
443 use lemmy_db_schema::source::{comment::*, community::*, post::*, person::*};
444 use serial_test::serial;
449 let conn = establish_unpooled_connection();
451 let new_person = PersonForm {
452 name: "thommy".into(),
453 preferred_username: None,
465 last_refreshed_at: None,
467 shared_inbox_url: None,
470 let inserted_person = Person::create(&conn, &new_person).unwrap();
472 let new_community = CommunityForm {
473 name: "test community 5".to_string(),
474 title: "nada".to_owned(),
476 creator_id: inserted_person.id,
485 last_refreshed_at: None,
491 shared_inbox_url: None,
494 let inserted_community = Community::create(&conn, &new_community).unwrap();
496 let new_post = PostForm {
497 name: "A test post 2".into(),
498 creator_id: inserted_person.id,
501 community_id: inserted_community.id,
509 embed_description: None,
517 let inserted_post = Post::create(&conn, &new_post).unwrap();
519 let comment_form = CommentForm {
520 content: "A test comment 32".into(),
521 creator_id: inserted_person.id,
522 post_id: inserted_post.id,
533 let inserted_comment = Comment::create(&conn, &comment_form).unwrap();
535 let comment_like_form = CommentLikeForm {
536 comment_id: inserted_comment.id,
537 post_id: inserted_post.id,
538 person_id: inserted_person.id,
542 let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
544 let agg = CommentAggregates::read(&conn, inserted_comment.id).unwrap();
546 let expected_comment_view_no_person = CommentView {
547 creator_banned_from_community: false,
552 id: inserted_comment.id,
553 content: "A test comment 32".into(),
554 creator_id: inserted_person.id,
555 post_id: inserted_post.id,
560 published: inserted_comment.published,
561 ap_id: inserted_comment.ap_id,
565 creator: PersonSafe {
566 id: inserted_person.id,
567 name: "timmy".into(),
568 preferred_username: None,
569 published: inserted_person.published,
571 actor_id: inserted_person.actor_id.to_owned(),
578 inbox_url: inserted_person.inbox_url.to_owned(),
579 shared_inbox_url: None,
583 id: inserted_post.id,
584 name: inserted_post.name.to_owned(),
585 creator_id: inserted_person.id,
588 published: inserted_post.published,
590 community_id: inserted_community.id,
597 embed_description: None,
600 ap_id: inserted_post.ap_id.to_owned(),
603 community: CommunitySafe {
604 id: inserted_community.id,
605 name: "test community 5".to_string(),
610 actor_id: inserted_community.actor_id.to_owned(),
612 title: "nada".to_owned(),
614 creator_id: inserted_person.id,
617 published: inserted_community.published,
619 counts: CommentAggregates {
621 comment_id: inserted_comment.id,
625 published: agg.published,
629 let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
630 expected_comment_view_with_person.my_vote = Some(1);
632 let read_comment_views_no_person = CommentQueryBuilder::create(&conn)
633 .post_id(inserted_post.id)
637 let read_comment_views_with_person = CommentQueryBuilder::create(&conn)
638 .post_id(inserted_post.id)
639 .my_person_id(inserted_person.id)
643 let like_removed = CommentLike::remove(&conn, inserted_person.id, inserted_comment.id).unwrap();
644 let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap();
645 Post::delete(&conn, inserted_post.id).unwrap();
646 Community::delete(&conn, inserted_community.id).unwrap();
647 Person::delete(&conn, inserted_person.id).unwrap();
649 assert_eq!(expected_comment_view_no_person, read_comment_views_no_person[0]);
651 expected_comment_view_with_person,
652 read_comment_views_with_person[0]
654 assert_eq!(1, num_deleted);
655 assert_eq!(1, like_removed);