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, CommunityPersonBan, CommunitySafe},
30 person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1},
41 #[derive(Debug, PartialEq, Serialize, Clone)]
42 pub struct CommentView {
44 pub creator: PersonSafe,
45 pub recipient: Option<PersonSafeAlias1>, // Left joins to comment and person
47 pub community: CommunitySafe,
48 pub counts: CommentAggregates,
49 pub creator_banned_from_community: bool, // Left Join to CommunityPersonBan
50 pub subscribed: bool, // Left join to CommunityFollower
51 pub saved: bool, // Left join to CommentSaved
52 pub my_vote: Option<i16>, // Left join to CommentLike
55 type CommentViewTuple = (
58 Option<CommentAlias1>,
59 Option<PersonSafeAlias1>,
63 Option<CommunityPersonBan>,
64 Option<CommunityFollower>,
72 comment_id: CommentId,
73 my_person_id: Option<PersonId>,
74 ) -> Result<Self, Error> {
75 // The left join below will return None in this case
76 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
86 creator_banned_from_community,
92 .inner_join(person::table)
94 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
95 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
96 .inner_join(post::table)
97 .inner_join(community::table.on(post::community_id.eq(community::id)))
98 .inner_join(comment_aggregates::table)
100 community_person_ban::table.on(
102 .eq(community_person_ban::community_id)
103 .and(community_person_ban::person_id.eq(comment::creator_id)),
107 community_follower::table.on(
109 .eq(community_follower::community_id)
110 .and(community_follower::person_id.eq(person_id_join)),
114 comment_saved::table.on(
116 .eq(comment_saved::comment_id)
117 .and(comment_saved::person_id.eq(person_id_join)),
121 comment_like::table.on(
123 .eq(comment_like::comment_id)
124 .and(comment_like::person_id.eq(person_id_join)),
128 comment::all_columns,
129 Person::safe_columns_tuple(),
130 comment_alias_1::all_columns.nullable(),
131 PersonAlias1::safe_columns_tuple().nullable(),
133 Community::safe_columns_tuple(),
134 comment_aggregates::all_columns,
135 community_person_ban::all_columns.nullable(),
136 community_follower::all_columns.nullable(),
137 comment_saved::all_columns.nullable(),
138 comment_like::score.nullable(),
140 .first::<CommentViewTuple>(conn)?;
142 // If a person is given, then my_vote, if None, should be 0, not null
143 // Necessary to differentiate between other person's votes
144 let my_vote = if my_person_id.is_some() && comment_like.is_none() {
157 creator_banned_from_community: creator_banned_from_community.is_some(),
158 subscribed: subscribed.is_some(),
159 saved: saved.is_some(),
164 /// Gets the recipient person id.
165 /// If there is no parent comment, its the post creator
166 pub fn get_recipient_id(&self) -> PersonId {
167 match &self.recipient {
168 Some(parent_commenter) => parent_commenter.id,
169 None => self.post.creator_id,
174 pub struct CommentQueryBuilder<'a> {
175 conn: &'a PgConnection,
176 listing_type: Option<ListingType>,
177 sort: Option<SortType>,
178 community_id: Option<CommunityId>,
179 community_actor_id: Option<DbUrl>,
180 post_id: Option<PostId>,
181 creator_id: Option<PersonId>,
182 recipient_id: Option<PersonId>,
183 my_person_id: Option<PersonId>,
184 search_term: Option<String>,
185 saved_only: Option<bool>,
186 unread_only: Option<bool>,
187 show_bot_accounts: Option<bool>,
192 impl<'a> CommentQueryBuilder<'a> {
193 pub fn create(conn: &'a PgConnection) -> Self {
194 CommentQueryBuilder {
199 community_actor_id: None,
207 show_bot_accounts: None,
213 pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
214 self.listing_type = listing_type.get_optional();
218 pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
219 self.sort = sort.get_optional();
223 pub fn post_id<T: MaybeOptional<PostId>>(mut self, post_id: T) -> Self {
224 self.post_id = post_id.get_optional();
228 pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
229 self.creator_id = creator_id.get_optional();
233 pub fn recipient_id<T: MaybeOptional<PersonId>>(mut self, recipient_id: T) -> Self {
234 self.recipient_id = recipient_id.get_optional();
238 pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
239 self.community_id = community_id.get_optional();
243 pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
244 self.my_person_id = my_person_id.get_optional();
248 pub fn community_actor_id<T: MaybeOptional<DbUrl>>(mut self, community_actor_id: T) -> Self {
249 self.community_actor_id = community_actor_id.get_optional();
253 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
254 self.search_term = search_term.get_optional();
258 pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
259 self.saved_only = saved_only.get_optional();
263 pub fn unread_only<T: MaybeOptional<bool>>(mut self, unread_only: T) -> Self {
264 self.unread_only = unread_only.get_optional();
268 pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
269 self.show_bot_accounts = show_bot_accounts.get_optional();
273 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
274 self.page = page.get_optional();
278 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
279 self.limit = limit.get_optional();
283 pub fn list(self) -> Result<Vec<CommentView>, Error> {
286 // The left join below will return None in this case
287 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
289 let mut query = comment::table
290 .inner_join(person::table)
292 .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
293 .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
294 .inner_join(post::table)
295 .inner_join(community::table.on(post::community_id.eq(community::id)))
296 .inner_join(comment_aggregates::table)
298 community_person_ban::table.on(
300 .eq(community_person_ban::community_id)
301 .and(community_person_ban::person_id.eq(comment::creator_id)),
305 community_follower::table.on(
307 .eq(community_follower::community_id)
308 .and(community_follower::person_id.eq(person_id_join)),
312 comment_saved::table.on(
314 .eq(comment_saved::comment_id)
315 .and(comment_saved::person_id.eq(person_id_join)),
319 comment_like::table.on(
321 .eq(comment_like::comment_id)
322 .and(comment_like::person_id.eq(person_id_join)),
326 comment::all_columns,
327 Person::safe_columns_tuple(),
328 comment_alias_1::all_columns.nullable(),
329 PersonAlias1::safe_columns_tuple().nullable(),
331 Community::safe_columns_tuple(),
332 comment_aggregates::all_columns,
333 community_person_ban::all_columns.nullable(),
334 community_follower::all_columns.nullable(),
335 comment_saved::all_columns.nullable(),
336 comment_like::score.nullable(),
341 if let Some(recipient_id) = self.recipient_id {
343 // TODO needs lots of testing
344 .filter(person_alias_1::id.eq(recipient_id)) // Gets the comment replies
348 .and(post::creator_id.eq(recipient_id)),
349 ) // Gets the top level replies
350 .filter(comment::deleted.eq(false))
351 .filter(comment::removed.eq(false));
354 if self.unread_only.unwrap_or(false) {
355 query = query.filter(comment::read.eq(false));
358 if let Some(creator_id) = self.creator_id {
359 query = query.filter(comment::creator_id.eq(creator_id));
362 if let Some(community_id) = self.community_id {
363 query = query.filter(post::community_id.eq(community_id));
366 if let Some(community_actor_id) = self.community_actor_id {
367 query = query.filter(community::actor_id.eq(community_actor_id))
370 if let Some(post_id) = self.post_id {
371 query = query.filter(comment::post_id.eq(post_id));
374 if let Some(search_term) = self.search_term {
375 query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
378 if let Some(listing_type) = self.listing_type {
379 query = match listing_type {
380 ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
381 ListingType::Local => query.filter(community::local.eq(true)),
386 if self.saved_only.unwrap_or(false) {
387 query = query.filter(comment_saved::id.is_not_null());
390 if !self.show_bot_accounts.unwrap_or(true) {
391 query = query.filter(person::bot_account.eq(false));
394 query = match self.sort.unwrap_or(SortType::New) {
395 SortType::Hot | SortType::Active => query
396 .order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
397 .then_order_by(comment_aggregates::published.desc()),
398 SortType::New | SortType::MostComments | SortType::NewComments => {
399 query.order_by(comment::published.desc())
401 SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
402 SortType::TopYear => query
403 .filter(comment::published.gt(now - 1.years()))
404 .order_by(comment_aggregates::score.desc()),
405 SortType::TopMonth => query
406 .filter(comment::published.gt(now - 1.months()))
407 .order_by(comment_aggregates::score.desc()),
408 SortType::TopWeek => query
409 .filter(comment::published.gt(now - 1.weeks()))
410 .order_by(comment_aggregates::score.desc()),
411 SortType::TopDay => query
412 .filter(comment::published.gt(now - 1.days()))
413 .order_by(comment_aggregates::score.desc()),
416 let (limit, offset) = limit_and_offset(self.page, self.limit);
418 // Note: deleted and removed comments are done on the front side
422 .load::<CommentViewTuple>(self.conn)?;
424 Ok(CommentView::from_tuple_to_vec(res))
428 impl ViewToVec for CommentView {
429 type DbTuple = CommentViewTuple;
430 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
434 comment: a.0.to_owned(),
435 creator: a.1.to_owned(),
436 recipient: a.3.to_owned(),
437 post: a.4.to_owned(),
438 community: a.5.to_owned(),
439 counts: a.6.to_owned(),
440 creator_banned_from_community: a.7.is_some(),
441 subscribed: a.8.is_some(),
442 saved: a.9.is_some(),
445 .collect::<Vec<Self>>()
451 use crate::comment_view::*;
452 use lemmy_db_queries::{
453 aggregates::comment_aggregates::CommentAggregates,
454 establish_unpooled_connection,
458 use lemmy_db_schema::source::{comment::*, community::*, person::*, post::*};
459 use serial_test::serial;
464 let conn = establish_unpooled_connection();
466 let new_person = PersonForm {
467 name: "timmy".into(),
468 ..PersonForm::default()
471 let inserted_person = Person::create(&conn, &new_person).unwrap();
473 let new_community = CommunityForm {
474 name: "test community 5".to_string(),
475 title: "nada".to_owned(),
476 ..CommunityForm::default()
479 let inserted_community = Community::create(&conn, &new_community).unwrap();
481 let new_post = PostForm {
482 name: "A test post 2".into(),
483 creator_id: inserted_person.id,
484 community_id: inserted_community.id,
485 ..PostForm::default()
488 let inserted_post = Post::create(&conn, &new_post).unwrap();
490 let comment_form = CommentForm {
491 content: "A test comment 32".into(),
492 creator_id: inserted_person.id,
493 post_id: inserted_post.id,
494 ..CommentForm::default()
497 let inserted_comment = Comment::create(&conn, &comment_form).unwrap();
499 let comment_like_form = CommentLikeForm {
500 comment_id: inserted_comment.id,
501 post_id: inserted_post.id,
502 person_id: inserted_person.id,
506 let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
508 let agg = CommentAggregates::read(&conn, inserted_comment.id).unwrap();
510 let expected_comment_view_no_person = CommentView {
511 creator_banned_from_community: false,
516 id: inserted_comment.id,
517 content: "A test comment 32".into(),
518 creator_id: inserted_person.id,
519 post_id: inserted_post.id,
524 published: inserted_comment.published,
525 ap_id: inserted_comment.ap_id,
529 creator: PersonSafe {
530 id: inserted_person.id,
531 name: "timmy".into(),
533 published: inserted_person.published,
535 actor_id: inserted_person.actor_id.to_owned(),
544 inbox_url: inserted_person.inbox_url.to_owned(),
545 shared_inbox_url: None,
546 matrix_user_id: None,
550 id: inserted_post.id,
551 name: inserted_post.name.to_owned(),
552 creator_id: inserted_person.id,
555 published: inserted_post.published,
557 community_id: inserted_community.id,
564 embed_description: None,
567 ap_id: inserted_post.ap_id.to_owned(),
570 community: CommunitySafe {
571 id: inserted_community.id,
572 name: "test community 5".to_string(),
577 actor_id: inserted_community.actor_id.to_owned(),
579 title: "nada".to_owned(),
583 published: inserted_community.published,
585 counts: CommentAggregates {
587 comment_id: inserted_comment.id,
591 published: agg.published,
595 let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
596 expected_comment_view_with_person.my_vote = Some(1);
598 let read_comment_views_no_person = CommentQueryBuilder::create(&conn)
599 .post_id(inserted_post.id)
603 let read_comment_views_with_person = CommentQueryBuilder::create(&conn)
604 .post_id(inserted_post.id)
605 .my_person_id(inserted_person.id)
609 let like_removed = CommentLike::remove(&conn, inserted_person.id, inserted_comment.id).unwrap();
610 let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap();
611 Post::delete(&conn, inserted_post.id).unwrap();
612 Community::delete(&conn, inserted_community.id).unwrap();
613 Person::delete(&conn, inserted_person.id).unwrap();
616 expected_comment_view_no_person,
617 read_comment_views_no_person[0]
620 expected_comment_view_with_person,
621 read_comment_views_with_person[0]
623 assert_eq!(1, num_deleted);
624 assert_eq!(1, like_removed);