]> Untitled Git - lemmy.git/blob - crates/db_views/src/post_view.rs
Adding temporary bans. Fixes #1423 (#1999)
[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       query = match listing_type {
359         ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()),
360         ListingType::Local => query.filter(community::local.eq(true)),
361         _ => query,
362       };
363     }
364
365     if let Some(community_id) = self.community_id {
366       query = query
367         .filter(post::community_id.eq(community_id))
368         .then_order_by(post_aggregates::stickied.desc());
369     }
370
371     if let Some(community_actor_id) = self.community_actor_id {
372       query = query
373         .filter(community::actor_id.eq(community_actor_id))
374         .then_order_by(post_aggregates::stickied.desc());
375     }
376
377     if let Some(url_search) = self.url_search {
378       query = query.filter(post::url.eq(url_search));
379     }
380
381     if let Some(search_term) = self.search_term {
382       let searcher = fuzzy_search(&search_term);
383       query = query.filter(
384         post::name
385           .ilike(searcher.to_owned())
386           .or(post::body.ilike(searcher)),
387       );
388     }
389
390     // If its for a specific person, show the removed / deleted
391     if let Some(creator_id) = self.creator_id {
392       query = query.filter(post::creator_id.eq(creator_id));
393     }
394
395     if !self.show_nsfw.unwrap_or(false) {
396       query = query
397         .filter(post::nsfw.eq(false))
398         .filter(community::nsfw.eq(false));
399     };
400
401     if !self.show_bot_accounts.unwrap_or(true) {
402       query = query.filter(person::bot_account.eq(false));
403     };
404
405     if self.saved_only.unwrap_or(false) {
406       query = query.filter(post_saved::id.is_not_null());
407     }
408     // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
409     // setting wont be able to see saved posts.
410     else if !self.show_read_posts.unwrap_or(true) {
411       query = query.filter(post_read::id.is_null());
412     }
413
414     // Don't show blocked communities or persons
415     if self.my_person_id.is_some() {
416       query = query.filter(community_block::person_id.is_null());
417       query = query.filter(person_block::person_id.is_null());
418     }
419
420     query = match self.sort.unwrap_or(SortType::Hot) {
421       SortType::Active => query
422         .then_order_by(
423           hot_rank(
424             post_aggregates::score,
425             post_aggregates::newest_comment_time_necro,
426           )
427           .desc(),
428         )
429         .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
430       SortType::Hot => query
431         .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
432         .then_order_by(post_aggregates::published.desc()),
433       SortType::New => query.then_order_by(post_aggregates::published.desc()),
434       SortType::MostComments => query.then_order_by(post_aggregates::comments.desc()),
435       SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
436       SortType::TopAll => query.then_order_by(post_aggregates::score.desc()),
437       SortType::TopYear => query
438         .filter(post::published.gt(now - 1.years()))
439         .then_order_by(post_aggregates::score.desc()),
440       SortType::TopMonth => query
441         .filter(post::published.gt(now - 1.months()))
442         .then_order_by(post_aggregates::score.desc()),
443       SortType::TopWeek => query
444         .filter(post::published.gt(now - 1.weeks()))
445         .then_order_by(post_aggregates::score.desc()),
446       SortType::TopDay => query
447         .filter(post::published.gt(now - 1.days()))
448         .then_order_by(post_aggregates::score.desc()),
449     };
450
451     let (limit, offset) = limit_and_offset(self.page, self.limit);
452
453     query = query
454       .limit(limit)
455       .offset(offset)
456       .filter(post::removed.eq(false))
457       .filter(post::deleted.eq(false))
458       .filter(community::removed.eq(false))
459       .filter(community::deleted.eq(false));
460
461     debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
462
463     let res = query.load::<PostViewTuple>(self.conn)?;
464
465     Ok(PostView::from_tuple_to_vec(res))
466   }
467 }
468
469 impl ViewToVec for PostView {
470   type DbTuple = PostViewTuple;
471   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
472     items
473       .iter()
474       .map(|a| Self {
475         post: a.0.to_owned(),
476         creator: a.1.to_owned(),
477         community: a.2.to_owned(),
478         creator_banned_from_community: a.3.is_some(),
479         counts: a.4.to_owned(),
480         subscribed: a.5.is_some(),
481         saved: a.6.is_some(),
482         read: a.7.is_some(),
483         creator_blocked: a.8.is_some(),
484         my_vote: a.9,
485       })
486       .collect::<Vec<Self>>()
487   }
488 }
489
490 #[cfg(test)]
491 mod tests {
492   use crate::post_view::{PostQueryBuilder, PostView};
493   use lemmy_db_schema::{
494     aggregates::post_aggregates::PostAggregates,
495     establish_unpooled_connection,
496     source::{
497       community::*,
498       community_block::{CommunityBlock, CommunityBlockForm},
499       person::*,
500       person_block::{PersonBlock, PersonBlockForm},
501       post::*,
502     },
503     traits::{Blockable, Crud, Likeable},
504     ListingType,
505     SortType,
506   };
507   use serial_test::serial;
508
509   #[test]
510   #[serial]
511   fn test_crud() {
512     let conn = establish_unpooled_connection();
513
514     let person_name = "tegan".to_string();
515     let community_name = "test_community_3".to_string();
516     let post_name = "test post 3".to_string();
517     let bot_post_name = "test bot post".to_string();
518
519     let new_person = PersonForm {
520       name: person_name.to_owned(),
521       ..PersonForm::default()
522     };
523
524     let inserted_person = Person::create(&conn, &new_person).unwrap();
525
526     let new_bot = PersonForm {
527       name: person_name.to_owned(),
528       bot_account: Some(true),
529       ..PersonForm::default()
530     };
531
532     let inserted_bot = Person::create(&conn, &new_bot).unwrap();
533
534     let new_community = CommunityForm {
535       name: community_name.to_owned(),
536       title: "nada".to_owned(),
537       ..CommunityForm::default()
538     };
539
540     let inserted_community = Community::create(&conn, &new_community).unwrap();
541
542     // Test a person block, make sure the post query doesn't include their post
543     let blocked_person = PersonForm {
544       name: person_name.to_owned(),
545       ..PersonForm::default()
546     };
547
548     let inserted_blocked_person = Person::create(&conn, &blocked_person).unwrap();
549
550     let post_from_blocked_person = PostForm {
551       name: "blocked_person_post".to_string(),
552       creator_id: inserted_blocked_person.id,
553       community_id: inserted_community.id,
554       ..PostForm::default()
555     };
556
557     Post::create(&conn, &post_from_blocked_person).unwrap();
558
559     // block that person
560     let person_block = PersonBlockForm {
561       person_id: inserted_person.id,
562       target_id: inserted_blocked_person.id,
563     };
564
565     PersonBlock::block(&conn, &person_block).unwrap();
566
567     // A sample post
568     let new_post = PostForm {
569       name: post_name.to_owned(),
570       creator_id: inserted_person.id,
571       community_id: inserted_community.id,
572       ..PostForm::default()
573     };
574
575     let inserted_post = Post::create(&conn, &new_post).unwrap();
576
577     let new_bot_post = PostForm {
578       name: bot_post_name,
579       creator_id: inserted_bot.id,
580       community_id: inserted_community.id,
581       ..PostForm::default()
582     };
583
584     let _inserted_bot_post = Post::create(&conn, &new_bot_post).unwrap();
585
586     let post_like_form = PostLikeForm {
587       post_id: inserted_post.id,
588       person_id: inserted_person.id,
589       score: 1,
590     };
591
592     let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
593
594     let expected_post_like = PostLike {
595       id: inserted_post_like.id,
596       post_id: inserted_post.id,
597       person_id: inserted_person.id,
598       published: inserted_post_like.published,
599       score: 1,
600     };
601
602     let read_post_listings_with_person = PostQueryBuilder::create(&conn)
603       .listing_type(ListingType::Community)
604       .sort(SortType::New)
605       .show_bot_accounts(false)
606       .community_id(inserted_community.id)
607       .my_person_id(inserted_person.id)
608       .list()
609       .unwrap();
610
611     let read_post_listings_no_person = PostQueryBuilder::create(&conn)
612       .listing_type(ListingType::Community)
613       .sort(SortType::New)
614       .community_id(inserted_community.id)
615       .list()
616       .unwrap();
617
618     let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
619     let read_post_listing_with_person =
620       PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
621
622     let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
623
624     // the non person version
625     let expected_post_listing_no_person = PostView {
626       post: Post {
627         id: inserted_post.id,
628         name: post_name,
629         creator_id: inserted_person.id,
630         url: None,
631         body: None,
632         published: inserted_post.published,
633         updated: None,
634         community_id: inserted_community.id,
635         removed: false,
636         deleted: false,
637         locked: false,
638         stickied: false,
639         nsfw: false,
640         embed_title: None,
641         embed_description: None,
642         embed_html: None,
643         thumbnail_url: None,
644         ap_id: inserted_post.ap_id.to_owned(),
645         local: true,
646       },
647       my_vote: None,
648       creator: PersonSafe {
649         id: inserted_person.id,
650         name: person_name,
651         display_name: None,
652         published: inserted_person.published,
653         avatar: None,
654         actor_id: inserted_person.actor_id.to_owned(),
655         local: true,
656         admin: false,
657         bot_account: false,
658         banned: false,
659         deleted: false,
660         bio: None,
661         banner: None,
662         updated: None,
663         inbox_url: inserted_person.inbox_url.to_owned(),
664         shared_inbox_url: None,
665         matrix_user_id: None,
666         ban_expires: None,
667       },
668       creator_banned_from_community: false,
669       community: CommunitySafe {
670         id: inserted_community.id,
671         name: community_name,
672         icon: None,
673         removed: false,
674         deleted: false,
675         nsfw: false,
676         actor_id: inserted_community.actor_id.to_owned(),
677         local: true,
678         title: "nada".to_owned(),
679         description: None,
680         updated: None,
681         banner: None,
682         published: inserted_community.published,
683       },
684       counts: PostAggregates {
685         id: agg.id,
686         post_id: inserted_post.id,
687         comments: 0,
688         score: 1,
689         upvotes: 1,
690         downvotes: 0,
691         stickied: false,
692         published: agg.published,
693         newest_comment_time_necro: inserted_post.published,
694         newest_comment_time: inserted_post.published,
695       },
696       subscribed: false,
697       read: false,
698       saved: false,
699       creator_blocked: false,
700     };
701
702     // Test a community block
703     let community_block = CommunityBlockForm {
704       person_id: inserted_person.id,
705       community_id: inserted_community.id,
706     };
707     CommunityBlock::block(&conn, &community_block).unwrap();
708
709     let read_post_listings_with_person_after_block = PostQueryBuilder::create(&conn)
710       .listing_type(ListingType::Community)
711       .sort(SortType::New)
712       .show_bot_accounts(false)
713       .community_id(inserted_community.id)
714       .my_person_id(inserted_person.id)
715       .list()
716       .unwrap();
717
718     // TODO More needs to be added here
719     let mut expected_post_listing_with_user = expected_post_listing_no_person.to_owned();
720     expected_post_listing_with_user.my_vote = Some(1);
721
722     let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
723     let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
724     PersonBlock::unblock(&conn, &person_block).unwrap();
725     CommunityBlock::unblock(&conn, &community_block).unwrap();
726     Community::delete(&conn, inserted_community.id).unwrap();
727     Person::delete(&conn, inserted_person.id).unwrap();
728     Person::delete(&conn, inserted_bot.id).unwrap();
729     Person::delete(&conn, inserted_blocked_person.id).unwrap();
730
731     // The with user
732     assert_eq!(
733       expected_post_listing_with_user,
734       read_post_listings_with_person[0]
735     );
736     assert_eq!(
737       expected_post_listing_with_user,
738       read_post_listing_with_person
739     );
740
741     // Should be only one person, IE the bot post, and blocked should be missing
742     assert_eq!(1, read_post_listings_with_person.len());
743
744     // Without the user
745     assert_eq!(
746       expected_post_listing_no_person,
747       read_post_listings_no_person[1]
748     );
749     assert_eq!(expected_post_listing_no_person, read_post_listing_no_person);
750
751     // Should be 2 posts, with the bot post, and the blocked
752     assert_eq!(3, read_post_listings_no_person.len());
753
754     // Should be 0 posts after the community block
755     assert_eq!(0, read_post_listings_with_person_after_block.len());
756
757     assert_eq!(expected_post_like, inserted_post_like);
758     assert_eq!(1, like_removed);
759     assert_eq!(1, num_deleted);
760   }
761 }