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