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