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