1 use crate::structs::PostView;
4 dsl::{now, IntervalDsl},
12 NullableExpressionMethods,
13 PgTextExpressionMethods,
16 use diesel_async::RunQueryDsl;
17 use lemmy_db_schema::{
18 aggregates::structs::PostAggregates,
19 newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
28 person_post_aggregates,
36 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
37 local_user::LocalUser,
38 person::{Person, PersonSafe},
39 person_block::PersonBlock,
40 post::{Post, PostRead, PostSaved},
42 traits::{ToSafe, ViewToVec},
43 utils::{functions::hot_rank, fuzzy_search, get_conn, limit_and_offset, DbPool},
48 use typed_builder::TypedBuilder;
50 type PostViewTuple = (
54 Option<CommunityPersonBan>,
56 Option<CommunityFollower>,
64 sql_function!(fn coalesce(x: sql_types::Nullable<sql_types::BigInt>, y: sql_types::BigInt) -> sql_types::BigInt);
70 my_person_id: Option<PersonId>,
71 ) -> Result<Self, Error> {
72 let conn = &mut get_conn(pool).await?;
74 // The left join below will return None in this case
75 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
80 creator_banned_from_community,
90 .inner_join(person::table)
91 .inner_join(community::table)
93 community_person_ban::table.on(
95 .eq(community_person_ban::community_id)
96 .and(community_person_ban::person_id.eq(post::creator_id))
98 community_person_ban::expires
100 .or(community_person_ban::expires.gt(now)),
104 .inner_join(post_aggregates::table)
106 community_follower::table.on(
108 .eq(community_follower::community_id)
109 .and(community_follower::person_id.eq(person_id_join)),
113 post_saved::table.on(
115 .eq(post_saved::post_id)
116 .and(post_saved::person_id.eq(person_id_join)),
122 .eq(post_read::post_id)
123 .and(post_read::person_id.eq(person_id_join)),
127 person_block::table.on(
129 .eq(person_block::target_id)
130 .and(person_block::person_id.eq(person_id_join)),
136 .eq(post_like::post_id)
137 .and(post_like::person_id.eq(person_id_join)),
141 person_post_aggregates::table.on(
143 .eq(person_post_aggregates::post_id)
144 .and(person_post_aggregates::person_id.eq(person_id_join)),
149 Person::safe_columns_tuple(),
150 Community::safe_columns_tuple(),
151 community_person_ban::all_columns.nullable(),
152 post_aggregates::all_columns,
153 community_follower::all_columns.nullable(),
154 post_saved::all_columns.nullable(),
155 post_read::all_columns.nullable(),
156 person_block::all_columns.nullable(),
157 post_like::score.nullable(),
159 post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
160 post_aggregates::comments,
163 .first::<PostViewTuple>(conn)
166 // If a person is given, then my_vote, if None, should be 0, not null
167 // Necessary to differentiate between other person's votes
168 let my_vote = if my_person_id.is_some() && post_like.is_none() {
178 creator_banned_from_community: creator_banned_from_community.is_some(),
180 subscribed: CommunityFollower::to_subscribed_type(&follower),
181 saved: saved.is_some(),
182 read: read.is_some(),
183 creator_blocked: creator_blocked.is_some(),
190 #[derive(TypedBuilder)]
191 #[builder(field_defaults(default))]
192 pub struct PostQuery<'a> {
195 listing_type: Option<ListingType>,
196 sort: Option<SortType>,
197 creator_id: Option<PersonId>,
198 community_id: Option<CommunityId>,
199 community_actor_id: Option<DbUrl>,
200 local_user: Option<&'a LocalUser>,
201 search_term: Option<String>,
202 url_search: Option<String>,
203 saved_only: Option<bool>,
208 impl<'a> PostQuery<'a> {
209 pub async fn list(self) -> Result<Vec<PostView>, Error> {
210 let conn = &mut get_conn(self.pool).await?;
212 // The left join below will return None in this case
213 let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1));
214 let local_user_id_join = self.local_user.map(|l| l.id).unwrap_or(LocalUserId(-1));
216 let mut query = post::table
217 .inner_join(person::table)
218 .inner_join(community::table)
220 community_person_ban::table.on(
222 .eq(community_person_ban::community_id)
223 .and(community_person_ban::person_id.eq(post::creator_id))
225 community_person_ban::expires
227 .or(community_person_ban::expires.gt(now)),
231 .inner_join(post_aggregates::table)
233 community_follower::table.on(
235 .eq(community_follower::community_id)
236 .and(community_follower::person_id.eq(person_id_join)),
240 post_saved::table.on(
242 .eq(post_saved::post_id)
243 .and(post_saved::person_id.eq(person_id_join)),
249 .eq(post_read::post_id)
250 .and(post_read::person_id.eq(person_id_join)),
254 person_block::table.on(
256 .eq(person_block::target_id)
257 .and(person_block::person_id.eq(person_id_join)),
261 community_block::table.on(
263 .eq(community_block::community_id)
264 .and(community_block::person_id.eq(person_id_join)),
270 .eq(post_like::post_id)
271 .and(post_like::person_id.eq(person_id_join)),
275 person_post_aggregates::table.on(
277 .eq(person_post_aggregates::post_id)
278 .and(person_post_aggregates::person_id.eq(person_id_join)),
282 local_user_language::table.on(
284 .eq(local_user_language::language_id)
285 .and(local_user_language::local_user_id.eq(local_user_id_join)),
290 Person::safe_columns_tuple(),
291 Community::safe_columns_tuple(),
292 community_person_ban::all_columns.nullable(),
293 post_aggregates::all_columns,
294 community_follower::all_columns.nullable(),
295 post_saved::all_columns.nullable(),
296 post_read::all_columns.nullable(),
297 person_block::all_columns.nullable(),
298 post_like::score.nullable(),
300 post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
301 post_aggregates::comments,
306 if let Some(listing_type) = self.listing_type {
308 ListingType::Subscribed => {
309 query = query.filter(community_follower::person_id.is_not_null())
311 ListingType::Local => {
312 query = query.filter(community::local.eq(true)).filter(
315 .or(community_follower::person_id.eq(person_id_join)),
318 ListingType::All => {
319 query = query.filter(
322 .or(community_follower::person_id.eq(person_id_join)),
327 if self.community_id.is_none() && self.community_actor_id.is_none() {
328 query = query.then_order_by(post_aggregates::featured_local.desc());
329 } else if let Some(community_id) = self.community_id {
331 .filter(post::community_id.eq(community_id))
332 .then_order_by(post_aggregates::featured_community.desc());
333 } else if let Some(community_actor_id) = self.community_actor_id {
335 .filter(community::actor_id.eq(community_actor_id))
336 .then_order_by(post_aggregates::featured_community.desc());
339 if let Some(url_search) = self.url_search {
340 query = query.filter(post::url.eq(url_search));
343 if let Some(search_term) = self.search_term {
344 let searcher = fuzzy_search(&search_term);
345 query = query.filter(
347 .ilike(searcher.clone())
348 .or(post::body.ilike(searcher)),
352 // If its for a specific person, show the removed / deleted
353 if let Some(creator_id) = self.creator_id {
354 query = query.filter(post::creator_id.eq(creator_id));
357 if !self.local_user.map(|l| l.show_nsfw).unwrap_or(false) {
359 .filter(post::nsfw.eq(false))
360 .filter(community::nsfw.eq(false));
363 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
364 query = query.filter(person::bot_account.eq(false));
367 if self.saved_only.unwrap_or(false) {
368 query = query.filter(post_saved::post_id.is_not_null());
370 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
371 // setting wont be able to see saved posts.
372 else if !self.local_user.map(|l| l.show_read_posts).unwrap_or(true) {
373 query = query.filter(post_read::post_id.is_null());
376 if self.local_user.is_some() {
377 // Filter out the rows with missing languages
378 query = query.filter(local_user_language::language_id.is_not_null());
380 // Don't show blocked communities or persons
381 query = query.filter(community_block::person_id.is_null());
382 query = query.filter(person_block::person_id.is_null());
385 query = match self.sort.unwrap_or(SortType::Hot) {
386 SortType::Active => query
389 post_aggregates::score,
390 post_aggregates::newest_comment_time_necro,
394 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
395 SortType::Hot => query
396 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
397 .then_order_by(post_aggregates::published.desc()),
398 SortType::New => query.then_order_by(post_aggregates::published.desc()),
399 SortType::Old => query.then_order_by(post_aggregates::published.asc()),
400 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
401 SortType::MostComments => query
402 .then_order_by(post_aggregates::comments.desc())
403 .then_order_by(post_aggregates::published.desc()),
404 SortType::TopAll => query
405 .then_order_by(post_aggregates::score.desc())
406 .then_order_by(post_aggregates::published.desc()),
407 SortType::TopYear => query
408 .filter(post_aggregates::published.gt(now - 1.years()))
409 .then_order_by(post_aggregates::score.desc())
410 .then_order_by(post_aggregates::published.desc()),
411 SortType::TopMonth => query
412 .filter(post_aggregates::published.gt(now - 1.months()))
413 .then_order_by(post_aggregates::score.desc())
414 .then_order_by(post_aggregates::published.desc()),
415 SortType::TopWeek => query
416 .filter(post_aggregates::published.gt(now - 1.weeks()))
417 .then_order_by(post_aggregates::score.desc())
418 .then_order_by(post_aggregates::published.desc()),
419 SortType::TopDay => query
420 .filter(post_aggregates::published.gt(now - 1.days()))
421 .then_order_by(post_aggregates::score.desc())
422 .then_order_by(post_aggregates::published.desc()),
425 let (limit, offset) = limit_and_offset(self.page, self.limit)?;
430 .filter(post::removed.eq(false))
431 .filter(post::deleted.eq(false))
432 .filter(community::removed.eq(false))
433 .filter(community::deleted.eq(false));
435 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
437 let res = query.load::<PostViewTuple>(conn).await?;
439 Ok(PostView::from_tuple_to_vec(res))
443 impl ViewToVec for PostView {
444 type DbTuple = PostViewTuple;
445 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
452 creator_banned_from_community: a.3.is_some(),
454 subscribed: CommunityFollower::to_subscribed_type(&a.5),
455 saved: a.6.is_some(),
457 creator_blocked: a.8.is_some(),
459 unread_comments: a.10,
461 .collect::<Vec<Self>>()
467 use crate::post_view::{PostQuery, PostView};
468 use lemmy_db_schema::{
469 aggregates::structs::PostAggregates,
470 impls::actor_language::UNDETERMINED_ID,
471 newtypes::LanguageId,
473 actor_language::LocalUserLanguage,
474 community::{Community, CommunityInsertForm, CommunitySafe},
475 community_block::{CommunityBlock, CommunityBlockForm},
478 local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm},
479 person::{Person, PersonInsertForm, PersonSafe},
480 person_block::{PersonBlock, PersonBlockForm},
481 post::{Post, PostInsertForm, PostLike, PostLikeForm},
483 traits::{Blockable, Crud, Likeable},
484 utils::{build_db_pool_for_tests, DbPool},
488 use serial_test::serial;
491 inserted_instance: Instance,
492 inserted_person: Person,
493 inserted_local_user: LocalUser,
494 inserted_blocked_person: Person,
495 inserted_bot: Person,
496 inserted_community: Community,
500 async fn init_data(pool: &DbPool) -> Data {
501 let inserted_instance = Instance::create(pool, "my_domain.tld").await.unwrap();
503 let person_name = "tegan".to_string();
505 let new_person = PersonInsertForm::builder()
506 .name(person_name.clone())
507 .public_key("pubkey".to_string())
508 .instance_id(inserted_instance.id)
511 let inserted_person = Person::create(pool, &new_person).await.unwrap();
513 let local_user_form = LocalUserInsertForm::builder()
514 .person_id(inserted_person.id)
515 .password_encrypted(String::new())
517 let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
519 let new_bot = PersonInsertForm::builder()
520 .name("mybot".to_string())
521 .bot_account(Some(true))
522 .public_key("pubkey".to_string())
523 .instance_id(inserted_instance.id)
526 let inserted_bot = Person::create(pool, &new_bot).await.unwrap();
528 let new_community = CommunityInsertForm::builder()
529 .name("test_community_3".to_string())
530 .title("nada".to_owned())
531 .public_key("pubkey".to_string())
532 .instance_id(inserted_instance.id)
535 let inserted_community = Community::create(pool, &new_community).await.unwrap();
537 // Test a person block, make sure the post query doesn't include their post
538 let blocked_person = PersonInsertForm::builder()
540 .public_key("pubkey".to_string())
541 .instance_id(inserted_instance.id)
544 let inserted_blocked_person = Person::create(pool, &blocked_person).await.unwrap();
546 let post_from_blocked_person = PostInsertForm::builder()
547 .name("blocked_person_post".to_string())
548 .creator_id(inserted_blocked_person.id)
549 .community_id(inserted_community.id)
550 .language_id(Some(LanguageId(1)))
553 Post::create(pool, &post_from_blocked_person).await.unwrap();
556 let person_block = PersonBlockForm {
557 person_id: inserted_person.id,
558 target_id: inserted_blocked_person.id,
561 PersonBlock::block(pool, &person_block).await.unwrap();
564 let new_post = PostInsertForm::builder()
565 .name("test post 3".to_string())
566 .creator_id(inserted_person.id)
567 .community_id(inserted_community.id)
568 .language_id(Some(LanguageId(47)))
571 let inserted_post = Post::create(pool, &new_post).await.unwrap();
573 let new_bot_post = PostInsertForm::builder()
574 .name("test bot post".to_string())
575 .creator_id(inserted_bot.id)
576 .community_id(inserted_community.id)
579 let _inserted_bot_post = Post::create(pool, &new_bot_post).await.unwrap();
585 inserted_blocked_person,
594 async fn post_listing_with_person() {
595 let pool = &build_db_pool_for_tests().await;
596 let data = init_data(pool).await;
598 let local_user_form = LocalUserUpdateForm::builder()
599 .show_bot_accounts(Some(false))
601 let inserted_local_user =
602 LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
606 let read_post_listing = PostQuery::builder()
608 .sort(Some(SortType::New))
609 .community_id(Some(data.inserted_community.id))
610 .local_user(Some(&inserted_local_user))
616 let post_listing_single_with_person =
617 PostView::read(pool, data.inserted_post.id, Some(data.inserted_person.id))
621 let mut expected_post_listing_with_user = expected_post_view(&data, pool).await;
623 // Should be only one person, IE the bot post, and blocked should be missing
624 assert_eq!(1, read_post_listing.len());
626 assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
627 expected_post_listing_with_user.my_vote = Some(0);
629 expected_post_listing_with_user,
630 post_listing_single_with_person
633 let local_user_form = LocalUserUpdateForm::builder()
634 .show_bot_accounts(Some(true))
636 let inserted_local_user =
637 LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
641 let post_listings_with_bots = PostQuery::builder()
643 .sort(Some(SortType::New))
644 .community_id(Some(data.inserted_community.id))
645 .local_user(Some(&inserted_local_user))
650 // should include bot post which has "undetermined" language
651 assert_eq!(2, post_listings_with_bots.len());
653 cleanup(data, pool).await;
658 async fn post_listing_no_person() {
659 let pool = &build_db_pool_for_tests().await;
660 let data = init_data(pool).await;
662 let read_post_listing_multiple_no_person = PostQuery::builder()
664 .sort(Some(SortType::New))
665 .community_id(Some(data.inserted_community.id))
671 let read_post_listing_single_no_person = PostView::read(pool, data.inserted_post.id, None)
675 let expected_post_listing_no_person = expected_post_view(&data, pool).await;
677 // Should be 2 posts, with the bot post, and the blocked
678 assert_eq!(3, read_post_listing_multiple_no_person.len());
681 expected_post_listing_no_person,
682 read_post_listing_multiple_no_person[1]
685 expected_post_listing_no_person,
686 read_post_listing_single_no_person
689 cleanup(data, pool).await;
694 async fn post_listing_block_community() {
695 let pool = &build_db_pool_for_tests().await;
696 let data = init_data(pool).await;
698 let community_block = CommunityBlockForm {
699 person_id: data.inserted_person.id,
700 community_id: data.inserted_community.id,
702 CommunityBlock::block(pool, &community_block).await.unwrap();
704 let read_post_listings_with_person_after_block = PostQuery::builder()
706 .sort(Some(SortType::New))
707 .community_id(Some(data.inserted_community.id))
708 .local_user(Some(&data.inserted_local_user))
713 // Should be 0 posts after the community block
714 assert_eq!(0, read_post_listings_with_person_after_block.len());
716 CommunityBlock::unblock(pool, &community_block)
719 cleanup(data, pool).await;
724 async fn post_listing_like() {
725 let pool = &build_db_pool_for_tests().await;
726 let data = init_data(pool).await;
728 let post_like_form = PostLikeForm {
729 post_id: data.inserted_post.id,
730 person_id: data.inserted_person.id,
734 let inserted_post_like = PostLike::like(pool, &post_like_form).await.unwrap();
736 let expected_post_like = PostLike {
737 id: inserted_post_like.id,
738 post_id: data.inserted_post.id,
739 person_id: data.inserted_person.id,
740 published: inserted_post_like.published,
743 assert_eq!(expected_post_like, inserted_post_like);
745 let like_removed = PostLike::remove(pool, data.inserted_person.id, data.inserted_post.id)
748 assert_eq!(1, like_removed);
749 cleanup(data, pool).await;
754 async fn post_listing_person_language() {
755 let pool = &build_db_pool_for_tests().await;
756 let data = init_data(pool).await;
758 let spanish_id = Language::read_id_from_code(pool, Some("es"))
762 let post_spanish = PostInsertForm::builder()
763 .name("asffgdsc".to_string())
764 .creator_id(data.inserted_person.id)
765 .community_id(data.inserted_community.id)
766 .language_id(Some(spanish_id))
769 Post::create(pool, &post_spanish).await.unwrap();
771 let post_listings_all = PostQuery::builder()
773 .sort(Some(SortType::New))
774 .local_user(Some(&data.inserted_local_user))
780 // no language filters specified, all posts should be returned
781 assert_eq!(3, post_listings_all.len());
783 let french_id = Language::read_id_from_code(pool, Some("fr"))
787 LocalUserLanguage::update(pool, vec![french_id], data.inserted_local_user.id)
791 let post_listing_french = PostQuery::builder()
793 .sort(Some(SortType::New))
794 .local_user(Some(&data.inserted_local_user))
800 // only one french language post should be returned
801 assert_eq!(1, post_listing_french.len());
802 assert_eq!(french_id, post_listing_french[0].post.language_id);
804 LocalUserLanguage::update(
806 vec![french_id, UNDETERMINED_ID],
807 data.inserted_local_user.id,
811 let post_listings_french_und = PostQuery::builder()
813 .sort(Some(SortType::New))
814 .local_user(Some(&data.inserted_local_user))
820 // french post and undetermined language post should be returned
821 assert_eq!(2, post_listings_french_und.len());
824 post_listings_french_und[0].post.language_id
826 assert_eq!(french_id, post_listings_french_und[1].post.language_id);
828 cleanup(data, pool).await;
831 async fn cleanup(data: Data, pool: &DbPool) {
832 let num_deleted = Post::delete(pool, data.inserted_post.id).await.unwrap();
833 Community::delete(pool, data.inserted_community.id)
836 Person::delete(pool, data.inserted_person.id).await.unwrap();
837 Person::delete(pool, data.inserted_bot.id).await.unwrap();
838 Person::delete(pool, data.inserted_blocked_person.id)
841 Instance::delete(pool, data.inserted_instance.id)
844 assert_eq!(1, num_deleted);
847 async fn expected_post_view(data: &Data, pool: &DbPool) -> PostView {
848 let (inserted_person, inserted_community, inserted_post) = (
849 &data.inserted_person,
850 &data.inserted_community,
853 let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap();
857 id: inserted_post.id,
858 name: inserted_post.name.clone(),
859 creator_id: inserted_person.id,
862 published: inserted_post.published,
864 community_id: inserted_community.id,
870 embed_description: None,
871 embed_video_url: None,
873 ap_id: inserted_post.ap_id.clone(),
875 language_id: LanguageId(47),
876 featured_community: false,
877 featured_local: false,
881 creator: PersonSafe {
882 id: inserted_person.id,
883 name: inserted_person.name.clone(),
885 published: inserted_person.published,
887 actor_id: inserted_person.actor_id.clone(),
896 inbox_url: inserted_person.inbox_url.clone(),
897 shared_inbox_url: None,
898 matrix_user_id: None,
900 instance_id: data.inserted_instance.id,
902 creator_banned_from_community: false,
903 community: CommunitySafe {
904 id: inserted_community.id,
905 name: inserted_community.name.clone(),
910 actor_id: inserted_community.actor_id.clone(),
912 title: "nada".to_owned(),
917 posting_restricted_to_mods: false,
918 published: inserted_community.published,
919 instance_id: data.inserted_instance.id,
921 counts: PostAggregates {
923 post_id: inserted_post.id,
928 published: agg.published,
929 newest_comment_time_necro: inserted_post.published,
930 newest_comment_time: inserted_post.published,
931 featured_community: false,
932 featured_local: false,
934 subscribed: SubscribedType::NotSubscribed,
937 creator_blocked: false,