]> Untitled Git - lemmy.git/blob - crates/db_views/src/comment_view.rs
Add cargo feature for building lemmy_api_common with mininum deps (#2243)
[lemmy.git] / crates / db_views / src / comment_view.rs
1 use crate::structs::CommentView;
2 use diesel::{dsl::*, result::Error, *};
3 use lemmy_db_schema::{
4   aggregates::structs::CommentAggregates,
5   newtypes::{CommentId, CommunityId, DbUrl, PersonId, PostId},
6   schema::{
7     comment,
8     comment_aggregates,
9     comment_alias_1,
10     comment_like,
11     comment_saved,
12     community,
13     community_block,
14     community_follower,
15     community_person_ban,
16     person,
17     person_alias_1,
18     person_block,
19     post,
20   },
21   source::{
22     comment::{Comment, CommentAlias1, CommentSaved},
23     community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
24     person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1},
25     person_block::PersonBlock,
26     post::Post,
27   },
28   traits::{MaybeOptional, ToSafe, ViewToVec},
29   utils::{functions::hot_rank, fuzzy_search, limit_and_offset, ListingType, SortType},
30 };
31
32 type CommentViewTuple = (
33   Comment,
34   PersonSafe,
35   Option<CommentAlias1>,
36   Option<PersonSafeAlias1>,
37   Post,
38   CommunitySafe,
39   CommentAggregates,
40   Option<CommunityPersonBan>,
41   Option<CommunityFollower>,
42   Option<CommentSaved>,
43   Option<PersonBlock>,
44   Option<i16>,
45 );
46
47 impl CommentView {
48   pub fn read(
49     conn: &PgConnection,
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));
55
56     let (
57       comment,
58       creator,
59       _parent_comment,
60       recipient,
61       post,
62       community,
63       counts,
64       creator_banned_from_community,
65       subscribed,
66       saved,
67       creator_blocked,
68       comment_like,
69     ) = comment::table
70       .find(comment_id)
71       .inner_join(person::table)
72       // recipient here
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)
78       .left_join(
79         community_person_ban::table.on(
80           community::id
81             .eq(community_person_ban::community_id)
82             .and(community_person_ban::person_id.eq(comment::creator_id))
83             .and(
84               community_person_ban::expires
85                 .is_null()
86                 .or(community_person_ban::expires.gt(now)),
87             ),
88         ),
89       )
90       .left_join(
91         community_follower::table.on(
92           post::community_id
93             .eq(community_follower::community_id)
94             .and(community_follower::person_id.eq(person_id_join)),
95         ),
96       )
97       .left_join(
98         comment_saved::table.on(
99           comment::id
100             .eq(comment_saved::comment_id)
101             .and(comment_saved::person_id.eq(person_id_join)),
102         ),
103       )
104       .left_join(
105         person_block::table.on(
106           comment::creator_id
107             .eq(person_block::target_id)
108             .and(person_block::person_id.eq(person_id_join)),
109         ),
110       )
111       .left_join(
112         comment_like::table.on(
113           comment::id
114             .eq(comment_like::comment_id)
115             .and(comment_like::person_id.eq(person_id_join)),
116         ),
117       )
118       .select((
119         comment::all_columns,
120         Person::safe_columns_tuple(),
121         comment_alias_1::all_columns.nullable(),
122         PersonAlias1::safe_columns_tuple().nullable(),
123         post::all_columns,
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(),
131       ))
132       .first::<CommentViewTuple>(conn)?;
133
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() {
137       Some(0)
138     } else {
139       comment_like
140     };
141
142     Ok(CommentView {
143       comment,
144       recipient,
145       post,
146       creator,
147       community,
148       counts,
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(),
153       my_vote,
154     })
155   }
156
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,
163     }
164   }
165
166   /// Gets the number of unread replies
167   pub fn get_unread_replies(conn: &PgConnection, my_person_id: PersonId) -> Result<i64, Error> {
168     use diesel::dsl::*;
169
170     comment::table
171       // recipient here
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)))
176       .left_join(
177         person_block::table.on(
178           comment::creator_id
179             .eq(person_block::target_id)
180             .and(person_block::person_id.eq(my_person_id)),
181         ),
182       )
183       .left_join(
184         community_block::table.on(
185           community::id
186             .eq(community_block::community_id)
187             .and(community_block::person_id.eq(my_person_id)),
188         ),
189       )
190       .filter(person_alias_1::id.eq(my_person_id)) // Gets the comment replies
191       .or_filter(
192         comment::parent_id
193           .is_null()
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))
203       .first::<i64>(conn)
204   }
205 }
206
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>,
221   page: Option<i64>,
222   limit: Option<i64>,
223 }
224
225 impl<'a> CommentQueryBuilder<'a> {
226   pub fn create(conn: &'a PgConnection) -> Self {
227     CommentQueryBuilder {
228       conn,
229       listing_type: None,
230       sort: None,
231       community_id: None,
232       community_actor_id: None,
233       post_id: None,
234       creator_id: None,
235       recipient_id: None,
236       my_person_id: None,
237       search_term: None,
238       saved_only: None,
239       unread_only: None,
240       show_bot_accounts: None,
241       page: None,
242       limit: None,
243     }
244   }
245
246   pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
247     self.listing_type = listing_type.get_optional();
248     self
249   }
250
251   pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
252     self.sort = sort.get_optional();
253     self
254   }
255
256   pub fn post_id<T: MaybeOptional<PostId>>(mut self, post_id: T) -> Self {
257     self.post_id = post_id.get_optional();
258     self
259   }
260
261   pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
262     self.creator_id = creator_id.get_optional();
263     self
264   }
265
266   pub fn recipient_id<T: MaybeOptional<PersonId>>(mut self, recipient_id: T) -> Self {
267     self.recipient_id = recipient_id.get_optional();
268     self
269   }
270
271   pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
272     self.community_id = community_id.get_optional();
273     self
274   }
275
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();
278     self
279   }
280
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();
283     self
284   }
285
286   pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
287     self.search_term = search_term.get_optional();
288     self
289   }
290
291   pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
292     self.saved_only = saved_only.get_optional();
293     self
294   }
295
296   pub fn unread_only<T: MaybeOptional<bool>>(mut self, unread_only: T) -> Self {
297     self.unread_only = unread_only.get_optional();
298     self
299   }
300
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();
303     self
304   }
305
306   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
307     self.page = page.get_optional();
308     self
309   }
310
311   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
312     self.limit = limit.get_optional();
313     self
314   }
315
316   pub fn list(self) -> Result<Vec<CommentView>, Error> {
317     use diesel::dsl::*;
318
319     // The left join below will return None in this case
320     let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
321
322     let mut query = comment::table
323       .inner_join(person::table)
324       // recipient here
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)
330       .left_join(
331         community_person_ban::table.on(
332           community::id
333             .eq(community_person_ban::community_id)
334             .and(community_person_ban::person_id.eq(comment::creator_id))
335             .and(
336               community_person_ban::expires
337                 .is_null()
338                 .or(community_person_ban::expires.gt(now)),
339             ),
340         ),
341       )
342       .left_join(
343         community_follower::table.on(
344           post::community_id
345             .eq(community_follower::community_id)
346             .and(community_follower::person_id.eq(person_id_join)),
347         ),
348       )
349       .left_join(
350         comment_saved::table.on(
351           comment::id
352             .eq(comment_saved::comment_id)
353             .and(comment_saved::person_id.eq(person_id_join)),
354         ),
355       )
356       .left_join(
357         person_block::table.on(
358           comment::creator_id
359             .eq(person_block::target_id)
360             .and(person_block::person_id.eq(person_id_join)),
361         ),
362       )
363       .left_join(
364         community_block::table.on(
365           community::id
366             .eq(community_block::community_id)
367             .and(community_block::person_id.eq(person_id_join)),
368         ),
369       )
370       .left_join(
371         comment_like::table.on(
372           comment::id
373             .eq(comment_like::comment_id)
374             .and(comment_like::person_id.eq(person_id_join)),
375         ),
376       )
377       .select((
378         comment::all_columns,
379         Person::safe_columns_tuple(),
380         comment_alias_1::all_columns.nullable(),
381         PersonAlias1::safe_columns_tuple().nullable(),
382         post::all_columns,
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(),
390       ))
391       .into_boxed();
392
393     // The replies
394     if let Some(recipient_id) = self.recipient_id {
395       query = query
396         // TODO needs lots of testing
397         .filter(person_alias_1::id.eq(recipient_id)) // Gets the comment replies
398         .or_filter(
399           comment::parent_id
400             .is_null()
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));
405     }
406
407     if self.unread_only.unwrap_or(false) {
408       query = query.filter(comment::read.eq(false));
409     }
410
411     if let Some(creator_id) = self.creator_id {
412       query = query.filter(comment::creator_id.eq(creator_id));
413     };
414
415     if let Some(community_id) = self.community_id {
416       query = query.filter(post::community_id.eq(community_id));
417     }
418
419     if let Some(community_actor_id) = self.community_actor_id {
420       query = query.filter(community::actor_id.eq(community_actor_id))
421     }
422
423     if let Some(post_id) = self.post_id {
424       query = query.filter(comment::post_id.eq(post_id));
425     };
426
427     if let Some(search_term) = self.search_term {
428       query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
429     };
430
431     if let Some(listing_type) = self.listing_type {
432       match 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(
438             community::hidden
439               .eq(false)
440               .or(community_follower::person_id.eq(person_id_join)),
441           )
442         }
443         ListingType::All => {
444           query = query.filter(
445             community::hidden
446               .eq(false)
447               .or(community_follower::person_id.eq(person_id_join)),
448           )
449         }
450         ListingType::Community => {}
451       };
452     }
453
454     if self.saved_only.unwrap_or(false) {
455       query = query.filter(comment_saved::id.is_not_null());
456     }
457
458     if !self.show_bot_accounts.unwrap_or(true) {
459       query = query.filter(person::bot_account.eq(false));
460     };
461
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())
468       }
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()),
482     };
483
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());
488     }
489
490     let (limit, offset) = limit_and_offset(self.page, self.limit);
491
492     // Note: deleted and removed comments are done on the front side
493     let res = query
494       .limit(limit)
495       .offset(offset)
496       .load::<CommentViewTuple>(self.conn)?;
497
498     Ok(CommentView::from_tuple_to_vec(res))
499   }
500 }
501
502 impl ViewToVec for CommentView {
503   type DbTuple = CommentViewTuple;
504   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
505     items
506       .iter()
507       .map(|a| 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(),
518         my_vote: a.11,
519       })
520       .collect::<Vec<Self>>()
521   }
522 }
523
524 #[cfg(test)]
525 mod tests {
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,
532   };
533   use serial_test::serial;
534
535   #[test]
536   #[serial]
537   fn test_crud() {
538     let conn = establish_unpooled_connection();
539
540     let new_person = PersonForm {
541       name: "timmy".into(),
542       ..PersonForm::default()
543     };
544
545     let inserted_person = Person::create(&conn, &new_person).unwrap();
546
547     let new_person_2 = PersonForm {
548       name: "sara".into(),
549       ..PersonForm::default()
550     };
551
552     let inserted_person_2 = Person::create(&conn, &new_person_2).unwrap();
553
554     let new_community = CommunityForm {
555       name: "test community 5".to_string(),
556       title: "nada".to_owned(),
557       ..CommunityForm::default()
558     };
559
560     let inserted_community = Community::create(&conn, &new_community).unwrap();
561
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()
567     };
568
569     let inserted_post = Post::create(&conn, &new_post).unwrap();
570
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()
576     };
577
578     let inserted_comment = Comment::create(&conn, &comment_form).unwrap();
579
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()
586     };
587
588     let inserted_comment_2 = Comment::create(&conn, &comment_form_2).unwrap();
589
590     let timmy_blocks_sara_form = PersonBlockForm {
591       person_id: inserted_person.id,
592       target_id: inserted_person_2.id,
593     };
594
595     let inserted_block = PersonBlock::block(&conn, &timmy_blocks_sara_form).unwrap();
596
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,
602     };
603
604     assert_eq!(expected_block, inserted_block);
605
606     let comment_like_form = CommentLikeForm {
607       comment_id: inserted_comment.id,
608       post_id: inserted_post.id,
609       person_id: inserted_person.id,
610       score: 1,
611     };
612
613     let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
614
615     let agg = CommentAggregates::read(&conn, inserted_comment.id).unwrap();
616
617     let expected_comment_view_no_person = CommentView {
618       creator_banned_from_community: false,
619       my_vote: None,
620       subscribed: false,
621       saved: false,
622       creator_blocked: false,
623       comment: Comment {
624         id: inserted_comment.id,
625         content: "A test comment 32".into(),
626         creator_id: inserted_person.id,
627         post_id: inserted_post.id,
628         parent_id: None,
629         removed: false,
630         deleted: false,
631         read: false,
632         published: inserted_comment.published,
633         ap_id: inserted_comment.ap_id,
634         updated: None,
635         local: true,
636       },
637       creator: PersonSafe {
638         id: inserted_person.id,
639         name: "timmy".into(),
640         display_name: None,
641         published: inserted_person.published,
642         avatar: None,
643         actor_id: inserted_person.actor_id.to_owned(),
644         local: true,
645         banned: false,
646         deleted: false,
647         admin: false,
648         bot_account: false,
649         bio: None,
650         banner: None,
651         updated: None,
652         inbox_url: inserted_person.inbox_url.to_owned(),
653         shared_inbox_url: None,
654         matrix_user_id: None,
655         ban_expires: None,
656       },
657       recipient: None,
658       post: Post {
659         id: inserted_post.id,
660         name: inserted_post.name.to_owned(),
661         creator_id: inserted_person.id,
662         url: None,
663         body: None,
664         published: inserted_post.published,
665         updated: None,
666         community_id: inserted_community.id,
667         removed: false,
668         deleted: false,
669         locked: false,
670         stickied: false,
671         nsfw: false,
672         embed_title: None,
673         embed_description: None,
674         embed_html: None,
675         thumbnail_url: None,
676         ap_id: inserted_post.ap_id.to_owned(),
677         local: true,
678       },
679       community: CommunitySafe {
680         id: inserted_community.id,
681         name: "test community 5".to_string(),
682         icon: None,
683         removed: false,
684         deleted: false,
685         nsfw: false,
686         actor_id: inserted_community.actor_id.to_owned(),
687         local: true,
688         title: "nada".to_owned(),
689         description: None,
690         updated: None,
691         banner: None,
692         hidden: false,
693         posting_restricted_to_mods: false,
694         published: inserted_community.published,
695       },
696       counts: CommentAggregates {
697         id: agg.id,
698         comment_id: inserted_comment.id,
699         score: 1,
700         upvotes: 1,
701         downvotes: 0,
702         published: agg.published,
703       },
704     };
705
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);
708
709     let read_comment_views_no_person = CommentQueryBuilder::create(&conn)
710       .post_id(inserted_post.id)
711       .list()
712       .unwrap();
713
714     let read_comment_views_with_person = CommentQueryBuilder::create(&conn)
715       .post_id(inserted_post.id)
716       .my_person_id(inserted_person.id)
717       .list()
718       .unwrap();
719
720     let read_comment_from_blocked_person =
721       CommentView::read(&conn, inserted_comment_2.id, Some(inserted_person.id)).unwrap();
722
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();
730
731     // Make sure its 1, not showing the blocked comment
732     assert_eq!(1, read_comment_views_with_person.len());
733
734     assert_eq!(
735       expected_comment_view_no_person,
736       read_comment_views_no_person[1]
737     );
738     assert_eq!(
739       expected_comment_view_with_person,
740       read_comment_views_with_person[0]
741     );
742
743     // Make sure block set the creator blocked
744     assert!(read_comment_from_blocked_person.creator_blocked);
745
746     assert_eq!(1, num_deleted);
747     assert_eq!(1, like_removed);
748   }
749 }