]> Untitled Git - lemmy.git/blob - crates/db_views/src/comment_view.rs
925ffb52857fa63bef61e690896d45a4f87f0cf6
[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_unlimited},
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       follower,
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: CommunityFollower::to_subscribed_type(&follower),
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: Some(ListingType::All),
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(post_id) = self.post_id {
418       query = query.filter(comment::post_id.eq(post_id));
419     };
420
421     if let Some(search_term) = self.search_term {
422       query = query.filter(comment::content.ilike(fuzzy_search(&search_term)));
423     };
424
425     if let Some(listing_type) = self.listing_type {
426       match listing_type {
427         ListingType::Subscribed => {
428           query = query.filter(community_follower::person_id.is_not_null())
429         } // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
430         ListingType::Local => {
431           query = query.filter(community::local.eq(true)).filter(
432             community::hidden
433               .eq(false)
434               .or(community_follower::person_id.eq(person_id_join)),
435           )
436         }
437         ListingType::All => {
438           query = query.filter(
439             community::hidden
440               .eq(false)
441               .or(community_follower::person_id.eq(person_id_join)),
442           )
443         }
444       }
445     };
446
447     if let Some(community_id) = self.community_id {
448       query = query.filter(post::community_id.eq(community_id));
449     }
450
451     if let Some(community_actor_id) = self.community_actor_id {
452       query = query.filter(community::actor_id.eq(community_actor_id))
453     }
454
455     if self.saved_only.unwrap_or(false) {
456       query = query.filter(comment_saved::id.is_not_null());
457     }
458
459     if !self.show_bot_accounts.unwrap_or(true) {
460       query = query.filter(person::bot_account.eq(false));
461     };
462
463     query = match self.sort.unwrap_or(SortType::New) {
464       SortType::Hot | SortType::Active => query
465         .order_by(hot_rank(comment_aggregates::score, comment_aggregates::published).desc())
466         .then_order_by(comment_aggregates::published.desc()),
467       SortType::New | SortType::MostComments | SortType::NewComments => {
468         query.order_by(comment::published.desc())
469       }
470       SortType::TopAll => query.order_by(comment_aggregates::score.desc()),
471       SortType::TopYear => query
472         .filter(comment::published.gt(now - 1.years()))
473         .order_by(comment_aggregates::score.desc()),
474       SortType::TopMonth => query
475         .filter(comment::published.gt(now - 1.months()))
476         .order_by(comment_aggregates::score.desc()),
477       SortType::TopWeek => query
478         .filter(comment::published.gt(now - 1.weeks()))
479         .order_by(comment_aggregates::score.desc()),
480       SortType::TopDay => query
481         .filter(comment::published.gt(now - 1.days()))
482         .order_by(comment_aggregates::score.desc()),
483     };
484
485     // Don't show blocked communities or persons
486     if self.my_person_id.is_some() {
487       query = query.filter(community_block::person_id.is_null());
488       query = query.filter(person_block::person_id.is_null());
489     }
490
491     // Don't use the regular error-checking one, many more comments must ofter be fetched.
492     let (limit, offset) = limit_and_offset_unlimited(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: CommunityFollower::to_subscribed_type(&a.8),
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     SubscribedType,
535   };
536   use serial_test::serial;
537
538   #[test]
539   #[serial]
540   fn test_crud() {
541     let conn = establish_unpooled_connection();
542
543     let new_person = PersonForm {
544       name: "timmy".into(),
545       public_key: Some("pubkey".to_string()),
546       ..PersonForm::default()
547     };
548
549     let inserted_person = Person::create(&conn, &new_person).unwrap();
550
551     let new_person_2 = PersonForm {
552       name: "sara".into(),
553       public_key: Some("pubkey".to_string()),
554       ..PersonForm::default()
555     };
556
557     let inserted_person_2 = Person::create(&conn, &new_person_2).unwrap();
558
559     let new_community = CommunityForm {
560       name: "test community 5".to_string(),
561       title: "nada".to_owned(),
562       public_key: Some("pubkey".to_string()),
563       ..CommunityForm::default()
564     };
565
566     let inserted_community = Community::create(&conn, &new_community).unwrap();
567
568     let new_post = PostForm {
569       name: "A test post 2".into(),
570       creator_id: inserted_person.id,
571       community_id: inserted_community.id,
572       ..PostForm::default()
573     };
574
575     let inserted_post = Post::create(&conn, &new_post).unwrap();
576
577     let comment_form = CommentForm {
578       content: "A test comment 32".into(),
579       creator_id: inserted_person.id,
580       post_id: inserted_post.id,
581       ..CommentForm::default()
582     };
583
584     let inserted_comment = Comment::create(&conn, &comment_form).unwrap();
585
586     let comment_form_2 = CommentForm {
587       content: "A test blocked comment".into(),
588       creator_id: inserted_person_2.id,
589       post_id: inserted_post.id,
590       parent_id: Some(inserted_comment.id),
591       ..CommentForm::default()
592     };
593
594     let inserted_comment_2 = Comment::create(&conn, &comment_form_2).unwrap();
595
596     let timmy_blocks_sara_form = PersonBlockForm {
597       person_id: inserted_person.id,
598       target_id: inserted_person_2.id,
599     };
600
601     let inserted_block = PersonBlock::block(&conn, &timmy_blocks_sara_form).unwrap();
602
603     let expected_block = PersonBlock {
604       id: inserted_block.id,
605       person_id: inserted_person.id,
606       target_id: inserted_person_2.id,
607       published: inserted_block.published,
608     };
609
610     assert_eq!(expected_block, inserted_block);
611
612     let comment_like_form = CommentLikeForm {
613       comment_id: inserted_comment.id,
614       post_id: inserted_post.id,
615       person_id: inserted_person.id,
616       score: 1,
617     };
618
619     let _inserted_comment_like = CommentLike::like(&conn, &comment_like_form).unwrap();
620
621     let agg = CommentAggregates::read(&conn, inserted_comment.id).unwrap();
622
623     let expected_comment_view_no_person = CommentView {
624       creator_banned_from_community: false,
625       my_vote: None,
626       subscribed: SubscribedType::NotSubscribed,
627       saved: false,
628       creator_blocked: false,
629       comment: Comment {
630         id: inserted_comment.id,
631         content: "A test comment 32".into(),
632         creator_id: inserted_person.id,
633         post_id: inserted_post.id,
634         parent_id: None,
635         removed: false,
636         deleted: false,
637         read: false,
638         published: inserted_comment.published,
639         ap_id: inserted_comment.ap_id,
640         updated: None,
641         local: true,
642       },
643       creator: PersonSafe {
644         id: inserted_person.id,
645         name: "timmy".into(),
646         display_name: None,
647         published: inserted_person.published,
648         avatar: None,
649         actor_id: inserted_person.actor_id.to_owned(),
650         local: true,
651         banned: false,
652         deleted: false,
653         admin: false,
654         bot_account: false,
655         bio: None,
656         banner: None,
657         updated: None,
658         inbox_url: inserted_person.inbox_url.to_owned(),
659         shared_inbox_url: None,
660         matrix_user_id: None,
661         ban_expires: None,
662       },
663       recipient: None,
664       post: Post {
665         id: inserted_post.id,
666         name: inserted_post.name.to_owned(),
667         creator_id: inserted_person.id,
668         url: None,
669         body: None,
670         published: inserted_post.published,
671         updated: None,
672         community_id: inserted_community.id,
673         removed: false,
674         deleted: false,
675         locked: false,
676         stickied: false,
677         nsfw: false,
678         embed_title: None,
679         embed_description: None,
680         embed_video_url: None,
681         thumbnail_url: None,
682         ap_id: inserted_post.ap_id.to_owned(),
683         local: true,
684       },
685       community: CommunitySafe {
686         id: inserted_community.id,
687         name: "test community 5".to_string(),
688         icon: None,
689         removed: false,
690         deleted: false,
691         nsfw: false,
692         actor_id: inserted_community.actor_id.to_owned(),
693         local: true,
694         title: "nada".to_owned(),
695         description: None,
696         updated: None,
697         banner: None,
698         hidden: false,
699         posting_restricted_to_mods: false,
700         published: inserted_community.published,
701       },
702       counts: CommentAggregates {
703         id: agg.id,
704         comment_id: inserted_comment.id,
705         score: 1,
706         upvotes: 1,
707         downvotes: 0,
708         published: agg.published,
709       },
710     };
711
712     let mut expected_comment_view_with_person = expected_comment_view_no_person.to_owned();
713     expected_comment_view_with_person.my_vote = Some(1);
714
715     let read_comment_views_no_person = CommentQueryBuilder::create(&conn)
716       .post_id(inserted_post.id)
717       .list()
718       .unwrap();
719
720     let read_comment_views_with_person = CommentQueryBuilder::create(&conn)
721       .post_id(inserted_post.id)
722       .my_person_id(inserted_person.id)
723       .list()
724       .unwrap();
725
726     let read_comment_from_blocked_person =
727       CommentView::read(&conn, inserted_comment_2.id, Some(inserted_person.id)).unwrap();
728
729     let like_removed = CommentLike::remove(&conn, inserted_person.id, inserted_comment.id).unwrap();
730     let num_deleted = Comment::delete(&conn, inserted_comment.id).unwrap();
731     Comment::delete(&conn, inserted_comment_2.id).unwrap();
732     Post::delete(&conn, inserted_post.id).unwrap();
733     Community::delete(&conn, inserted_community.id).unwrap();
734     Person::delete(&conn, inserted_person.id).unwrap();
735     Person::delete(&conn, inserted_person_2.id).unwrap();
736
737     // Make sure its 1, not showing the blocked comment
738     assert_eq!(1, read_comment_views_with_person.len());
739
740     assert_eq!(
741       expected_comment_view_no_person,
742       read_comment_views_no_person[1]
743     );
744     assert_eq!(
745       expected_comment_view_with_person,
746       read_comment_views_with_person[0]
747     );
748
749     // Make sure block set the creator blocked
750     assert!(read_comment_from_blocked_person.creator_blocked);
751
752     assert_eq!(1, num_deleted);
753     assert_eq!(1, like_removed);
754   }
755 }