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 is_mod_or_admin: Option<bool>,
72 ) -> Result<Self, Error> {
73 let conn = &mut get_conn(pool).await?;
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
80 .inner_join(person::table)
81 .inner_join(community::table)
83 community_person_ban::table.on(
85 .eq(community_person_ban::community_id)
86 .and(community_person_ban::person_id.eq(post::creator_id))
88 community_person_ban::expires
90 .or(community_person_ban::expires.gt(now)),
94 .inner_join(post_aggregates::table)
96 community_follower::table.on(
98 .eq(community_follower::community_id)
99 .and(community_follower::person_id.eq(person_id_join)),
103 post_saved::table.on(
105 .eq(post_saved::post_id)
106 .and(post_saved::person_id.eq(person_id_join)),
112 .eq(post_read::post_id)
113 .and(post_read::person_id.eq(person_id_join)),
117 person_block::table.on(
119 .eq(person_block::target_id)
120 .and(person_block::person_id.eq(person_id_join)),
126 .eq(post_like::post_id)
127 .and(post_like::person_id.eq(person_id_join)),
131 person_post_aggregates::table.on(
133 .eq(person_post_aggregates::post_id)
134 .and(person_post_aggregates::person_id.eq(person_id_join)),
137 // Used to check if you are the post creator
141 .eq(person_alias_1.field(person::id))
142 .and(person_alias_1.field(person::id).eq(person_id_join)),
147 Person::safe_columns_tuple(),
148 Community::safe_columns_tuple(),
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(),
157 post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
158 post_aggregates::comments,
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.
168 person_alias_1.field(person::id).is_null().and(
171 .and(post::deleted.eq(false))
172 .and(community::removed.eq(false))
173 .and(community::deleted.eq(false)),
176 // If you are the creator, keep them
177 .or_filter(person_alias_1.field(person::id).is_not_null())
184 creator_banned_from_community,
192 ) = query.first::<PostViewTuple>(conn).await?;
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() {
206 creator_banned_from_community: creator_banned_from_community.is_some(),
208 subscribed: CommunityFollower::to_subscribed_type(&follower),
209 saved: saved.is_some(),
210 read: read.is_some(),
211 creator_blocked: creator_blocked.is_some(),
218 #[derive(TypedBuilder)]
219 #[builder(field_defaults(default))]
220 pub struct PostQuery<'a> {
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>,
238 impl<'a> PostQuery<'a> {
239 pub async fn list(self) -> Result<Vec<PostView>, Error> {
240 let conn = &mut get_conn(self.pool).await?;
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);
247 let mut query = post::table
248 .inner_join(person::table)
249 .inner_join(community::table)
251 community_person_ban::table.on(
253 .eq(community_person_ban::community_id)
254 .and(community_person_ban::person_id.eq(post::creator_id))
256 community_person_ban::expires
258 .or(community_person_ban::expires.gt(now)),
262 .inner_join(post_aggregates::table)
264 community_follower::table.on(
266 .eq(community_follower::community_id)
267 .and(community_follower::person_id.eq(person_id_join)),
271 post_saved::table.on(
273 .eq(post_saved::post_id)
274 .and(post_saved::person_id.eq(person_id_join)),
280 .eq(post_read::post_id)
281 .and(post_read::person_id.eq(person_id_join)),
285 person_block::table.on(
287 .eq(person_block::target_id)
288 .and(person_block::person_id.eq(person_id_join)),
292 community_block::table.on(
294 .eq(community_block::community_id)
295 .and(community_block::person_id.eq(person_id_join)),
301 .eq(post_like::post_id)
302 .and(post_like::person_id.eq(person_id_join)),
306 person_post_aggregates::table.on(
308 .eq(person_post_aggregates::post_id)
309 .and(person_post_aggregates::person_id.eq(person_id_join)),
313 local_user_language::table.on(
315 .eq(local_user_language::language_id)
316 .and(local_user_language::local_user_id.eq(local_user_id_join)),
319 // Used to check if you are the post creator
323 .eq(person_alias_1.field(person::id))
324 .and(person_alias_1.field(person::id).eq(person_id_join)),
329 Person::safe_columns_tuple(),
330 Community::safe_columns_tuple(),
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(),
339 post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
340 post_aggregates::comments,
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.
350 person_alias_1.field(person::id).is_null().and(
353 .and(post::deleted.eq(false))
354 .and(community::removed.eq(false))
355 .and(community::deleted.eq(false)),
358 // If you are the creator, keep them
359 .or_filter(person_alias_1.field(person::id).is_not_null())
362 if let Some(listing_type) = self.listing_type {
364 ListingType::Subscribed => {
365 query = query.filter(community_follower::person_id.is_not_null())
367 ListingType::Local => {
368 query = query.filter(community::local.eq(true)).filter(
371 .or(community_follower::person_id.eq(person_id_join)),
374 ListingType::All => {
375 query = query.filter(
378 .or(community_follower::person_id.eq(person_id_join)),
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 {
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 {
391 .filter(community::actor_id.eq(community_actor_id))
392 .then_order_by(post_aggregates::featured_community.desc());
395 if let Some(url_search) = self.url_search {
396 query = query.filter(post::url.eq(url_search));
399 if let Some(search_term) = self.search_term {
400 let searcher = fuzzy_search(&search_term);
401 query = query.filter(
403 .ilike(searcher.clone())
404 .or(post::body.ilike(searcher)),
408 if let Some(creator_id) = self.creator_id {
409 query = query.filter(post::creator_id.eq(creator_id));
412 if !self.local_user.map(|l| l.show_nsfw).unwrap_or(false) {
414 .filter(post::nsfw.eq(false))
415 .filter(community::nsfw.eq(false));
418 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
419 query = query.filter(person::bot_account.eq(false));
422 if self.saved_only.unwrap_or(false) {
423 query = query.filter(post_saved::post_id.is_not_null());
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());
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());
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());
440 query = match self.sort.unwrap_or(SortType::Hot) {
441 SortType::Active => query
444 post_aggregates::score,
445 post_aggregates::newest_comment_time_necro,
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()),
480 let (limit, offset) = limit_and_offset(self.page, self.limit)?;
482 query = query.limit(limit).offset(offset);
484 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
486 let res = query.load::<PostViewTuple>(conn).await?;
488 Ok(PostView::from_tuple_to_vec(res))
492 impl ViewToVec for PostView {
493 type DbTuple = PostViewTuple;
494 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
501 creator_banned_from_community: a.3.is_some(),
503 subscribed: CommunityFollower::to_subscribed_type(&a.5),
504 saved: a.6.is_some(),
506 creator_blocked: a.8.is_some(),
508 unread_comments: a.10,
510 .collect::<Vec<Self>>()
516 use crate::post_view::{PostQuery, PostView};
517 use lemmy_db_schema::{
518 aggregates::structs::PostAggregates,
519 impls::actor_language::UNDETERMINED_ID,
520 newtypes::LanguageId,
522 actor_language::LocalUserLanguage,
523 community::{Community, CommunityInsertForm, CommunitySafe},
524 community_block::{CommunityBlock, CommunityBlockForm},
527 local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm},
528 person::{Person, PersonInsertForm, PersonSafe},
529 person_block::{PersonBlock, PersonBlockForm},
530 post::{Post, PostInsertForm, PostLike, PostLikeForm},
532 traits::{Blockable, Crud, Likeable},
533 utils::{build_db_pool_for_tests, DbPool},
537 use serial_test::serial;
540 inserted_instance: Instance,
541 inserted_person: Person,
542 inserted_local_user: LocalUser,
543 inserted_blocked_person: Person,
544 inserted_bot: Person,
545 inserted_community: Community,
549 async fn init_data(pool: &DbPool) -> Data {
550 let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
554 let person_name = "tegan".to_string();
556 let new_person = PersonInsertForm::builder()
557 .name(person_name.clone())
558 .public_key("pubkey".to_string())
559 .instance_id(inserted_instance.id)
562 let inserted_person = Person::create(pool, &new_person).await.unwrap();
564 let local_user_form = LocalUserInsertForm::builder()
565 .person_id(inserted_person.id)
566 .password_encrypted(String::new())
568 let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
570 let new_bot = PersonInsertForm::builder()
571 .name("mybot".to_string())
572 .bot_account(Some(true))
573 .public_key("pubkey".to_string())
574 .instance_id(inserted_instance.id)
577 let inserted_bot = Person::create(pool, &new_bot).await.unwrap();
579 let new_community = CommunityInsertForm::builder()
580 .name("test_community_3".to_string())
581 .title("nada".to_owned())
582 .public_key("pubkey".to_string())
583 .instance_id(inserted_instance.id)
586 let inserted_community = Community::create(pool, &new_community).await.unwrap();
588 // Test a person block, make sure the post query doesn't include their post
589 let blocked_person = PersonInsertForm::builder()
591 .public_key("pubkey".to_string())
592 .instance_id(inserted_instance.id)
595 let inserted_blocked_person = Person::create(pool, &blocked_person).await.unwrap();
597 let post_from_blocked_person = PostInsertForm::builder()
598 .name("blocked_person_post".to_string())
599 .creator_id(inserted_blocked_person.id)
600 .community_id(inserted_community.id)
601 .language_id(Some(LanguageId(1)))
604 Post::create(pool, &post_from_blocked_person).await.unwrap();
607 let person_block = PersonBlockForm {
608 person_id: inserted_person.id,
609 target_id: inserted_blocked_person.id,
612 PersonBlock::block(pool, &person_block).await.unwrap();
615 let new_post = PostInsertForm::builder()
616 .name("test post 3".to_string())
617 .creator_id(inserted_person.id)
618 .community_id(inserted_community.id)
619 .language_id(Some(LanguageId(47)))
622 let inserted_post = Post::create(pool, &new_post).await.unwrap();
624 let new_bot_post = PostInsertForm::builder()
625 .name("test bot post".to_string())
626 .creator_id(inserted_bot.id)
627 .community_id(inserted_community.id)
630 let _inserted_bot_post = Post::create(pool, &new_bot_post).await.unwrap();
636 inserted_blocked_person,
645 async fn post_listing_with_person() {
646 let pool = &build_db_pool_for_tests().await;
647 let data = init_data(pool).await;
649 let local_user_form = LocalUserUpdateForm::builder()
650 .show_bot_accounts(Some(false))
652 let inserted_local_user =
653 LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
657 let read_post_listing = PostQuery::builder()
659 .sort(Some(SortType::New))
660 .community_id(Some(data.inserted_community.id))
661 .local_user(Some(&inserted_local_user))
667 let post_listing_single_with_person = PostView::read(
669 data.inserted_post.id,
670 Some(data.inserted_person.id),
676 let mut expected_post_listing_with_user = expected_post_view(&data, pool).await;
678 // Should be only one person, IE the bot post, and blocked should be missing
679 assert_eq!(1, read_post_listing.len());
681 assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
682 expected_post_listing_with_user.my_vote = Some(0);
684 expected_post_listing_with_user,
685 post_listing_single_with_person
688 let local_user_form = LocalUserUpdateForm::builder()
689 .show_bot_accounts(Some(true))
691 let inserted_local_user =
692 LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
696 let post_listings_with_bots = PostQuery::builder()
698 .sort(Some(SortType::New))
699 .community_id(Some(data.inserted_community.id))
700 .local_user(Some(&inserted_local_user))
705 // should include bot post which has "undetermined" language
706 assert_eq!(2, post_listings_with_bots.len());
708 cleanup(data, pool).await;
713 async fn post_listing_no_person() {
714 let pool = &build_db_pool_for_tests().await;
715 let data = init_data(pool).await;
717 let read_post_listing_multiple_no_person = PostQuery::builder()
719 .sort(Some(SortType::New))
720 .community_id(Some(data.inserted_community.id))
726 let read_post_listing_single_no_person =
727 PostView::read(pool, data.inserted_post.id, None, None)
731 let expected_post_listing_no_person = expected_post_view(&data, pool).await;
733 // Should be 2 posts, with the bot post, and the blocked
734 assert_eq!(3, read_post_listing_multiple_no_person.len());
737 expected_post_listing_no_person,
738 read_post_listing_multiple_no_person[1]
741 expected_post_listing_no_person,
742 read_post_listing_single_no_person
745 cleanup(data, pool).await;
750 async fn post_listing_block_community() {
751 let pool = &build_db_pool_for_tests().await;
752 let data = init_data(pool).await;
754 let community_block = CommunityBlockForm {
755 person_id: data.inserted_person.id,
756 community_id: data.inserted_community.id,
758 CommunityBlock::block(pool, &community_block).await.unwrap();
760 let read_post_listings_with_person_after_block = PostQuery::builder()
762 .sort(Some(SortType::New))
763 .community_id(Some(data.inserted_community.id))
764 .local_user(Some(&data.inserted_local_user))
769 // Should be 0 posts after the community block
770 assert_eq!(0, read_post_listings_with_person_after_block.len());
772 CommunityBlock::unblock(pool, &community_block)
775 cleanup(data, pool).await;
780 async fn post_listing_like() {
781 let pool = &build_db_pool_for_tests().await;
782 let data = init_data(pool).await;
784 let post_like_form = PostLikeForm {
785 post_id: data.inserted_post.id,
786 person_id: data.inserted_person.id,
790 let inserted_post_like = PostLike::like(pool, &post_like_form).await.unwrap();
792 let expected_post_like = PostLike {
793 id: inserted_post_like.id,
794 post_id: data.inserted_post.id,
795 person_id: data.inserted_person.id,
796 published: inserted_post_like.published,
799 assert_eq!(expected_post_like, inserted_post_like);
801 let like_removed = PostLike::remove(pool, data.inserted_person.id, data.inserted_post.id)
804 assert_eq!(1, like_removed);
805 cleanup(data, pool).await;
810 async fn post_listing_person_language() {
811 let pool = &build_db_pool_for_tests().await;
812 let data = init_data(pool).await;
814 let spanish_id = Language::read_id_from_code(pool, Some("es"))
818 let post_spanish = PostInsertForm::builder()
819 .name("asffgdsc".to_string())
820 .creator_id(data.inserted_person.id)
821 .community_id(data.inserted_community.id)
822 .language_id(Some(spanish_id))
825 Post::create(pool, &post_spanish).await.unwrap();
827 let post_listings_all = PostQuery::builder()
829 .sort(Some(SortType::New))
830 .local_user(Some(&data.inserted_local_user))
836 // no language filters specified, all posts should be returned
837 assert_eq!(3, post_listings_all.len());
839 let french_id = Language::read_id_from_code(pool, Some("fr"))
843 LocalUserLanguage::update(pool, vec![french_id], data.inserted_local_user.id)
847 let post_listing_french = PostQuery::builder()
849 .sort(Some(SortType::New))
850 .local_user(Some(&data.inserted_local_user))
856 // only one french language post should be returned
857 assert_eq!(1, post_listing_french.len());
858 assert_eq!(french_id, post_listing_french[0].post.language_id);
860 LocalUserLanguage::update(
862 vec![french_id, UNDETERMINED_ID],
863 data.inserted_local_user.id,
867 let post_listings_french_und = PostQuery::builder()
869 .sort(Some(SortType::New))
870 .local_user(Some(&data.inserted_local_user))
876 // french post and undetermined language post should be returned
877 assert_eq!(2, post_listings_french_und.len());
880 post_listings_french_und[0].post.language_id
882 assert_eq!(french_id, post_listings_french_und[1].post.language_id);
884 cleanup(data, pool).await;
887 async fn cleanup(data: Data, pool: &DbPool) {
888 let num_deleted = Post::delete(pool, data.inserted_post.id).await.unwrap();
889 Community::delete(pool, data.inserted_community.id)
892 Person::delete(pool, data.inserted_person.id).await.unwrap();
893 Person::delete(pool, data.inserted_bot.id).await.unwrap();
894 Person::delete(pool, data.inserted_blocked_person.id)
897 Instance::delete(pool, data.inserted_instance.id)
900 assert_eq!(1, num_deleted);
903 async fn expected_post_view(data: &Data, pool: &DbPool) -> PostView {
904 let (inserted_person, inserted_community, inserted_post) = (
905 &data.inserted_person,
906 &data.inserted_community,
909 let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap();
913 id: inserted_post.id,
914 name: inserted_post.name.clone(),
915 creator_id: inserted_person.id,
918 published: inserted_post.published,
920 community_id: inserted_community.id,
926 embed_description: None,
927 embed_video_url: None,
929 ap_id: inserted_post.ap_id.clone(),
931 language_id: LanguageId(47),
932 featured_community: false,
933 featured_local: false,
937 creator: PersonSafe {
938 id: inserted_person.id,
939 name: inserted_person.name.clone(),
941 published: inserted_person.published,
943 actor_id: inserted_person.actor_id.clone(),
952 inbox_url: inserted_person.inbox_url.clone(),
953 shared_inbox_url: None,
954 matrix_user_id: None,
956 instance_id: data.inserted_instance.id,
958 creator_banned_from_community: false,
959 community: CommunitySafe {
960 id: inserted_community.id,
961 name: inserted_community.name.clone(),
966 actor_id: inserted_community.actor_id.clone(),
968 title: "nada".to_owned(),
973 posting_restricted_to_mods: false,
974 published: inserted_community.published,
975 instance_id: data.inserted_instance.id,
977 counts: PostAggregates {
979 post_id: inserted_post.id,
984 published: agg.published,
985 newest_comment_time_necro: inserted_post.published,
986 newest_comment_time: inserted_post.published,
987 featured_community: false,
988 featured_local: false,
990 subscribed: SubscribedType::NotSubscribed,
993 creator_blocked: false,