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