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