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