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