]> Untitled Git - lemmy.git/blob - crates/db_views/src/post_view.rs
Remove federation backwards compatibility with 0.16.x (#2183)
[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
328     if let Some(community_id) = self.community_id {
329       query = query
330         .filter(post::community_id.eq(community_id))
331         .then_order_by(post_aggregates::stickied.desc());
332     }
333
334     if let Some(community_actor_id) = self.community_actor_id {
335       query = query
336         .filter(community::actor_id.eq(community_actor_id))
337         .then_order_by(post_aggregates::stickied.desc());
338     }
339
340     if let Some(url_search) = self.url_search {
341       query = query.filter(post::url.eq(url_search));
342     }
343
344     if let Some(search_term) = self.search_term {
345       let searcher = fuzzy_search(&search_term);
346       query = query.filter(
347         post::name
348           .ilike(searcher.clone())
349           .or(post::body.ilike(searcher)),
350       );
351     }
352
353     // If its for a specific person, show the removed / deleted
354     if let Some(creator_id) = self.creator_id {
355       query = query.filter(post::creator_id.eq(creator_id));
356     }
357
358     if !self.local_user.map(|l| l.show_nsfw).unwrap_or(false) {
359       query = query
360         .filter(post::nsfw.eq(false))
361         .filter(community::nsfw.eq(false));
362     };
363
364     if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
365       query = query.filter(person::bot_account.eq(false));
366     };
367
368     if self.saved_only.unwrap_or(false) {
369       query = query.filter(post_saved::id.is_not_null());
370     }
371     // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
372     // setting wont be able to see saved posts.
373     else if !self.local_user.map(|l| l.show_read_posts).unwrap_or(true) {
374       query = query.filter(post_read::id.is_null());
375     }
376
377     if self.local_user.is_some() {
378       // Filter out the rows with missing languages
379       query = query.filter(local_user_language::id.is_not_null());
380
381       // Don't show blocked communities or persons
382       query = query.filter(community_block::person_id.is_null());
383       query = query.filter(person_block::person_id.is_null());
384     }
385
386     query = match self.sort.unwrap_or(SortType::Hot) {
387       SortType::Active => query
388         .then_order_by(
389           hot_rank(
390             post_aggregates::score,
391             post_aggregates::newest_comment_time_necro,
392           )
393           .desc(),
394         )
395         .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
396       SortType::Hot => query
397         .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
398         .then_order_by(post_aggregates::published.desc()),
399       SortType::New => query.then_order_by(post_aggregates::published.desc()),
400       SortType::Old => query.then_order_by(post_aggregates::published.asc()),
401       SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
402       SortType::MostComments => query
403         .then_order_by(post_aggregates::comments.desc())
404         .then_order_by(post_aggregates::published.desc()),
405       SortType::TopAll => query
406         .then_order_by(post_aggregates::score.desc())
407         .then_order_by(post_aggregates::published.desc()),
408       SortType::TopYear => query
409         .filter(post_aggregates::published.gt(now - 1.years()))
410         .then_order_by(post_aggregates::score.desc())
411         .then_order_by(post_aggregates::published.desc()),
412       SortType::TopMonth => query
413         .filter(post_aggregates::published.gt(now - 1.months()))
414         .then_order_by(post_aggregates::score.desc())
415         .then_order_by(post_aggregates::published.desc()),
416       SortType::TopWeek => query
417         .filter(post_aggregates::published.gt(now - 1.weeks()))
418         .then_order_by(post_aggregates::score.desc())
419         .then_order_by(post_aggregates::published.desc()),
420       SortType::TopDay => query
421         .filter(post_aggregates::published.gt(now - 1.days()))
422         .then_order_by(post_aggregates::score.desc())
423         .then_order_by(post_aggregates::published.desc()),
424     };
425
426     let (limit, offset) = limit_and_offset(self.page, self.limit)?;
427
428     query = query
429       .limit(limit)
430       .offset(offset)
431       .filter(post::removed.eq(false))
432       .filter(post::deleted.eq(false))
433       .filter(community::removed.eq(false))
434       .filter(community::deleted.eq(false));
435
436     debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
437
438     let res = query.load::<PostViewTuple>(conn).await?;
439
440     Ok(PostView::from_tuple_to_vec(res))
441   }
442 }
443
444 impl ViewToVec for PostView {
445   type DbTuple = PostViewTuple;
446   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
447     items
448       .into_iter()
449       .map(|a| Self {
450         post: a.0,
451         creator: a.1,
452         community: a.2,
453         creator_banned_from_community: a.3.is_some(),
454         counts: a.4,
455         subscribed: CommunityFollower::to_subscribed_type(&a.5),
456         saved: a.6.is_some(),
457         read: a.7.is_some(),
458         creator_blocked: a.8.is_some(),
459         my_vote: a.9,
460         unread_comments: a.10,
461       })
462       .collect::<Vec<Self>>()
463   }
464 }
465
466 #[cfg(test)]
467 mod tests {
468   use crate::post_view::{PostQuery, PostView};
469   use lemmy_db_schema::{
470     aggregates::structs::PostAggregates,
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::create(pool, "my_domain.tld").await.unwrap();
502
503     let person_name = "tegan".to_string();
504
505     let new_person = PersonInsertForm::builder()
506       .name(person_name.clone())
507       .public_key("pubkey".to_string())
508       .instance_id(inserted_instance.id)
509       .build();
510
511     let inserted_person = Person::create(pool, &new_person).await.unwrap();
512
513     let local_user_form = LocalUserInsertForm::builder()
514       .person_id(inserted_person.id)
515       .password_encrypted(String::new())
516       .build();
517     let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
518
519     let new_bot = PersonInsertForm::builder()
520       .name("mybot".to_string())
521       .bot_account(Some(true))
522       .public_key("pubkey".to_string())
523       .instance_id(inserted_instance.id)
524       .build();
525
526     let inserted_bot = Person::create(pool, &new_bot).await.unwrap();
527
528     let new_community = CommunityInsertForm::builder()
529       .name("test_community_3".to_string())
530       .title("nada".to_owned())
531       .public_key("pubkey".to_string())
532       .instance_id(inserted_instance.id)
533       .build();
534
535     let inserted_community = Community::create(pool, &new_community).await.unwrap();
536
537     // Test a person block, make sure the post query doesn't include their post
538     let blocked_person = PersonInsertForm::builder()
539       .name(person_name)
540       .public_key("pubkey".to_string())
541       .instance_id(inserted_instance.id)
542       .build();
543
544     let inserted_blocked_person = Person::create(pool, &blocked_person).await.unwrap();
545
546     let post_from_blocked_person = PostInsertForm::builder()
547       .name("blocked_person_post".to_string())
548       .creator_id(inserted_blocked_person.id)
549       .community_id(inserted_community.id)
550       .language_id(Some(LanguageId(1)))
551       .build();
552
553     Post::create(pool, &post_from_blocked_person).await.unwrap();
554
555     // block that person
556     let person_block = PersonBlockForm {
557       person_id: inserted_person.id,
558       target_id: inserted_blocked_person.id,
559     };
560
561     PersonBlock::block(pool, &person_block).await.unwrap();
562
563     // A sample post
564     let new_post = PostInsertForm::builder()
565       .name("test post 3".to_string())
566       .creator_id(inserted_person.id)
567       .community_id(inserted_community.id)
568       .language_id(Some(LanguageId(47)))
569       .build();
570
571     let inserted_post = Post::create(pool, &new_post).await.unwrap();
572
573     let new_bot_post = PostInsertForm::builder()
574       .name("test bot post".to_string())
575       .creator_id(inserted_bot.id)
576       .community_id(inserted_community.id)
577       .build();
578
579     let _inserted_bot_post = Post::create(pool, &new_bot_post).await.unwrap();
580
581     Data {
582       inserted_instance,
583       inserted_person,
584       inserted_local_user,
585       inserted_blocked_person,
586       inserted_bot,
587       inserted_community,
588       inserted_post,
589     }
590   }
591
592   #[tokio::test]
593   #[serial]
594   async fn post_listing_with_person() {
595     let pool = &build_db_pool_for_tests().await;
596     let data = init_data(pool).await;
597
598     let local_user_form = LocalUserUpdateForm::builder()
599       .show_bot_accounts(Some(false))
600       .build();
601     let inserted_local_user =
602       LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
603         .await
604         .unwrap();
605
606     let read_post_listing = PostQuery::builder()
607       .pool(pool)
608       .sort(Some(SortType::New))
609       .community_id(Some(data.inserted_community.id))
610       .local_user(Some(&inserted_local_user))
611       .build()
612       .list()
613       .await
614       .unwrap();
615
616     let post_listing_single_with_person =
617       PostView::read(pool, data.inserted_post.id, Some(data.inserted_person.id))
618         .await
619         .unwrap();
620
621     let mut expected_post_listing_with_user = expected_post_view(&data, pool).await;
622
623     // Should be only one person, IE the bot post, and blocked should be missing
624     assert_eq!(1, read_post_listing.len());
625
626     assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
627     expected_post_listing_with_user.my_vote = Some(0);
628     assert_eq!(
629       expected_post_listing_with_user,
630       post_listing_single_with_person
631     );
632
633     let local_user_form = LocalUserUpdateForm::builder()
634       .show_bot_accounts(Some(true))
635       .build();
636     let inserted_local_user =
637       LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
638         .await
639         .unwrap();
640
641     let post_listings_with_bots = PostQuery::builder()
642       .pool(pool)
643       .sort(Some(SortType::New))
644       .community_id(Some(data.inserted_community.id))
645       .local_user(Some(&inserted_local_user))
646       .build()
647       .list()
648       .await
649       .unwrap();
650     // should include bot post which has "undetermined" language
651     assert_eq!(2, post_listings_with_bots.len());
652
653     cleanup(data, pool).await;
654   }
655
656   #[tokio::test]
657   #[serial]
658   async fn post_listing_no_person() {
659     let pool = &build_db_pool_for_tests().await;
660     let data = init_data(pool).await;
661
662     let read_post_listing_multiple_no_person = PostQuery::builder()
663       .pool(pool)
664       .sort(Some(SortType::New))
665       .community_id(Some(data.inserted_community.id))
666       .build()
667       .list()
668       .await
669       .unwrap();
670
671     let read_post_listing_single_no_person = PostView::read(pool, data.inserted_post.id, None)
672       .await
673       .unwrap();
674
675     let expected_post_listing_no_person = expected_post_view(&data, pool).await;
676
677     // Should be 2 posts, with the bot post, and the blocked
678     assert_eq!(3, read_post_listing_multiple_no_person.len());
679
680     assert_eq!(
681       expected_post_listing_no_person,
682       read_post_listing_multiple_no_person[1]
683     );
684     assert_eq!(
685       expected_post_listing_no_person,
686       read_post_listing_single_no_person
687     );
688
689     cleanup(data, pool).await;
690   }
691
692   #[tokio::test]
693   #[serial]
694   async fn post_listing_block_community() {
695     let pool = &build_db_pool_for_tests().await;
696     let data = init_data(pool).await;
697
698     let community_block = CommunityBlockForm {
699       person_id: data.inserted_person.id,
700       community_id: data.inserted_community.id,
701     };
702     CommunityBlock::block(pool, &community_block).await.unwrap();
703
704     let read_post_listings_with_person_after_block = PostQuery::builder()
705       .pool(pool)
706       .sort(Some(SortType::New))
707       .community_id(Some(data.inserted_community.id))
708       .local_user(Some(&data.inserted_local_user))
709       .build()
710       .list()
711       .await
712       .unwrap();
713     // Should be 0 posts after the community block
714     assert_eq!(0, read_post_listings_with_person_after_block.len());
715
716     CommunityBlock::unblock(pool, &community_block)
717       .await
718       .unwrap();
719     cleanup(data, pool).await;
720   }
721
722   #[tokio::test]
723   #[serial]
724   async fn post_listing_like() {
725     let pool = &build_db_pool_for_tests().await;
726     let data = init_data(pool).await;
727
728     let post_like_form = PostLikeForm {
729       post_id: data.inserted_post.id,
730       person_id: data.inserted_person.id,
731       score: 1,
732     };
733
734     let inserted_post_like = PostLike::like(pool, &post_like_form).await.unwrap();
735
736     let expected_post_like = PostLike {
737       id: inserted_post_like.id,
738       post_id: data.inserted_post.id,
739       person_id: data.inserted_person.id,
740       published: inserted_post_like.published,
741       score: 1,
742     };
743     assert_eq!(expected_post_like, inserted_post_like);
744
745     let like_removed = PostLike::remove(pool, data.inserted_person.id, data.inserted_post.id)
746       .await
747       .unwrap();
748     assert_eq!(1, like_removed);
749     cleanup(data, pool).await;
750   }
751
752   #[tokio::test]
753   #[serial]
754   async fn post_listing_person_language() {
755     let pool = &build_db_pool_for_tests().await;
756     let data = init_data(pool).await;
757
758     let spanish_id = Language::read_id_from_code(pool, "es").await.unwrap();
759     let post_spanish = PostInsertForm::builder()
760       .name("asffgdsc".to_string())
761       .creator_id(data.inserted_person.id)
762       .community_id(data.inserted_community.id)
763       .language_id(Some(spanish_id))
764       .build();
765
766     Post::create(pool, &post_spanish).await.unwrap();
767
768     let post_listings_all = PostQuery::builder()
769       .pool(pool)
770       .sort(Some(SortType::New))
771       .local_user(Some(&data.inserted_local_user))
772       .build()
773       .list()
774       .await
775       .unwrap();
776
777     // no language filters specified, all posts should be returned
778     assert_eq!(3, post_listings_all.len());
779
780     let french_id = Language::read_id_from_code(pool, "fr").await.unwrap();
781     LocalUserLanguage::update(pool, vec![french_id], data.inserted_local_user.id)
782       .await
783       .unwrap();
784
785     let post_listing_french = PostQuery::builder()
786       .pool(pool)
787       .sort(Some(SortType::New))
788       .local_user(Some(&data.inserted_local_user))
789       .build()
790       .list()
791       .await
792       .unwrap();
793
794     // only one french language post should be returned
795     assert_eq!(1, post_listing_french.len());
796     assert_eq!(french_id, post_listing_french[0].post.language_id);
797
798     let undetermined_id = Language::read_id_from_code(pool, "und").await.unwrap();
799     LocalUserLanguage::update(
800       pool,
801       vec![french_id, undetermined_id],
802       data.inserted_local_user.id,
803     )
804     .await
805     .unwrap();
806     let post_listings_french_und = PostQuery::builder()
807       .pool(pool)
808       .sort(Some(SortType::New))
809       .local_user(Some(&data.inserted_local_user))
810       .build()
811       .list()
812       .await
813       .unwrap();
814
815     // french post and undetermined language post should be returned
816     assert_eq!(2, post_listings_french_und.len());
817     assert_eq!(
818       undetermined_id,
819       post_listings_french_und[0].post.language_id
820     );
821     assert_eq!(french_id, post_listings_french_und[1].post.language_id);
822
823     cleanup(data, pool).await;
824   }
825
826   async fn cleanup(data: Data, pool: &DbPool) {
827     let num_deleted = Post::delete(pool, data.inserted_post.id).await.unwrap();
828     Community::delete(pool, data.inserted_community.id)
829       .await
830       .unwrap();
831     Person::delete(pool, data.inserted_person.id).await.unwrap();
832     Person::delete(pool, data.inserted_bot.id).await.unwrap();
833     Person::delete(pool, data.inserted_blocked_person.id)
834       .await
835       .unwrap();
836     Instance::delete(pool, data.inserted_instance.id)
837       .await
838       .unwrap();
839     assert_eq!(1, num_deleted);
840   }
841
842   async fn expected_post_view(data: &Data, pool: &DbPool) -> PostView {
843     let (inserted_person, inserted_community, inserted_post) = (
844       &data.inserted_person,
845       &data.inserted_community,
846       &data.inserted_post,
847     );
848     let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap();
849
850     PostView {
851       post: Post {
852         id: inserted_post.id,
853         name: inserted_post.name.clone(),
854         creator_id: inserted_person.id,
855         url: None,
856         body: None,
857         published: inserted_post.published,
858         updated: None,
859         community_id: inserted_community.id,
860         removed: false,
861         deleted: false,
862         locked: false,
863         stickied: false,
864         nsfw: false,
865         embed_title: None,
866         embed_description: None,
867         embed_video_url: None,
868         thumbnail_url: None,
869         ap_id: inserted_post.ap_id.clone(),
870         local: true,
871         language_id: LanguageId(47),
872       },
873       my_vote: None,
874       unread_comments: 0,
875       creator: PersonSafe {
876         id: inserted_person.id,
877         name: inserted_person.name.clone(),
878         display_name: None,
879         published: inserted_person.published,
880         avatar: None,
881         actor_id: inserted_person.actor_id.clone(),
882         local: true,
883         admin: false,
884         bot_account: false,
885         banned: false,
886         deleted: false,
887         bio: None,
888         banner: None,
889         updated: None,
890         inbox_url: inserted_person.inbox_url.clone(),
891         shared_inbox_url: None,
892         matrix_user_id: None,
893         ban_expires: None,
894         instance_id: data.inserted_instance.id,
895       },
896       creator_banned_from_community: false,
897       community: CommunitySafe {
898         id: inserted_community.id,
899         name: inserted_community.name.clone(),
900         icon: None,
901         removed: false,
902         deleted: false,
903         nsfw: false,
904         actor_id: inserted_community.actor_id.clone(),
905         local: true,
906         title: "nada".to_owned(),
907         description: None,
908         updated: None,
909         banner: None,
910         hidden: false,
911         posting_restricted_to_mods: false,
912         published: inserted_community.published,
913         instance_id: data.inserted_instance.id,
914       },
915       counts: PostAggregates {
916         id: agg.id,
917         post_id: inserted_post.id,
918         comments: 0,
919         score: 0,
920         upvotes: 0,
921         downvotes: 0,
922         stickied: false,
923         published: agg.published,
924         newest_comment_time_necro: inserted_post.published,
925         newest_comment_time: inserted_post.published,
926       },
927       subscribed: SubscribedType::NotSubscribed,
928       read: false,
929       saved: false,
930       creator_blocked: false,
931     }
932   }
933 }