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