]> Untitled Git - lemmy.git/blob - crates/db_views/src/post_view.rs
e02310928a2e4484479ef0eadd91c87aa0405e49
[lemmy.git] / crates / db_views / src / post_view.rs
1 use crate::structs::{LocalUserView, PostView};
2 use diesel::{
3   debug_query,
4   dsl::{now, IntervalDsl},
5   pg::Pg,
6   result::Error,
7   sql_function,
8   sql_types,
9   BoolExpressionMethods,
10   ExpressionMethods,
11   JoinOnDsl,
12   NullableExpressionMethods,
13   PgTextExpressionMethods,
14   QueryDsl,
15 };
16 use diesel_async::RunQueryDsl;
17 use lemmy_db_schema::{
18   aggregates::structs::PostAggregates,
19   newtypes::{CommunityId, LocalUserId, PersonId, PostId},
20   schema::{
21     community,
22     community_block,
23     community_follower,
24     community_moderator,
25     community_person_ban,
26     local_user_language,
27     person,
28     person_block,
29     person_post_aggregates,
30     post,
31     post_aggregates,
32     post_like,
33     post_read,
34     post_saved,
35   },
36   source::{
37     community::{Community, CommunityFollower, CommunityPersonBan},
38     person::Person,
39     person_block::PersonBlock,
40     post::{Post, PostRead, PostSaved},
41   },
42   traits::JoinView,
43   utils::{fuzzy_search, get_conn, limit_and_offset, DbPool},
44   ListingType,
45   SortType,
46 };
47 use tracing::debug;
48
49 type PostViewTuple = (
50   Post,
51   Person,
52   Community,
53   Option<CommunityPersonBan>,
54   PostAggregates,
55   Option<CommunityFollower>,
56   Option<PostSaved>,
57   Option<PostRead>,
58   Option<PersonBlock>,
59   Option<i16>,
60   i64,
61 );
62
63 sql_function!(fn coalesce(x: sql_types::Nullable<sql_types::BigInt>, y: sql_types::BigInt) -> sql_types::BigInt);
64
65 impl PostView {
66   pub async fn read(
67     pool: &mut DbPool<'_>,
68     post_id: PostId,
69     my_person_id: Option<PersonId>,
70     is_mod_or_admin: Option<bool>,
71   ) -> Result<Self, Error> {
72     let conn = &mut get_conn(pool).await?;
73
74     // The left join below will return None in this case
75     let person_id_join = my_person_id.unwrap_or(PersonId(-1));
76     let mut query = post_aggregates::table
77       .filter(post_aggregates::post_id.eq(post_id))
78       .inner_join(person::table)
79       .inner_join(community::table)
80       .left_join(
81         community_person_ban::table.on(
82           post_aggregates::community_id
83             .eq(community_person_ban::community_id)
84             .and(community_person_ban::person_id.eq(post_aggregates::creator_id)),
85         ),
86       )
87       .inner_join(post::table)
88       .left_join(
89         community_follower::table.on(
90           post_aggregates::community_id
91             .eq(community_follower::community_id)
92             .and(community_follower::person_id.eq(person_id_join)),
93         ),
94       )
95       .left_join(
96         community_moderator::table.on(
97           post::community_id
98             .eq(community_moderator::community_id)
99             .and(community_moderator::person_id.eq(person_id_join)),
100         ),
101       )
102       .left_join(
103         post_saved::table.on(
104           post_aggregates::post_id
105             .eq(post_saved::post_id)
106             .and(post_saved::person_id.eq(person_id_join)),
107         ),
108       )
109       .left_join(
110         post_read::table.on(
111           post_aggregates::post_id
112             .eq(post_read::post_id)
113             .and(post_read::person_id.eq(person_id_join)),
114         ),
115       )
116       .left_join(
117         person_block::table.on(
118           post_aggregates::creator_id
119             .eq(person_block::target_id)
120             .and(person_block::person_id.eq(person_id_join)),
121         ),
122       )
123       .left_join(
124         post_like::table.on(
125           post_aggregates::post_id
126             .eq(post_like::post_id)
127             .and(post_like::person_id.eq(person_id_join)),
128         ),
129       )
130       .left_join(
131         person_post_aggregates::table.on(
132           post_aggregates::post_id
133             .eq(person_post_aggregates::post_id)
134             .and(person_post_aggregates::person_id.eq(person_id_join)),
135         ),
136       )
137       .select((
138         post::all_columns,
139         person::all_columns,
140         community::all_columns,
141         community_person_ban::all_columns.nullable(),
142         post_aggregates::all_columns,
143         community_follower::all_columns.nullable(),
144         post_saved::all_columns.nullable(),
145         post_read::all_columns.nullable(),
146         person_block::all_columns.nullable(),
147         post_like::score.nullable(),
148         coalesce(
149           post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
150           post_aggregates::comments,
151         ),
152       ))
153       .into_boxed();
154
155     // Hide deleted and removed for non-admins or mods
156     if !is_mod_or_admin.unwrap_or(false) {
157       query = query
158         .filter(community::removed.eq(false))
159         .filter(post::removed.eq(false))
160         // users can see their own deleted posts
161         .filter(
162           community::deleted
163             .eq(false)
164             .or(post::creator_id.eq(person_id_join)),
165         )
166         .filter(
167           post::deleted
168             .eq(false)
169             .or(post::creator_id.eq(person_id_join)),
170         );
171     }
172
173     let (
174       post,
175       creator,
176       community,
177       creator_banned_from_community,
178       counts,
179       follower,
180       saved,
181       read,
182       creator_blocked,
183       post_like,
184       unread_comments,
185     ) = query.first::<PostViewTuple>(conn).await?;
186
187     // If a person is given, then my_vote, if None, should be 0, not null
188     // Necessary to differentiate between other person's votes
189     let my_vote = if my_person_id.is_some() && post_like.is_none() {
190       Some(0)
191     } else {
192       post_like
193     };
194
195     Ok(PostView {
196       post,
197       creator,
198       community,
199       creator_banned_from_community: creator_banned_from_community.is_some(),
200       counts,
201       subscribed: CommunityFollower::to_subscribed_type(&follower),
202       saved: saved.is_some(),
203       read: read.is_some(),
204       creator_blocked: creator_blocked.is_some(),
205       my_vote,
206       unread_comments,
207     })
208   }
209 }
210
211 #[derive(Default)]
212 pub struct PostQuery<'a> {
213   pub listing_type: Option<ListingType>,
214   pub sort: Option<SortType>,
215   pub creator_id: Option<PersonId>,
216   pub community_id: Option<CommunityId>,
217   pub local_user: Option<&'a LocalUserView>,
218   pub search_term: Option<String>,
219   pub url_search: Option<String>,
220   pub saved_only: Option<bool>,
221   pub moderator_view: Option<bool>,
222   pub is_profile_view: Option<bool>,
223   pub page: Option<i64>,
224   pub limit: Option<i64>,
225 }
226
227 impl<'a> PostQuery<'a> {
228   pub async fn list(self, pool: &mut DbPool<'_>) -> Result<Vec<PostView>, Error> {
229     let conn = &mut get_conn(pool).await?;
230
231     // The left join below will return None in this case
232     let person_id_join = self.local_user.map(|l| l.person.id).unwrap_or(PersonId(-1));
233     let local_user_id_join = self
234       .local_user
235       .map(|l| l.local_user.id)
236       .unwrap_or(LocalUserId(-1));
237
238     let mut query = post_aggregates::table
239       .inner_join(person::table)
240       .inner_join(post::table)
241       .inner_join(community::table)
242       .left_join(
243         community_person_ban::table.on(
244           post_aggregates::community_id
245             .eq(community_person_ban::community_id)
246             .and(community_person_ban::person_id.eq(post_aggregates::creator_id)),
247         ),
248       )
249       .left_join(
250         community_follower::table.on(
251           post_aggregates::community_id
252             .eq(community_follower::community_id)
253             .and(community_follower::person_id.eq(person_id_join)),
254         ),
255       )
256       .left_join(
257         community_moderator::table.on(
258           post::community_id
259             .eq(community_moderator::community_id)
260             .and(community_moderator::person_id.eq(person_id_join)),
261         ),
262       )
263       .left_join(
264         post_saved::table.on(
265           post_aggregates::post_id
266             .eq(post_saved::post_id)
267             .and(post_saved::person_id.eq(person_id_join)),
268         ),
269       )
270       .left_join(
271         post_read::table.on(
272           post_aggregates::post_id
273             .eq(post_read::post_id)
274             .and(post_read::person_id.eq(person_id_join)),
275         ),
276       )
277       .left_join(
278         person_block::table.on(
279           post_aggregates::creator_id
280             .eq(person_block::target_id)
281             .and(person_block::person_id.eq(person_id_join)),
282         ),
283       )
284       .left_join(
285         community_block::table.on(
286           post_aggregates::community_id
287             .eq(community_block::community_id)
288             .and(community_block::person_id.eq(person_id_join)),
289         ),
290       )
291       .left_join(
292         post_like::table.on(
293           post_aggregates::post_id
294             .eq(post_like::post_id)
295             .and(post_like::person_id.eq(person_id_join)),
296         ),
297       )
298       .left_join(
299         person_post_aggregates::table.on(
300           post_aggregates::post_id
301             .eq(person_post_aggregates::post_id)
302             .and(person_post_aggregates::person_id.eq(person_id_join)),
303         ),
304       )
305       .left_join(
306         local_user_language::table.on(
307           post::language_id
308             .eq(local_user_language::language_id)
309             .and(local_user_language::local_user_id.eq(local_user_id_join)),
310         ),
311       )
312       .select((
313         post::all_columns,
314         person::all_columns,
315         community::all_columns,
316         community_person_ban::all_columns.nullable(),
317         post_aggregates::all_columns,
318         community_follower::all_columns.nullable(),
319         post_saved::all_columns.nullable(),
320         post_read::all_columns.nullable(),
321         person_block::all_columns.nullable(),
322         post_like::score.nullable(),
323         coalesce(
324           post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
325           post_aggregates::comments,
326         ),
327       ))
328       .into_boxed();
329
330     let is_profile_view = self.is_profile_view.unwrap_or(false);
331     let is_creator = self.creator_id == self.local_user.map(|l| l.person.id);
332     // only show deleted posts to creator
333     if is_creator {
334       query = query
335         .filter(community::deleted.eq(false))
336         .filter(post::deleted.eq(false));
337     }
338
339     let is_admin = self.local_user.map(|l| l.person.admin).unwrap_or(false);
340     // only show removed posts to admin when viewing user profile
341     if !(is_profile_view && is_admin) {
342       query = query
343         .filter(community::removed.eq(false))
344         .filter(post::removed.eq(false));
345     }
346
347     if self.community_id.is_none() {
348       query = query.then_order_by(post_aggregates::featured_local.desc());
349     } else if let Some(community_id) = self.community_id {
350       query = query
351         .filter(post_aggregates::community_id.eq(community_id))
352         .then_order_by(post_aggregates::featured_community.desc());
353     }
354
355     if let Some(creator_id) = self.creator_id {
356       query = query.filter(post_aggregates::creator_id.eq(creator_id));
357     }
358
359     if let Some(listing_type) = self.listing_type {
360       match listing_type {
361         ListingType::Subscribed => {
362           query = query.filter(community_follower::person_id.is_not_null())
363         }
364         ListingType::Local => {
365           query = query.filter(community::local.eq(true)).filter(
366             community::hidden
367               .eq(false)
368               .or(community_follower::person_id.eq(person_id_join)),
369           );
370         }
371         ListingType::All => {
372           query = query.filter(
373             community::hidden
374               .eq(false)
375               .or(community_follower::person_id.eq(person_id_join)),
376           )
377         }
378       }
379     }
380
381     if let Some(url_search) = self.url_search {
382       query = query.filter(post::url.eq(url_search));
383     }
384
385     if let Some(search_term) = self.search_term {
386       let searcher = fuzzy_search(&search_term);
387       query = query.filter(
388         post::name
389           .ilike(searcher.clone())
390           .or(post::body.ilike(searcher)),
391       );
392     }
393
394     if !self
395       .local_user
396       .map(|l| l.local_user.show_nsfw)
397       .unwrap_or(false)
398     {
399       query = query
400         .filter(post::nsfw.eq(false))
401         .filter(community::nsfw.eq(false));
402     };
403
404     if !self
405       .local_user
406       .map(|l| l.local_user.show_bot_accounts)
407       .unwrap_or(true)
408     {
409       query = query.filter(person::bot_account.eq(false));
410     };
411
412     if self.saved_only.unwrap_or(false) {
413       query = query.filter(post_saved::post_id.is_not_null());
414     }
415
416     if self.moderator_view.unwrap_or(false) {
417       query = query.filter(community_moderator::person_id.is_not_null());
418     }
419     // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
420     // setting wont be able to see saved posts.
421     else if !self
422       .local_user
423       .map(|l| l.local_user.show_read_posts)
424       .unwrap_or(true)
425     {
426       query = query.filter(post_read::post_id.is_null());
427     }
428
429     if self.local_user.is_some() {
430       // Filter out the rows with missing languages
431       query = query.filter(local_user_language::language_id.is_not_null());
432
433       // Don't show blocked communities or persons
434       query = query.filter(community_block::person_id.is_null());
435       if !self.moderator_view.unwrap_or(false) {
436         query = query.filter(person_block::person_id.is_null());
437       }
438     }
439
440     query = match self.sort.unwrap_or(SortType::Hot) {
441       SortType::Active => query
442         .then_order_by(post_aggregates::hot_rank_active.desc())
443         .then_order_by(post_aggregates::published.desc()),
444       SortType::Hot => query
445         .then_order_by(post_aggregates::hot_rank.desc())
446         .then_order_by(post_aggregates::published.desc()),
447       SortType::Controversial => query.then_order_by(post_aggregates::controversy_rank.desc()),
448       SortType::New => query.then_order_by(post_aggregates::published.desc()),
449       SortType::Old => query.then_order_by(post_aggregates::published.asc()),
450       SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
451       SortType::MostComments => query
452         .then_order_by(post_aggregates::comments.desc())
453         .then_order_by(post_aggregates::published.desc()),
454       SortType::TopAll => query
455         .then_order_by(post_aggregates::score.desc())
456         .then_order_by(post_aggregates::published.desc()),
457       SortType::TopYear => query
458         .filter(post_aggregates::published.gt(now - 1.years()))
459         .then_order_by(post_aggregates::score.desc())
460         .then_order_by(post_aggregates::published.desc()),
461       SortType::TopMonth => query
462         .filter(post_aggregates::published.gt(now - 1.months()))
463         .then_order_by(post_aggregates::score.desc())
464         .then_order_by(post_aggregates::published.desc()),
465       SortType::TopWeek => query
466         .filter(post_aggregates::published.gt(now - 1.weeks()))
467         .then_order_by(post_aggregates::score.desc())
468         .then_order_by(post_aggregates::published.desc()),
469       SortType::TopDay => query
470         .filter(post_aggregates::published.gt(now - 1.days()))
471         .then_order_by(post_aggregates::score.desc())
472         .then_order_by(post_aggregates::published.desc()),
473       SortType::TopHour => query
474         .filter(post_aggregates::published.gt(now - 1.hours()))
475         .then_order_by(post_aggregates::score.desc())
476         .then_order_by(post_aggregates::published.desc()),
477       SortType::TopSixHour => query
478         .filter(post_aggregates::published.gt(now - 6.hours()))
479         .then_order_by(post_aggregates::score.desc())
480         .then_order_by(post_aggregates::published.desc()),
481       SortType::TopTwelveHour => query
482         .filter(post_aggregates::published.gt(now - 12.hours()))
483         .then_order_by(post_aggregates::score.desc())
484         .then_order_by(post_aggregates::published.desc()),
485       SortType::TopThreeMonths => query
486         .filter(post_aggregates::published.gt(now - 3.months()))
487         .then_order_by(post_aggregates::score.desc())
488         .then_order_by(post_aggregates::published.desc()),
489       SortType::TopSixMonths => query
490         .filter(post_aggregates::published.gt(now - 6.months()))
491         .then_order_by(post_aggregates::score.desc())
492         .then_order_by(post_aggregates::published.desc()),
493       SortType::TopNineMonths => query
494         .filter(post_aggregates::published.gt(now - 9.months()))
495         .then_order_by(post_aggregates::score.desc())
496         .then_order_by(post_aggregates::published.desc()),
497     };
498
499     let (limit, offset) = limit_and_offset(self.page, self.limit)?;
500
501     query = query.limit(limit).offset(offset);
502
503     debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
504
505     let res = query.load::<PostViewTuple>(conn).await?;
506
507     Ok(res.into_iter().map(PostView::from_tuple).collect())
508   }
509 }
510
511 impl JoinView for PostView {
512   type JoinTuple = PostViewTuple;
513   fn from_tuple(a: Self::JoinTuple) -> Self {
514     Self {
515       post: a.0,
516       creator: a.1,
517       community: a.2,
518       creator_banned_from_community: a.3.is_some(),
519       counts: a.4,
520       subscribed: CommunityFollower::to_subscribed_type(&a.5),
521       saved: a.6.is_some(),
522       read: a.7.is_some(),
523       creator_blocked: a.8.is_some(),
524       my_vote: a.9,
525       unread_comments: a.10,
526     }
527   }
528 }
529
530 #[cfg(test)]
531 mod tests {
532   #![allow(clippy::unwrap_used)]
533   #![allow(clippy::indexing_slicing)]
534
535   use crate::{
536     post_view::{PostQuery, PostView},
537     structs::LocalUserView,
538   };
539   use lemmy_db_schema::{
540     aggregates::structs::PostAggregates,
541     impls::actor_language::UNDETERMINED_ID,
542     newtypes::LanguageId,
543     source::{
544       actor_language::LocalUserLanguage,
545       community::{Community, CommunityInsertForm},
546       community_block::{CommunityBlock, CommunityBlockForm},
547       instance::Instance,
548       language::Language,
549       local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm},
550       person::{Person, PersonInsertForm},
551       person_block::{PersonBlock, PersonBlockForm},
552       post::{Post, PostInsertForm, PostLike, PostLikeForm, PostUpdateForm},
553     },
554     traits::{Blockable, Crud, Likeable},
555     utils::{build_db_pool_for_tests, DbPool},
556     SortType,
557     SubscribedType,
558   };
559   use serial_test::serial;
560
561   struct Data {
562     inserted_instance: Instance,
563     local_user_view: LocalUserView,
564     inserted_blocked_person: Person,
565     inserted_bot: Person,
566     inserted_community: Community,
567     inserted_post: Post,
568   }
569
570   async fn init_data(pool: &mut DbPool<'_>) -> Data {
571     let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
572       .await
573       .unwrap();
574
575     let person_name = "tegan".to_string();
576
577     let new_person = PersonInsertForm::builder()
578       .name(person_name.clone())
579       .public_key("pubkey".to_string())
580       .instance_id(inserted_instance.id)
581       .build();
582
583     let inserted_person = Person::create(pool, &new_person).await.unwrap();
584
585     let local_user_form = LocalUserInsertForm::builder()
586       .person_id(inserted_person.id)
587       .password_encrypted(String::new())
588       .build();
589     let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
590
591     let new_bot = PersonInsertForm::builder()
592       .name("mybot".to_string())
593       .bot_account(Some(true))
594       .public_key("pubkey".to_string())
595       .instance_id(inserted_instance.id)
596       .build();
597
598     let inserted_bot = Person::create(pool, &new_bot).await.unwrap();
599
600     let new_community = CommunityInsertForm::builder()
601       .name("test_community_3".to_string())
602       .title("nada".to_owned())
603       .public_key("pubkey".to_string())
604       .instance_id(inserted_instance.id)
605       .build();
606
607     let inserted_community = Community::create(pool, &new_community).await.unwrap();
608
609     // Test a person block, make sure the post query doesn't include their post
610     let blocked_person = PersonInsertForm::builder()
611       .name(person_name)
612       .public_key("pubkey".to_string())
613       .instance_id(inserted_instance.id)
614       .build();
615
616     let inserted_blocked_person = Person::create(pool, &blocked_person).await.unwrap();
617
618     let post_from_blocked_person = PostInsertForm::builder()
619       .name("blocked_person_post".to_string())
620       .creator_id(inserted_blocked_person.id)
621       .community_id(inserted_community.id)
622       .language_id(Some(LanguageId(1)))
623       .build();
624
625     Post::create(pool, &post_from_blocked_person).await.unwrap();
626
627     // block that person
628     let person_block = PersonBlockForm {
629       person_id: inserted_person.id,
630       target_id: inserted_blocked_person.id,
631     };
632
633     PersonBlock::block(pool, &person_block).await.unwrap();
634
635     // A sample post
636     let new_post = PostInsertForm::builder()
637       .name("test post 3".to_string())
638       .creator_id(inserted_person.id)
639       .community_id(inserted_community.id)
640       .language_id(Some(LanguageId(47)))
641       .build();
642
643     let inserted_post = Post::create(pool, &new_post).await.unwrap();
644
645     let new_bot_post = PostInsertForm::builder()
646       .name("test bot post".to_string())
647       .creator_id(inserted_bot.id)
648       .community_id(inserted_community.id)
649       .build();
650
651     let _inserted_bot_post = Post::create(pool, &new_bot_post).await.unwrap();
652     let local_user_view = LocalUserView {
653       local_user: inserted_local_user,
654       person: inserted_person,
655       counts: Default::default(),
656     };
657
658     Data {
659       inserted_instance,
660       local_user_view,
661       inserted_blocked_person,
662       inserted_bot,
663       inserted_community,
664       inserted_post,
665     }
666   }
667
668   #[tokio::test]
669   #[serial]
670   async fn post_listing_with_person() {
671     let pool = &build_db_pool_for_tests().await;
672     let pool = &mut pool.into();
673     let mut data = init_data(pool).await;
674
675     let local_user_form = LocalUserUpdateForm::builder()
676       .show_bot_accounts(Some(false))
677       .build();
678     let inserted_local_user =
679       LocalUser::update(pool, data.local_user_view.local_user.id, &local_user_form)
680         .await
681         .unwrap();
682     data.local_user_view.local_user = inserted_local_user;
683
684     let read_post_listing = PostQuery {
685       sort: (Some(SortType::New)),
686       community_id: (Some(data.inserted_community.id)),
687       local_user: (Some(&data.local_user_view)),
688       ..Default::default()
689     }
690     .list(pool)
691     .await
692     .unwrap();
693
694     let post_listing_single_with_person = PostView::read(
695       pool,
696       data.inserted_post.id,
697       Some(data.local_user_view.person.id),
698       None,
699     )
700     .await
701     .unwrap();
702
703     let mut expected_post_listing_with_user = expected_post_view(&data, pool).await;
704
705     // Should be only one person, IE the bot post, and blocked should be missing
706     assert_eq!(1, read_post_listing.len());
707
708     assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
709     expected_post_listing_with_user.my_vote = Some(0);
710     assert_eq!(
711       expected_post_listing_with_user,
712       post_listing_single_with_person
713     );
714
715     let local_user_form = LocalUserUpdateForm::builder()
716       .show_bot_accounts(Some(true))
717       .build();
718     let inserted_local_user =
719       LocalUser::update(pool, data.local_user_view.local_user.id, &local_user_form)
720         .await
721         .unwrap();
722     data.local_user_view.local_user = inserted_local_user;
723
724     let post_listings_with_bots = PostQuery {
725       sort: (Some(SortType::New)),
726       community_id: (Some(data.inserted_community.id)),
727       local_user: (Some(&data.local_user_view)),
728       ..Default::default()
729     }
730     .list(pool)
731     .await
732     .unwrap();
733     // should include bot post which has "undetermined" language
734     assert_eq!(2, post_listings_with_bots.len());
735
736     cleanup(data, pool).await;
737   }
738
739   #[tokio::test]
740   #[serial]
741   async fn post_listing_no_person() {
742     let pool = &build_db_pool_for_tests().await;
743     let pool = &mut pool.into();
744     let data = init_data(pool).await;
745
746     let read_post_listing_multiple_no_person = PostQuery {
747       sort: (Some(SortType::New)),
748       community_id: (Some(data.inserted_community.id)),
749       ..Default::default()
750     }
751     .list(pool)
752     .await
753     .unwrap();
754
755     let read_post_listing_single_no_person =
756       PostView::read(pool, data.inserted_post.id, None, None)
757         .await
758         .unwrap();
759
760     let expected_post_listing_no_person = expected_post_view(&data, pool).await;
761
762     // Should be 2 posts, with the bot post, and the blocked
763     assert_eq!(3, read_post_listing_multiple_no_person.len());
764
765     assert_eq!(
766       expected_post_listing_no_person,
767       read_post_listing_multiple_no_person[1]
768     );
769     assert_eq!(
770       expected_post_listing_no_person,
771       read_post_listing_single_no_person
772     );
773
774     cleanup(data, pool).await;
775   }
776
777   #[tokio::test]
778   #[serial]
779   async fn post_listing_block_community() {
780     let pool = &build_db_pool_for_tests().await;
781     let pool = &mut pool.into();
782     let data = init_data(pool).await;
783
784     let community_block = CommunityBlockForm {
785       person_id: data.local_user_view.person.id,
786       community_id: data.inserted_community.id,
787     };
788     CommunityBlock::block(pool, &community_block).await.unwrap();
789
790     let read_post_listings_with_person_after_block = PostQuery {
791       sort: (Some(SortType::New)),
792       community_id: (Some(data.inserted_community.id)),
793       local_user: (Some(&data.local_user_view)),
794       ..Default::default()
795     }
796     .list(pool)
797     .await
798     .unwrap();
799     // Should be 0 posts after the community block
800     assert_eq!(0, read_post_listings_with_person_after_block.len());
801
802     CommunityBlock::unblock(pool, &community_block)
803       .await
804       .unwrap();
805     cleanup(data, pool).await;
806   }
807
808   #[tokio::test]
809   #[serial]
810   async fn post_listing_like() {
811     let pool = &build_db_pool_for_tests().await;
812     let pool = &mut pool.into();
813     let mut data = init_data(pool).await;
814
815     let post_like_form = PostLikeForm {
816       post_id: data.inserted_post.id,
817       person_id: data.local_user_view.person.id,
818       score: 1,
819     };
820
821     let inserted_post_like = PostLike::like(pool, &post_like_form).await.unwrap();
822
823     let expected_post_like = PostLike {
824       id: inserted_post_like.id,
825       post_id: data.inserted_post.id,
826       person_id: data.local_user_view.person.id,
827       published: inserted_post_like.published,
828       score: 1,
829     };
830     assert_eq!(expected_post_like, inserted_post_like);
831
832     let post_listing_single_with_person = PostView::read(
833       pool,
834       data.inserted_post.id,
835       Some(data.local_user_view.person.id),
836       None,
837     )
838     .await
839     .unwrap();
840
841     let mut expected_post_with_upvote = expected_post_view(&data, pool).await;
842     expected_post_with_upvote.my_vote = Some(1);
843     expected_post_with_upvote.counts.score = 1;
844     expected_post_with_upvote.counts.upvotes = 1;
845     assert_eq!(expected_post_with_upvote, post_listing_single_with_person);
846
847     let local_user_form = LocalUserUpdateForm::builder()
848       .show_bot_accounts(Some(false))
849       .build();
850     let inserted_local_user =
851       LocalUser::update(pool, data.local_user_view.local_user.id, &local_user_form)
852         .await
853         .unwrap();
854     data.local_user_view.local_user = inserted_local_user;
855
856     let read_post_listing = PostQuery {
857       sort: (Some(SortType::New)),
858       community_id: (Some(data.inserted_community.id)),
859       local_user: (Some(&data.local_user_view)),
860       ..Default::default()
861     }
862     .list(pool)
863     .await
864     .unwrap();
865     assert_eq!(1, read_post_listing.len());
866
867     assert_eq!(expected_post_with_upvote, read_post_listing[0]);
868
869     let like_removed =
870       PostLike::remove(pool, data.local_user_view.person.id, data.inserted_post.id)
871         .await
872         .unwrap();
873     assert_eq!(1, like_removed);
874     cleanup(data, pool).await;
875   }
876
877   #[tokio::test]
878   #[serial]
879   async fn post_listing_person_language() {
880     let pool = &build_db_pool_for_tests().await;
881     let pool = &mut pool.into();
882     let data = init_data(pool).await;
883
884     let spanish_id = Language::read_id_from_code(pool, Some("es"))
885       .await
886       .unwrap()
887       .unwrap();
888     let post_spanish = PostInsertForm::builder()
889       .name("asffgdsc".to_string())
890       .creator_id(data.local_user_view.person.id)
891       .community_id(data.inserted_community.id)
892       .language_id(Some(spanish_id))
893       .build();
894
895     Post::create(pool, &post_spanish).await.unwrap();
896
897     let post_listings_all = PostQuery {
898       sort: (Some(SortType::New)),
899       local_user: (Some(&data.local_user_view)),
900       ..Default::default()
901     }
902     .list(pool)
903     .await
904     .unwrap();
905
906     // no language filters specified, all posts should be returned
907     assert_eq!(3, post_listings_all.len());
908
909     let french_id = Language::read_id_from_code(pool, Some("fr"))
910       .await
911       .unwrap()
912       .unwrap();
913     LocalUserLanguage::update(pool, vec![french_id], data.local_user_view.local_user.id)
914       .await
915       .unwrap();
916
917     let post_listing_french = PostQuery {
918       sort: (Some(SortType::New)),
919       local_user: (Some(&data.local_user_view)),
920       ..Default::default()
921     }
922     .list(pool)
923     .await
924     .unwrap();
925
926     // only one post in french and one undetermined should be returned
927     assert_eq!(2, post_listing_french.len());
928     assert!(post_listing_french
929       .iter()
930       .any(|p| p.post.language_id == french_id));
931
932     LocalUserLanguage::update(
933       pool,
934       vec![french_id, UNDETERMINED_ID],
935       data.local_user_view.local_user.id,
936     )
937     .await
938     .unwrap();
939     let post_listings_french_und = PostQuery {
940       sort: (Some(SortType::New)),
941       local_user: (Some(&data.local_user_view)),
942       ..Default::default()
943     }
944     .list(pool)
945     .await
946     .unwrap();
947
948     // french post and undetermined language post should be returned
949     assert_eq!(2, post_listings_french_und.len());
950     assert_eq!(
951       UNDETERMINED_ID,
952       post_listings_french_und[0].post.language_id
953     );
954     assert_eq!(french_id, post_listings_french_und[1].post.language_id);
955
956     cleanup(data, pool).await;
957   }
958
959   #[tokio::test]
960   #[serial]
961   async fn post_listings_removed() {
962     let pool = &build_db_pool_for_tests().await;
963     let pool = &mut pool.into();
964     let mut data = init_data(pool).await;
965
966     // Remove the post
967     Post::update(
968       pool,
969       data.inserted_post.id,
970       &PostUpdateForm::builder().removed(Some(true)).build(),
971     )
972     .await
973     .unwrap();
974
975     // Make sure you don't see the removed post in the results
976     let post_listings_no_admin = PostQuery {
977       sort: Some(SortType::New),
978       local_user: Some(&data.local_user_view),
979       ..Default::default()
980     }
981     .list(pool)
982     .await
983     .unwrap();
984     assert_eq!(1, post_listings_no_admin.len());
985
986     // Removed post is shown to admins on profile page
987     data.local_user_view.person.admin = true;
988     let post_listings_is_admin = PostQuery {
989       sort: Some(SortType::New),
990       local_user: Some(&data.local_user_view),
991       is_profile_view: Some(true),
992       ..Default::default()
993     }
994     .list(pool)
995     .await
996     .unwrap();
997     assert_eq!(2, post_listings_is_admin.len());
998
999     cleanup(data, pool).await;
1000   }
1001
1002   #[tokio::test]
1003   #[serial]
1004   async fn post_listings_deleted() {
1005     let pool = &build_db_pool_for_tests().await;
1006     let pool = &mut pool.into();
1007     let data = init_data(pool).await;
1008
1009     // Delete the post
1010     Post::update(
1011       pool,
1012       data.inserted_post.id,
1013       &PostUpdateForm::builder().deleted(Some(true)).build(),
1014     )
1015     .await
1016     .unwrap();
1017
1018     // Make sure you don't see the deleted post in the results
1019     let post_listings_no_creator = PostQuery {
1020       sort: Some(SortType::New),
1021       ..Default::default()
1022     }
1023     .list(pool)
1024     .await
1025     .unwrap();
1026     let not_contains_deleted = post_listings_no_creator
1027       .iter()
1028       .map(|p| p.post.id)
1029       .all(|p| p != data.inserted_post.id);
1030     assert!(not_contains_deleted);
1031
1032     // Deleted post is shown to creator
1033     let post_listings_is_creator = PostQuery {
1034       sort: Some(SortType::New),
1035       local_user: Some(&data.local_user_view),
1036       ..Default::default()
1037     }
1038     .list(pool)
1039     .await
1040     .unwrap();
1041     let contains_deleted = post_listings_is_creator
1042       .iter()
1043       .map(|p| p.post.id)
1044       .any(|p| p == data.inserted_post.id);
1045     assert!(contains_deleted);
1046
1047     cleanup(data, pool).await;
1048   }
1049
1050   async fn cleanup(data: Data, pool: &mut DbPool<'_>) {
1051     let num_deleted = Post::delete(pool, data.inserted_post.id).await.unwrap();
1052     Community::delete(pool, data.inserted_community.id)
1053       .await
1054       .unwrap();
1055     Person::delete(pool, data.local_user_view.person.id)
1056       .await
1057       .unwrap();
1058     Person::delete(pool, data.inserted_bot.id).await.unwrap();
1059     Person::delete(pool, data.inserted_blocked_person.id)
1060       .await
1061       .unwrap();
1062     Instance::delete(pool, data.inserted_instance.id)
1063       .await
1064       .unwrap();
1065     assert_eq!(1, num_deleted);
1066   }
1067
1068   async fn expected_post_view(data: &Data, pool: &mut DbPool<'_>) -> PostView {
1069     let (inserted_person, inserted_community, inserted_post) = (
1070       &data.local_user_view.person,
1071       &data.inserted_community,
1072       &data.inserted_post,
1073     );
1074     let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap();
1075
1076     PostView {
1077       post: Post {
1078         id: inserted_post.id,
1079         name: inserted_post.name.clone(),
1080         creator_id: inserted_person.id,
1081         url: None,
1082         body: None,
1083         published: inserted_post.published,
1084         updated: None,
1085         community_id: inserted_community.id,
1086         removed: false,
1087         deleted: false,
1088         locked: false,
1089         nsfw: false,
1090         embed_title: None,
1091         embed_description: None,
1092         embed_video_url: None,
1093         thumbnail_url: None,
1094         ap_id: inserted_post.ap_id.clone(),
1095         local: true,
1096         language_id: LanguageId(47),
1097         featured_community: false,
1098         featured_local: false,
1099       },
1100       my_vote: None,
1101       unread_comments: 0,
1102       creator: Person {
1103         id: inserted_person.id,
1104         name: inserted_person.name.clone(),
1105         display_name: None,
1106         published: inserted_person.published,
1107         avatar: None,
1108         actor_id: inserted_person.actor_id.clone(),
1109         local: true,
1110         admin: false,
1111         bot_account: false,
1112         banned: false,
1113         deleted: false,
1114         bio: None,
1115         banner: None,
1116         updated: None,
1117         inbox_url: inserted_person.inbox_url.clone(),
1118         shared_inbox_url: None,
1119         matrix_user_id: None,
1120         ban_expires: None,
1121         instance_id: data.inserted_instance.id,
1122         private_key: inserted_person.private_key.clone(),
1123         public_key: inserted_person.public_key.clone(),
1124         last_refreshed_at: inserted_person.last_refreshed_at,
1125       },
1126       creator_banned_from_community: false,
1127       community: Community {
1128         id: inserted_community.id,
1129         name: inserted_community.name.clone(),
1130         icon: None,
1131         removed: false,
1132         deleted: false,
1133         nsfw: false,
1134         actor_id: inserted_community.actor_id.clone(),
1135         local: true,
1136         title: "nada".to_owned(),
1137         description: None,
1138         updated: None,
1139         banner: None,
1140         hidden: false,
1141         posting_restricted_to_mods: false,
1142         published: inserted_community.published,
1143         instance_id: data.inserted_instance.id,
1144         private_key: inserted_community.private_key.clone(),
1145         public_key: inserted_community.public_key.clone(),
1146         last_refreshed_at: inserted_community.last_refreshed_at,
1147         followers_url: inserted_community.followers_url.clone(),
1148         inbox_url: inserted_community.inbox_url.clone(),
1149         shared_inbox_url: inserted_community.shared_inbox_url.clone(),
1150         moderators_url: inserted_community.moderators_url.clone(),
1151         featured_url: inserted_community.featured_url.clone(),
1152       },
1153       counts: PostAggregates {
1154         id: agg.id,
1155         post_id: inserted_post.id,
1156         comments: 0,
1157         score: 0,
1158         upvotes: 0,
1159         downvotes: 0,
1160         published: agg.published,
1161         newest_comment_time_necro: inserted_post.published,
1162         newest_comment_time: inserted_post.published,
1163         featured_community: false,
1164         featured_local: false,
1165         hot_rank: 1728,
1166         hot_rank_active: 1728,
1167         controversy_rank: 0.0,
1168         community_id: inserted_post.community_id,
1169         creator_id: inserted_post.creator_id,
1170       },
1171       subscribed: SubscribedType::NotSubscribed,
1172       read: false,
1173       saved: false,
1174       creator_blocked: false,
1175     }
1176   }
1177 }