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