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