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