]> Untitled Git - lemmy.git/blob - crates/db_views/src/comment_view.rs
Strictly typing DB id fields. Fixes #1498
[lemmy.git] / crates / db_views / src / comment_view.rs
1 use diesel::{result::Error, *};
2 use lemmy_db_queries::{
3   aggregates::comment_aggregates::CommentAggregates,
4   functions::hot_rank,
5   fuzzy_search,
6   limit_and_offset,
7   ListingType,
8   MaybeOptional,
9   SortType,
10   ToSafe,
11   ViewToVec,
12 };
13 use lemmy_db_schema::{
14   schema::{
15     comment,
16     comment_aggregates,
17     comment_alias_1,
18     comment_like,
19     comment_saved,
20     community,
21     community_follower,
22     community_person_ban,
23     person,
24     person_alias_1,
25     post,
26   },
27   source::{
28     comment::{Comment, CommentAlias1, CommentSaved},
29     community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
30     person::{Person, PersonAlias1, PersonSafe, PersonSafeAlias1},
31     post::Post,
32   },
33   CommentId,
34   CommunityId,
35   PersonId,
36   PostId,
37 };
38 use serde::Serialize;
39
40 #[derive(Debug, PartialEq, Serialize, Clone)]
41 pub struct CommentView {
42   pub comment: Comment,
43   pub creator: PersonSafe,
44   pub recipient: Option<PersonSafeAlias1>, // Left joins to comment and person
45   pub post: Post,
46   pub community: CommunitySafe,
47   pub counts: CommentAggregates,
48   pub creator_banned_from_community: bool, // Left Join to CommunityPersonBan
49   pub subscribed: bool,                    // Left join to CommunityFollower
50   pub saved: bool,                         // Left join to CommentSaved
51   pub my_vote: Option<i16>,                // Left join to CommentLike
52 }
53
54 type CommentViewTuple = (
55   Comment,
56   PersonSafe,
57   Option<CommentAlias1>,
58   Option<PersonSafeAlias1>,
59   Post,
60   CommunitySafe,
61   CommentAggregates,
62   Option<CommunityPersonBan>,
63   Option<CommunityFollower>,
64   Option<CommentSaved>,
65   Option<i16>,
66 );
67
68 impl CommentView {
69   pub fn read(
70     conn: &PgConnection,
71     comment_id: CommentId,
72     my_person_id: Option<PersonId>,
73   ) -> Result<Self, Error> {
74     // The left join below will return None in this case
75     let person_id_join = my_person_id.unwrap_or(PersonId(-1));
76
77     let (
78       comment,
79       creator,
80       _parent_comment,
81       recipient,
82       post,
83       community,
84       counts,
85       creator_banned_from_community,
86       subscribed,
87       saved,
88       comment_like,
89     ) = comment::table
90       .find(comment_id)
91       .inner_join(person::table)
92       // recipient here
93       .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
94       .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
95       .inner_join(post::table)
96       .inner_join(community::table.on(post::community_id.eq(community::id)))
97       .inner_join(comment_aggregates::table)
98       .left_join(
99         community_person_ban::table.on(
100           community::id
101             .eq(community_person_ban::community_id)
102             .and(community_person_ban::person_id.eq(comment::creator_id)),
103         ),
104       )
105       .left_join(
106         community_follower::table.on(
107           post::community_id
108             .eq(community_follower::community_id)
109             .and(community_follower::person_id.eq(person_id_join)),
110         ),
111       )
112       .left_join(
113         comment_saved::table.on(
114           comment::id
115             .eq(comment_saved::comment_id)
116             .and(comment_saved::person_id.eq(person_id_join)),
117         ),
118       )
119       .left_join(
120         comment_like::table.on(
121           comment::id
122             .eq(comment_like::comment_id)
123             .and(comment_like::person_id.eq(person_id_join)),
124         ),
125       )
126       .select((
127         comment::all_columns,
128         Person::safe_columns_tuple(),
129         comment_alias_1::all_columns.nullable(),
130         PersonAlias1::safe_columns_tuple().nullable(),
131         post::all_columns,
132         Community::safe_columns_tuple(),
133         comment_aggregates::all_columns,
134         community_person_ban::all_columns.nullable(),
135         community_follower::all_columns.nullable(),
136         comment_saved::all_columns.nullable(),
137         comment_like::score.nullable(),
138       ))
139       .first::<CommentViewTuple>(conn)?;
140
141     // If a person is given, then my_vote, if None, should be 0, not null
142     // Necessary to differentiate between other person's votes
143     let my_vote = if my_person_id.is_some() && comment_like.is_none() {
144       Some(0)
145     } else {
146       comment_like
147     };
148
149     Ok(CommentView {
150       comment,
151       recipient,
152       post,
153       creator,
154       community,
155       counts,
156       creator_banned_from_community: creator_banned_from_community.is_some(),
157       subscribed: subscribed.is_some(),
158       saved: saved.is_some(),
159       my_vote,
160     })
161   }
162
163   /// Gets the recipient person id.
164   /// If there is no parent comment, its the post creator
165   pub fn get_recipient_id(&self) -> PersonId {
166     match &self.recipient {
167       Some(parent_commenter) => parent_commenter.id,
168       None => self.post.creator_id,
169     }
170   }
171 }
172
173 pub struct CommentQueryBuilder<'a> {
174   conn: &'a PgConnection,
175   listing_type: ListingType,
176   sort: &'a SortType,
177   community_id: Option<CommunityId>,
178   community_name: Option<String>,
179   post_id: Option<PostId>,
180   creator_id: Option<PersonId>,
181   recipient_id: Option<PersonId>,
182   my_person_id: Option<PersonId>,
183   search_term: Option<String>,
184   saved_only: bool,
185   unread_only: bool,
186   page: Option<i64>,
187   limit: Option<i64>,
188 }
189
190 impl<'a> CommentQueryBuilder<'a> {
191   pub fn create(conn: &'a PgConnection) -> Self {
192     CommentQueryBuilder {
193       conn,
194       listing_type: ListingType::All,
195       sort: &SortType::New,
196       community_id: None,
197       community_name: None,
198       post_id: None,
199       creator_id: None,
200       recipient_id: None,
201       my_person_id: None,
202       search_term: None,
203       saved_only: false,
204       unread_only: false,
205       page: None,
206       limit: None,
207     }
208   }
209
210   pub fn listing_type(mut self, listing_type: ListingType) -> Self {
211     self.listing_type = listing_type;
212     self
213   }
214
215   pub fn sort(mut self, sort: &'a SortType) -> Self {
216     self.sort = sort;
217     self
218   }
219
220   pub fn post_id<T: MaybeOptional<PostId>>(mut self, post_id: T) -> Self {
221     self.post_id = post_id.get_optional();
222     self
223   }
224
225   pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
226     self.creator_id = creator_id.get_optional();
227     self
228   }
229
230   pub fn recipient_id<T: MaybeOptional<PersonId>>(mut self, recipient_id: T) -> Self {
231     self.recipient_id = recipient_id.get_optional();
232     self
233   }
234
235   pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
236     self.community_id = community_id.get_optional();
237     self
238   }
239
240   pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
241     self.my_person_id = my_person_id.get_optional();
242     self
243   }
244
245   pub fn community_name<T: MaybeOptional<String>>(mut self, community_name: T) -> Self {
246     self.community_name = community_name.get_optional();
247     self
248   }
249
250   pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
251     self.search_term = search_term.get_optional();
252     self
253   }
254
255   pub fn saved_only(mut self, saved_only: bool) -> Self {
256     self.saved_only = saved_only;
257     self
258   }
259
260   pub fn unread_only(mut self, unread_only: bool) -> Self {
261     self.unread_only = unread_only;
262     self
263   }
264
265   pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
266     self.page = page.get_optional();
267     self
268   }
269
270   pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
271     self.limit = limit.get_optional();
272     self
273   }
274
275   pub fn list(self) -> Result<Vec<CommentView>, Error> {
276     use diesel::dsl::*;
277
278     // The left join below will return None in this case
279     let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
280
281     let mut query = comment::table
282       .inner_join(person::table)
283       // recipient here
284       .left_join(comment_alias_1::table.on(comment_alias_1::id.nullable().eq(comment::parent_id)))
285       .left_join(person_alias_1::table.on(person_alias_1::id.eq(comment_alias_1::creator_id)))
286       .inner_join(post::table)
287       .inner_join(community::table.on(post::community_id.eq(community::id)))
288       .inner_join(comment_aggregates::table)
289       .left_join(
290         community_person_ban::table.on(
291           community::id
292             .eq(community_person_ban::community_id)
293             .and(community_person_ban::person_id.eq(comment::creator_id)),
294         ),
295       )
296       .left_join(
297         community_follower::table.on(
298           post::community_id
299             .eq(community_follower::community_id)
300             .and(community_follower::person_id.eq(person_id_join)),
301         ),
302       )
303       .left_join(
304         comment_saved::table.on(
305           comment::id
306             .eq(comment_saved::comment_id)
307             .and(comment_saved::person_id.eq(person_id_join)),
308         ),
309       )
310       .left_join(
311         comment_like::table.on(
312           comment::id
313             .eq(comment_like::comment_id)
314             .and(comment_like::person_id.eq(person_id_join)),
315         ),
316       )
317       .select((
318         comment::all_columns,
319         Person::safe_columns_tuple(),
320         comment_alias_1::all_columns.nullable(),
321         PersonAlias1::safe_columns_tuple().nullable(),
322         post::all_columns,
323         Community::safe_columns_tuple(),
324         comment_aggregates::all_columns,
325         community_person_ban::all_columns.nullable(),
326         community_follower::all_columns.nullable(),
327         comment_saved::all_columns.nullable(),
328         comment_like::score.nullable(),
329       ))
330       .into_boxed();
331
332     // The replies
333     if let Some(recipient_id) = self.recipient_id {
334       query = query
335         // TODO needs lots of testing
336         .filter(person_alias_1::id.eq(recipient_id)) // Gets the comment replies
337         .or_filter(
338           comment::parent_id
339             .is_null()
340             .and(post::creator_id.eq(recipient_id)),
341         ) // Gets the top level replies
342         .filter(comment::deleted.eq(false))
343         .filter(comment::removed.eq(false));
344     }
345
346     if self.unread_only {
347       query = query.filter(comment::read.eq(false));
348     }
349
350     if let Some(creator_id) = self.creator_id {
351       query = query.filter(comment::creator_id.eq(creator_id));
352     };
353
354     if let Some(community_id) = self.community_id {
355       query = query.filter(post::community_id.eq(community_id));
356     }
357
358     if let Some(community_name) = self.community_name {
359       query = query
360         .filter(community::name.eq(community_name))
361         .filter(comment::local.eq(true));
362     }
363
364     if let Some(post_id) = self.post_id {
365       query = query.filter(comment::post_id.eq(post_id));
366     };
367
368     if let Some(search_term) = self.search_term {
369       query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
370     };
371
372     query = match self.listing_type {
373       // ListingType::Subscribed => query.filter(community_follower::subscribed.eq(true)),
374       ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
375       ListingType::Local => query.filter(community::local.eq(true)),
376       _ => query,
377     };
378
379     if self.saved_only {
380       query = query.filter(comment_saved::id.is_not_null());
381     }
382
383     query = match self.sort {
384       SortType::Hot | SortType::Active => query
385         .order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
386         .then_order_by(comment_aggregates::published.desc()),
387       SortType::New | SortType::MostComments | SortType::NewComments => {
388         query.order_by(comment::published.desc())
389       }
390       SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
391       SortType::TopYear => query
392         .filter(comment::published.gt(now - 1.years()))
393         .order_by(comment_aggregates::score.desc()),
394       SortType::TopMonth => query
395         .filter(comment::published.gt(now - 1.months()))
396         .order_by(comment_aggregates::score.desc()),
397       SortType::TopWeek => query
398         .filter(comment::published.gt(now - 1.weeks()))
399         .order_by(comment_aggregates::score.desc()),
400       SortType::TopDay => query
401         .filter(comment::published.gt(now - 1.days()))
402         .order_by(comment_aggregates::score.desc()),
403     };
404
405     let (limit, offset) = limit_and_offset(self.page, self.limit);
406
407     // Note: deleted and removed comments are done on the front side
408     let res = query
409       .limit(limit)
410       .offset(offset)
411       .load::<CommentViewTuple>(self.conn)?;
412
413     Ok(CommentView::from_tuple_to_vec(res))
414   }
415 }
416
417 impl ViewToVec for CommentView {
418   type DbTuple = CommentViewTuple;
419   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
420     items
421       .iter()
422       .map(|a| Self {
423         comment: a.0.to_owned(),
424         creator: a.1.to_owned(),
425         recipient: a.3.to_owned(),
426         post: a.4.to_owned(),
427         community: a.5.to_owned(),
428         counts: a.6.to_owned(),
429         creator_banned_from_community: a.7.is_some(),
430         subscribed: a.8.is_some(),
431         saved: a.9.is_some(),
432         my_vote: a.10,
433       })
434       .collect::<Vec<Self>>()
435   }
436 }
437
438 #[cfg(test)]
439 mod tests {
440   use crate::comment_view::*;
441   use lemmy_db_queries::{
442     aggregates::comment_aggregates::CommentAggregates,
443     establish_unpooled_connection,
444     Crud,
445     Likeable,
446   };
447   use lemmy_db_schema::source::{comment::*, community::*, person::*, post::*};
448   use serial_test::serial;
449
450   #[test]
451   #[serial]
452   fn test_crud() {
453     let conn = establish_unpooled_connection();
454
455     let new_person = PersonForm {
456       name: "timmy".into(),
457       preferred_username: None,
458       avatar: None,
459       banner: None,
460       banned: None,
461       deleted: None,
462       published: None,
463       updated: None,
464       actor_id: None,
465       bio: None,
466       local: None,
467       private_key: None,
468       public_key: None,
469       last_refreshed_at: None,
470       inbox_url: None,
471       shared_inbox_url: None,
472     };
473
474     let inserted_person = Person::create(&conn, &new_person).unwrap();
475
476     let new_community = CommunityForm {
477       name: "test community 5".to_string(),
478       title: "nada".to_owned(),
479       description: None,
480       creator_id: inserted_person.id,
481       removed: None,
482       deleted: None,
483       updated: None,
484       nsfw: false,
485       actor_id: None,
486       local: true,
487       private_key: None,
488       public_key: None,
489       last_refreshed_at: None,
490       published: None,
491       icon: None,
492       banner: None,
493       followers_url: None,
494       inbox_url: None,
495       shared_inbox_url: None,
496     };
497
498     let inserted_community = Community::create(&conn, &new_community).unwrap();
499
500     let new_post = PostForm {
501       name: "A test post 2".into(),
502       creator_id: inserted_person.id,
503       url: None,
504       body: None,
505       community_id: inserted_community.id,
506       removed: None,
507       deleted: None,
508       locked: None,
509       stickied: None,
510       updated: None,
511       nsfw: false,
512       embed_title: None,
513       embed_description: None,
514       embed_html: None,
515       thumbnail_url: None,
516       ap_id: None,
517       local: true,
518       published: None,
519     };
520
521     let inserted_post = Post::create(&conn, &new_post).unwrap();
522
523     let comment_form = CommentForm {
524       content: "A test comment 32".into(),
525       creator_id: inserted_person.id,
526       post_id: inserted_post.id,
527       parent_id: None,
528       removed: None,
529       deleted: None,
530       read: None,
531       published: None,
532       updated: None,
533       ap_id: None,
534       local: true,
535     };
536
537     let inserted_comment = Comment::create(&conn, &comment_form).unwrap();
538
539     let comment_like_form = CommentLikeForm {
540       comment_id: inserted_comment.id,
541       post_id: inserted_post.id,
542       person_id: inserted_person.id,
543       score: 1,
544     };
545
546     let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
547
548     let agg = CommentAggregates::read(&conn, inserted_comment.id).unwrap();
549
550     let expected_comment_view_no_person = CommentView {
551       creator_banned_from_community: false,
552       my_vote: None,
553       subscribed: false,
554       saved: false,
555       comment: Comment {
556         id: inserted_comment.id,
557         content: "A test comment 32".into(),
558         creator_id: inserted_person.id,
559         post_id: inserted_post.id,
560         parent_id: None,
561         removed: false,
562         deleted: false,
563         read: false,
564         published: inserted_comment.published,
565         ap_id: inserted_comment.ap_id,
566         updated: None,
567         local: true,
568       },
569       creator: PersonSafe {
570         id: inserted_person.id,
571         name: "timmy".into(),
572         preferred_username: None,
573         published: inserted_person.published,
574         avatar: None,
575         actor_id: inserted_person.actor_id.to_owned(),
576         local: true,
577         banned: false,
578         deleted: false,
579         bio: None,
580         banner: None,
581         updated: None,
582         inbox_url: inserted_person.inbox_url.to_owned(),
583         shared_inbox_url: None,
584       },
585       recipient: None,
586       post: Post {
587         id: inserted_post.id,
588         name: inserted_post.name.to_owned(),
589         creator_id: inserted_person.id,
590         url: None,
591         body: None,
592         published: inserted_post.published,
593         updated: None,
594         community_id: inserted_community.id,
595         removed: false,
596         deleted: false,
597         locked: false,
598         stickied: false,
599         nsfw: false,
600         embed_title: None,
601         embed_description: None,
602         embed_html: None,
603         thumbnail_url: None,
604         ap_id: inserted_post.ap_id.to_owned(),
605         local: true,
606       },
607       community: CommunitySafe {
608         id: inserted_community.id,
609         name: "test community 5".to_string(),
610         icon: None,
611         removed: false,
612         deleted: false,
613         nsfw: false,
614         actor_id: inserted_community.actor_id.to_owned(),
615         local: true,
616         title: "nada".to_owned(),
617         description: None,
618         creator_id: inserted_person.id,
619         updated: None,
620         banner: None,
621         published: inserted_community.published,
622       },
623       counts: CommentAggregates {
624         id: agg.id,
625         comment_id: inserted_comment.id,
626         score: 1,
627         upvotes: 1,
628         downvotes: 0,
629         published: agg.published,
630       },
631     };
632
633     let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
634     expected_comment_view_with_person.my_vote = Some(1);
635
636     let read_comment_views_no_person = CommentQueryBuilder::create(&conn)
637       .post_id(inserted_post.id)
638       .list()
639       .unwrap();
640
641     let read_comment_views_with_person = CommentQueryBuilder::create(&conn)
642       .post_id(inserted_post.id)
643       .my_person_id(inserted_person.id)
644       .list()
645       .unwrap();
646
647     let like_removed = CommentLike::remove(&conn, inserted_person.id, inserted_comment.id).unwrap();
648     let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap();
649     Post::delete(&conn, inserted_post.id).unwrap();
650     Community::delete(&conn, inserted_community.id).unwrap();
651     Person::delete(&conn, inserted_person.id).unwrap();
652
653     assert_eq!(
654       expected_comment_view_no_person,
655       read_comment_views_no_person[0]
656     );
657     assert_eq!(
658       expected_comment_view_with_person,
659       read_comment_views_with_person[0]
660     );
661     assert_eq!(1, num_deleted);
662     assert_eq!(1, like_removed);
663   }
664 }