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