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