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, LocalUserId, PersonId, PostId},
28 person_post_aggregates,
36 community::{Community, CommunityFollower, CommunityPersonBan},
37 local_user::LocalUser,
39 person_block::PersonBlock,
40 post::{Post, PostRead, PostSaved},
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 mut query = post::table
79 .inner_join(person::table)
80 .inner_join(community::table)
82 community_person_ban::table.on(
84 .eq(community_person_ban::community_id)
85 .and(community_person_ban::person_id.eq(post::creator_id)),
88 .inner_join(post_aggregates::table)
90 community_follower::table.on(
92 .eq(community_follower::community_id)
93 .and(community_follower::person_id.eq(person_id_join)),
99 .eq(post_saved::post_id)
100 .and(post_saved::person_id.eq(person_id_join)),
106 .eq(post_read::post_id)
107 .and(post_read::person_id.eq(person_id_join)),
111 person_block::table.on(
113 .eq(person_block::target_id)
114 .and(person_block::person_id.eq(person_id_join)),
120 .eq(post_like::post_id)
121 .and(post_like::person_id.eq(person_id_join)),
125 person_post_aggregates::table.on(
127 .eq(person_post_aggregates::post_id)
128 .and(person_post_aggregates::person_id.eq(person_id_join)),
134 community::all_columns,
135 community_person_ban::all_columns.nullable(),
136 post_aggregates::all_columns,
137 community_follower::all_columns.nullable(),
138 post_saved::all_columns.nullable(),
139 post_read::all_columns.nullable(),
140 person_block::all_columns.nullable(),
141 post_like::score.nullable(),
143 post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
144 post_aggregates::comments,
149 // Hide deleted and removed for non-admins or mods
150 if !is_mod_or_admin.unwrap_or(true) {
152 .filter(community::removed.eq(false))
153 .filter(community::deleted.eq(false));
160 creator_banned_from_community,
168 ) = query.first::<PostViewTuple>(conn).await?;
170 // If a person is given, then my_vote, if None, should be 0, not null
171 // Necessary to differentiate between other person's votes
172 let my_vote = if my_person_id.is_some() && post_like.is_none() {
182 creator_banned_from_community: creator_banned_from_community.is_some(),
184 subscribed: CommunityFollower::to_subscribed_type(&follower),
185 saved: saved.is_some(),
186 read: read.is_some(),
187 creator_blocked: creator_blocked.is_some(),
194 #[derive(TypedBuilder)]
195 #[builder(field_defaults(default))]
196 pub struct PostQuery<'a> {
199 listing_type: Option<ListingType>,
200 sort: Option<SortType>,
201 creator_id: Option<PersonId>,
202 community_id: Option<CommunityId>,
203 local_user: Option<&'a LocalUser>,
204 search_term: Option<String>,
205 url_search: Option<String>,
206 saved_only: Option<bool>,
207 /// Used to show deleted or removed posts for admins
208 is_mod_or_admin: Option<bool>,
213 impl<'a> PostQuery<'a> {
214 pub async fn list(self) -> Result<Vec<PostView>, Error> {
215 let conn = &mut get_conn(self.pool).await?;
217 // The left join below will return None in this case
218 let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1));
219 let local_user_id_join = self.local_user.map(|l| l.id).unwrap_or(LocalUserId(-1));
221 let mut query = post::table
222 .inner_join(person::table)
223 .inner_join(community::table)
225 community_person_ban::table.on(
227 .eq(community_person_ban::community_id)
228 .and(community_person_ban::person_id.eq(post::creator_id)),
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)),
291 community::all_columns,
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 // Hide deleted and removed for non-admins or mods
307 // TODO This eventually needs to show posts where you are the creator
308 if !self.is_mod_or_admin.unwrap_or(true) {
310 .filter(community::removed.eq(false))
311 .filter(community::deleted.eq(false));
314 if self.community_id.is_none() {
315 query = query.then_order_by(post_aggregates::featured_local.desc());
316 } else if let Some(community_id) = self.community_id {
318 .filter(post::community_id.eq(community_id))
319 .then_order_by(post_aggregates::featured_community.desc());
322 if let Some(creator_id) = self.creator_id {
323 query = query.filter(post::creator_id.eq(creator_id));
326 if let Some(listing_type) = self.listing_type {
328 ListingType::Subscribed => {
329 query = query.filter(community_follower::person_id.is_not_null())
331 ListingType::Local => {
332 query = query.filter(community::local.eq(true)).filter(
335 .or(community_follower::person_id.eq(person_id_join)),
338 ListingType::All => {
339 query = query.filter(
342 .or(community_follower::person_id.eq(person_id_join)),
348 if let Some(url_search) = self.url_search {
349 query = query.filter(post::url.eq(url_search));
352 if let Some(search_term) = self.search_term {
353 let searcher = fuzzy_search(&search_term);
354 query = query.filter(
356 .ilike(searcher.clone())
357 .or(post::body.ilike(searcher)),
361 if !self.local_user.map(|l| l.show_nsfw).unwrap_or(false) {
363 .filter(post::nsfw.eq(false))
364 .filter(community::nsfw.eq(false));
367 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
368 query = query.filter(person::bot_account.eq(false));
371 if self.saved_only.unwrap_or(false) {
372 query = query.filter(post_saved::post_id.is_not_null());
374 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
375 // setting wont be able to see saved posts.
376 else if !self.local_user.map(|l| l.show_read_posts).unwrap_or(true) {
377 query = query.filter(post_read::post_id.is_null());
380 if self.local_user.is_some() {
381 // Filter out the rows with missing languages
382 query = query.filter(local_user_language::language_id.is_not_null());
384 // Don't show blocked communities or persons
385 query = query.filter(community_block::person_id.is_null());
386 query = query.filter(person_block::person_id.is_null());
389 query = match self.sort.unwrap_or(SortType::Hot) {
390 SortType::Active => query
393 post_aggregates::score,
394 post_aggregates::newest_comment_time_necro,
398 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
399 SortType::Hot => query
400 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
401 .then_order_by(post_aggregates::published.desc()),
402 SortType::New => query.then_order_by(post_aggregates::published.desc()),
403 SortType::Old => query.then_order_by(post_aggregates::published.asc()),
404 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
405 SortType::MostComments => query
406 .then_order_by(post_aggregates::comments.desc())
407 .then_order_by(post_aggregates::published.desc()),
408 SortType::TopAll => query
409 .then_order_by(post_aggregates::score.desc())
410 .then_order_by(post_aggregates::published.desc()),
411 SortType::TopYear => query
412 .filter(post_aggregates::published.gt(now - 1.years()))
413 .then_order_by(post_aggregates::score.desc())
414 .then_order_by(post_aggregates::published.desc()),
415 SortType::TopMonth => query
416 .filter(post_aggregates::published.gt(now - 1.months()))
417 .then_order_by(post_aggregates::score.desc())
418 .then_order_by(post_aggregates::published.desc()),
419 SortType::TopWeek => query
420 .filter(post_aggregates::published.gt(now - 1.weeks()))
421 .then_order_by(post_aggregates::score.desc())
422 .then_order_by(post_aggregates::published.desc()),
423 SortType::TopDay => query
424 .filter(post_aggregates::published.gt(now - 1.days()))
425 .then_order_by(post_aggregates::score.desc())
426 .then_order_by(post_aggregates::published.desc()),
429 let (limit, offset) = limit_and_offset(self.page, self.limit)?;
431 query = query.limit(limit).offset(offset);
433 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
435 let res = query.load::<PostViewTuple>(conn).await?;
437 Ok(res.into_iter().map(PostView::from_tuple).collect())
441 impl JoinView for PostView {
442 type JoinTuple = PostViewTuple;
443 fn from_tuple(a: Self::JoinTuple) -> Self {
448 creator_banned_from_community: a.3.is_some(),
450 subscribed: CommunityFollower::to_subscribed_type(&a.5),
451 saved: a.6.is_some(),
453 creator_blocked: a.8.is_some(),
455 unread_comments: a.10,
462 use crate::post_view::{PostQuery, PostView};
463 use lemmy_db_schema::{
464 aggregates::structs::PostAggregates,
465 impls::actor_language::UNDETERMINED_ID,
466 newtypes::LanguageId,
468 actor_language::LocalUserLanguage,
469 community::{Community, CommunityInsertForm},
470 community_block::{CommunityBlock, CommunityBlockForm},
473 local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm},
474 person::{Person, PersonInsertForm},
475 person_block::{PersonBlock, PersonBlockForm},
476 post::{Post, PostInsertForm, PostLike, PostLikeForm},
478 traits::{Blockable, Crud, Likeable},
479 utils::{build_db_pool_for_tests, DbPool},
483 use serial_test::serial;
486 inserted_instance: Instance,
487 inserted_person: Person,
488 inserted_local_user: LocalUser,
489 inserted_blocked_person: Person,
490 inserted_bot: Person,
491 inserted_community: Community,
495 async fn init_data(pool: &DbPool) -> Data {
496 let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
500 let person_name = "tegan".to_string();
502 let new_person = PersonInsertForm::builder()
503 .name(person_name.clone())
504 .public_key("pubkey".to_string())
505 .instance_id(inserted_instance.id)
508 let inserted_person = Person::create(pool, &new_person).await.unwrap();
510 let local_user_form = LocalUserInsertForm::builder()
511 .person_id(inserted_person.id)
512 .password_encrypted(String::new())
514 let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
516 let new_bot = PersonInsertForm::builder()
517 .name("mybot".to_string())
518 .bot_account(Some(true))
519 .public_key("pubkey".to_string())
520 .instance_id(inserted_instance.id)
523 let inserted_bot = Person::create(pool, &new_bot).await.unwrap();
525 let new_community = CommunityInsertForm::builder()
526 .name("test_community_3".to_string())
527 .title("nada".to_owned())
528 .public_key("pubkey".to_string())
529 .instance_id(inserted_instance.id)
532 let inserted_community = Community::create(pool, &new_community).await.unwrap();
534 // Test a person block, make sure the post query doesn't include their post
535 let blocked_person = PersonInsertForm::builder()
537 .public_key("pubkey".to_string())
538 .instance_id(inserted_instance.id)
541 let inserted_blocked_person = Person::create(pool, &blocked_person).await.unwrap();
543 let post_from_blocked_person = PostInsertForm::builder()
544 .name("blocked_person_post".to_string())
545 .creator_id(inserted_blocked_person.id)
546 .community_id(inserted_community.id)
547 .language_id(Some(LanguageId(1)))
550 Post::create(pool, &post_from_blocked_person).await.unwrap();
553 let person_block = PersonBlockForm {
554 person_id: inserted_person.id,
555 target_id: inserted_blocked_person.id,
558 PersonBlock::block(pool, &person_block).await.unwrap();
561 let new_post = PostInsertForm::builder()
562 .name("test post 3".to_string())
563 .creator_id(inserted_person.id)
564 .community_id(inserted_community.id)
565 .language_id(Some(LanguageId(47)))
568 let inserted_post = Post::create(pool, &new_post).await.unwrap();
570 let new_bot_post = PostInsertForm::builder()
571 .name("test bot post".to_string())
572 .creator_id(inserted_bot.id)
573 .community_id(inserted_community.id)
576 let _inserted_bot_post = Post::create(pool, &new_bot_post).await.unwrap();
582 inserted_blocked_person,
591 async fn post_listing_with_person() {
592 let pool = &build_db_pool_for_tests().await;
593 let data = init_data(pool).await;
595 let local_user_form = LocalUserUpdateForm::builder()
596 .show_bot_accounts(Some(false))
598 let inserted_local_user =
599 LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
603 let read_post_listing = PostQuery::builder()
605 .sort(Some(SortType::New))
606 .community_id(Some(data.inserted_community.id))
607 .local_user(Some(&inserted_local_user))
613 let post_listing_single_with_person = PostView::read(
615 data.inserted_post.id,
616 Some(data.inserted_person.id),
622 let mut expected_post_listing_with_user = expected_post_view(&data, pool).await;
624 // Should be only one person, IE the bot post, and blocked should be missing
625 assert_eq!(1, read_post_listing.len());
627 assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
628 expected_post_listing_with_user.my_vote = Some(0);
630 expected_post_listing_with_user,
631 post_listing_single_with_person
634 let local_user_form = LocalUserUpdateForm::builder()
635 .show_bot_accounts(Some(true))
637 let inserted_local_user =
638 LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
642 let post_listings_with_bots = PostQuery::builder()
644 .sort(Some(SortType::New))
645 .community_id(Some(data.inserted_community.id))
646 .local_user(Some(&inserted_local_user))
651 // should include bot post which has "undetermined" language
652 assert_eq!(2, post_listings_with_bots.len());
654 cleanup(data, pool).await;
659 async fn post_listing_no_person() {
660 let pool = &build_db_pool_for_tests().await;
661 let data = init_data(pool).await;
663 let read_post_listing_multiple_no_person = PostQuery::builder()
665 .sort(Some(SortType::New))
666 .community_id(Some(data.inserted_community.id))
672 let read_post_listing_single_no_person =
673 PostView::read(pool, data.inserted_post.id, None, None)
677 let expected_post_listing_no_person = expected_post_view(&data, pool).await;
679 // Should be 2 posts, with the bot post, and the blocked
680 assert_eq!(3, read_post_listing_multiple_no_person.len());
683 expected_post_listing_no_person,
684 read_post_listing_multiple_no_person[1]
687 expected_post_listing_no_person,
688 read_post_listing_single_no_person
691 cleanup(data, pool).await;
696 async fn post_listing_block_community() {
697 let pool = &build_db_pool_for_tests().await;
698 let data = init_data(pool).await;
700 let community_block = CommunityBlockForm {
701 person_id: data.inserted_person.id,
702 community_id: data.inserted_community.id,
704 CommunityBlock::block(pool, &community_block).await.unwrap();
706 let read_post_listings_with_person_after_block = PostQuery::builder()
708 .sort(Some(SortType::New))
709 .community_id(Some(data.inserted_community.id))
710 .local_user(Some(&data.inserted_local_user))
715 // Should be 0 posts after the community block
716 assert_eq!(0, read_post_listings_with_person_after_block.len());
718 CommunityBlock::unblock(pool, &community_block)
721 cleanup(data, pool).await;
726 async fn post_listing_like() {
727 let pool = &build_db_pool_for_tests().await;
728 let data = init_data(pool).await;
730 let post_like_form = PostLikeForm {
731 post_id: data.inserted_post.id,
732 person_id: data.inserted_person.id,
736 let inserted_post_like = PostLike::like(pool, &post_like_form).await.unwrap();
738 let expected_post_like = PostLike {
739 id: inserted_post_like.id,
740 post_id: data.inserted_post.id,
741 person_id: data.inserted_person.id,
742 published: inserted_post_like.published,
745 assert_eq!(expected_post_like, inserted_post_like);
747 let like_removed = PostLike::remove(pool, data.inserted_person.id, data.inserted_post.id)
750 assert_eq!(1, like_removed);
751 cleanup(data, pool).await;
756 async fn post_listing_person_language() {
757 let pool = &build_db_pool_for_tests().await;
758 let data = init_data(pool).await;
760 let spanish_id = Language::read_id_from_code(pool, Some("es"))
764 let post_spanish = PostInsertForm::builder()
765 .name("asffgdsc".to_string())
766 .creator_id(data.inserted_person.id)
767 .community_id(data.inserted_community.id)
768 .language_id(Some(spanish_id))
771 Post::create(pool, &post_spanish).await.unwrap();
773 let post_listings_all = PostQuery::builder()
775 .sort(Some(SortType::New))
776 .local_user(Some(&data.inserted_local_user))
782 // no language filters specified, all posts should be returned
783 assert_eq!(3, post_listings_all.len());
785 let french_id = Language::read_id_from_code(pool, Some("fr"))
789 LocalUserLanguage::update(pool, vec![french_id], data.inserted_local_user.id)
793 let post_listing_french = PostQuery::builder()
795 .sort(Some(SortType::New))
796 .local_user(Some(&data.inserted_local_user))
802 // only one post in french and one undetermined should be returned
803 assert_eq!(2, post_listing_french.len());
804 assert!(post_listing_french
806 .any(|p| p.post.language_id == french_id));
808 LocalUserLanguage::update(
810 vec![french_id, UNDETERMINED_ID],
811 data.inserted_local_user.id,
815 let post_listings_french_und = PostQuery::builder()
817 .sort(Some(SortType::New))
818 .local_user(Some(&data.inserted_local_user))
824 // french post and undetermined language post should be returned
825 assert_eq!(2, post_listings_french_und.len());
828 post_listings_french_und[0].post.language_id
830 assert_eq!(french_id, post_listings_french_und[1].post.language_id);
832 cleanup(data, pool).await;
835 async fn cleanup(data: Data, pool: &DbPool) {
836 let num_deleted = Post::delete(pool, data.inserted_post.id).await.unwrap();
837 Community::delete(pool, data.inserted_community.id)
840 Person::delete(pool, data.inserted_person.id).await.unwrap();
841 Person::delete(pool, data.inserted_bot.id).await.unwrap();
842 Person::delete(pool, data.inserted_blocked_person.id)
845 Instance::delete(pool, data.inserted_instance.id)
848 assert_eq!(1, num_deleted);
851 async fn expected_post_view(data: &Data, pool: &DbPool) -> PostView {
852 let (inserted_person, inserted_community, inserted_post) = (
853 &data.inserted_person,
854 &data.inserted_community,
857 let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap();
861 id: inserted_post.id,
862 name: inserted_post.name.clone(),
863 creator_id: inserted_person.id,
866 published: inserted_post.published,
868 community_id: inserted_community.id,
874 embed_description: None,
875 embed_video_url: None,
877 ap_id: inserted_post.ap_id.clone(),
879 language_id: LanguageId(47),
880 featured_community: false,
881 featured_local: false,
886 id: inserted_person.id,
887 name: inserted_person.name.clone(),
889 published: inserted_person.published,
891 actor_id: inserted_person.actor_id.clone(),
900 inbox_url: inserted_person.inbox_url.clone(),
901 shared_inbox_url: None,
902 matrix_user_id: None,
904 instance_id: data.inserted_instance.id,
905 private_key: inserted_person.private_key.clone(),
906 public_key: inserted_person.public_key.clone(),
907 last_refreshed_at: inserted_person.last_refreshed_at,
909 creator_banned_from_community: false,
910 community: Community {
911 id: inserted_community.id,
912 name: inserted_community.name.clone(),
917 actor_id: inserted_community.actor_id.clone(),
919 title: "nada".to_owned(),
924 posting_restricted_to_mods: false,
925 published: inserted_community.published,
926 instance_id: data.inserted_instance.id,
927 private_key: inserted_community.private_key.clone(),
928 public_key: inserted_community.public_key.clone(),
929 last_refreshed_at: inserted_community.last_refreshed_at,
930 followers_url: inserted_community.followers_url.clone(),
931 inbox_url: inserted_community.inbox_url.clone(),
932 shared_inbox_url: inserted_community.shared_inbox_url.clone(),
933 moderators_url: inserted_community.moderators_url.clone(),
934 featured_url: inserted_community.featured_url.clone(),
936 counts: PostAggregates {
938 post_id: inserted_post.id,
943 published: agg.published,
944 newest_comment_time_necro: inserted_post.published,
945 newest_comment_time: inserted_post.published,
946 featured_community: false,
947 featured_local: false,
949 subscribed: SubscribedType::NotSubscribed,
952 creator_blocked: false,