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