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))
87 community_person_ban::expires
89 .or(community_person_ban::expires.gt(now)),
93 .inner_join(post_aggregates::table)
95 community_follower::table.on(
97 .eq(community_follower::community_id)
98 .and(community_follower::person_id.eq(person_id_join)),
102 post_saved::table.on(
104 .eq(post_saved::post_id)
105 .and(post_saved::person_id.eq(person_id_join)),
111 .eq(post_read::post_id)
112 .and(post_read::person_id.eq(person_id_join)),
116 person_block::table.on(
118 .eq(person_block::target_id)
119 .and(person_block::person_id.eq(person_id_join)),
125 .eq(post_like::post_id)
126 .and(post_like::person_id.eq(person_id_join)),
130 person_post_aggregates::table.on(
132 .eq(person_post_aggregates::post_id)
133 .and(person_post_aggregates::person_id.eq(person_id_join)),
139 community::all_columns,
140 community_person_ban::all_columns.nullable(),
141 post_aggregates::all_columns,
142 community_follower::all_columns.nullable(),
143 post_saved::all_columns.nullable(),
144 post_read::all_columns.nullable(),
145 person_block::all_columns.nullable(),
146 post_like::score.nullable(),
148 post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
149 post_aggregates::comments,
154 // Hide deleted and removed for non-admins or mods
155 if !is_mod_or_admin.unwrap_or(true) {
157 .filter(community::removed.eq(false))
158 .filter(community::deleted.eq(false));
165 creator_banned_from_community,
173 ) = query.first::<PostViewTuple>(conn).await?;
175 // If a person is given, then my_vote, if None, should be 0, not null
176 // Necessary to differentiate between other person's votes
177 let my_vote = if my_person_id.is_some() && post_like.is_none() {
187 creator_banned_from_community: creator_banned_from_community.is_some(),
189 subscribed: CommunityFollower::to_subscribed_type(&follower),
190 saved: saved.is_some(),
191 read: read.is_some(),
192 creator_blocked: creator_blocked.is_some(),
199 #[derive(TypedBuilder)]
200 #[builder(field_defaults(default))]
201 pub struct PostQuery<'a> {
204 listing_type: Option<ListingType>,
205 sort: Option<SortType>,
206 creator_id: Option<PersonId>,
207 community_id: Option<CommunityId>,
208 local_user: Option<&'a LocalUser>,
209 search_term: Option<String>,
210 url_search: Option<String>,
211 saved_only: Option<bool>,
212 /// Used to show deleted or removed posts for admins
213 is_mod_or_admin: Option<bool>,
218 impl<'a> PostQuery<'a> {
219 pub async fn list(self) -> Result<Vec<PostView>, Error> {
220 let conn = &mut get_conn(self.pool).await?;
222 // The left join below will return None in this case
223 let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1));
224 let local_user_id_join = self.local_user.map(|l| l.id).unwrap_or(LocalUserId(-1));
226 let mut query = post::table
227 .inner_join(person::table)
228 .inner_join(community::table)
230 community_person_ban::table.on(
232 .eq(community_person_ban::community_id)
233 .and(community_person_ban::person_id.eq(post::creator_id))
235 community_person_ban::expires
237 .or(community_person_ban::expires.gt(now)),
241 .inner_join(post_aggregates::table)
243 community_follower::table.on(
245 .eq(community_follower::community_id)
246 .and(community_follower::person_id.eq(person_id_join)),
250 post_saved::table.on(
252 .eq(post_saved::post_id)
253 .and(post_saved::person_id.eq(person_id_join)),
259 .eq(post_read::post_id)
260 .and(post_read::person_id.eq(person_id_join)),
264 person_block::table.on(
266 .eq(person_block::target_id)
267 .and(person_block::person_id.eq(person_id_join)),
271 community_block::table.on(
273 .eq(community_block::community_id)
274 .and(community_block::person_id.eq(person_id_join)),
280 .eq(post_like::post_id)
281 .and(post_like::person_id.eq(person_id_join)),
285 person_post_aggregates::table.on(
287 .eq(person_post_aggregates::post_id)
288 .and(person_post_aggregates::person_id.eq(person_id_join)),
292 local_user_language::table.on(
294 .eq(local_user_language::language_id)
295 .and(local_user_language::local_user_id.eq(local_user_id_join)),
301 community::all_columns,
302 community_person_ban::all_columns.nullable(),
303 post_aggregates::all_columns,
304 community_follower::all_columns.nullable(),
305 post_saved::all_columns.nullable(),
306 post_read::all_columns.nullable(),
307 person_block::all_columns.nullable(),
308 post_like::score.nullable(),
310 post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
311 post_aggregates::comments,
316 // Hide deleted and removed for non-admins or mods
317 // TODO This eventually needs to show posts where you are the creator
318 if !self.is_mod_or_admin.unwrap_or(true) {
320 .filter(community::removed.eq(false))
321 .filter(community::deleted.eq(false));
324 if let Some(listing_type) = self.listing_type {
326 ListingType::Subscribed => {
327 query = query.filter(community_follower::person_id.is_not_null())
329 ListingType::Local => {
330 query = query.filter(community::local.eq(true)).filter(
333 .or(community_follower::person_id.eq(person_id_join)),
336 ListingType::All => {
337 query = query.filter(
340 .or(community_follower::person_id.eq(person_id_join)),
345 if self.community_id.is_none() {
346 query = query.then_order_by(post_aggregates::featured_local.desc());
347 } else if let Some(community_id) = self.community_id {
349 .filter(post::community_id.eq(community_id))
350 .then_order_by(post_aggregates::featured_community.desc());
353 if let Some(url_search) = self.url_search {
354 query = query.filter(post::url.eq(url_search));
357 if let Some(search_term) = self.search_term {
358 let searcher = fuzzy_search(&search_term);
359 query = query.filter(
361 .ilike(searcher.clone())
362 .or(post::body.ilike(searcher)),
366 if let Some(creator_id) = self.creator_id {
367 query = query.filter(post::creator_id.eq(creator_id));
370 if !self.local_user.map(|l| l.show_nsfw).unwrap_or(false) {
372 .filter(post::nsfw.eq(false))
373 .filter(community::nsfw.eq(false));
376 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
377 query = query.filter(person::bot_account.eq(false));
380 if self.saved_only.unwrap_or(false) {
381 query = query.filter(post_saved::post_id.is_not_null());
383 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
384 // setting wont be able to see saved posts.
385 else if !self.local_user.map(|l| l.show_read_posts).unwrap_or(true) {
386 query = query.filter(post_read::post_id.is_null());
389 if self.local_user.is_some() {
390 // Filter out the rows with missing languages
391 query = query.filter(local_user_language::language_id.is_not_null());
393 // Don't show blocked communities or persons
394 query = query.filter(community_block::person_id.is_null());
395 query = query.filter(person_block::person_id.is_null());
398 query = match self.sort.unwrap_or(SortType::Hot) {
399 SortType::Active => query
402 post_aggregates::score,
403 post_aggregates::newest_comment_time_necro,
407 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
408 SortType::Hot => query
409 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
410 .then_order_by(post_aggregates::published.desc()),
411 SortType::New => query.then_order_by(post_aggregates::published.desc()),
412 SortType::Old => query.then_order_by(post_aggregates::published.asc()),
413 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
414 SortType::MostComments => query
415 .then_order_by(post_aggregates::comments.desc())
416 .then_order_by(post_aggregates::published.desc()),
417 SortType::TopAll => query
418 .then_order_by(post_aggregates::score.desc())
419 .then_order_by(post_aggregates::published.desc()),
420 SortType::TopYear => query
421 .filter(post_aggregates::published.gt(now - 1.years()))
422 .then_order_by(post_aggregates::score.desc())
423 .then_order_by(post_aggregates::published.desc()),
424 SortType::TopMonth => query
425 .filter(post_aggregates::published.gt(now - 1.months()))
426 .then_order_by(post_aggregates::score.desc())
427 .then_order_by(post_aggregates::published.desc()),
428 SortType::TopWeek => query
429 .filter(post_aggregates::published.gt(now - 1.weeks()))
430 .then_order_by(post_aggregates::score.desc())
431 .then_order_by(post_aggregates::published.desc()),
432 SortType::TopDay => query
433 .filter(post_aggregates::published.gt(now - 1.days()))
434 .then_order_by(post_aggregates::score.desc())
435 .then_order_by(post_aggregates::published.desc()),
438 let (limit, offset) = limit_and_offset(self.page, self.limit)?;
440 query = query.limit(limit).offset(offset);
442 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
444 let res = query.load::<PostViewTuple>(conn).await?;
446 Ok(res.into_iter().map(PostView::from_tuple).collect())
450 impl JoinView for PostView {
451 type JoinTuple = PostViewTuple;
452 fn from_tuple(a: Self::JoinTuple) -> Self {
457 creator_banned_from_community: a.3.is_some(),
459 subscribed: CommunityFollower::to_subscribed_type(&a.5),
460 saved: a.6.is_some(),
462 creator_blocked: a.8.is_some(),
464 unread_comments: a.10,
471 use crate::post_view::{PostQuery, PostView};
472 use lemmy_db_schema::{
473 aggregates::structs::PostAggregates,
474 impls::actor_language::UNDETERMINED_ID,
475 newtypes::LanguageId,
477 actor_language::LocalUserLanguage,
478 community::{Community, CommunityInsertForm},
479 community_block::{CommunityBlock, CommunityBlockForm},
482 local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm},
483 person::{Person, PersonInsertForm},
484 person_block::{PersonBlock, PersonBlockForm},
485 post::{Post, PostInsertForm, PostLike, PostLikeForm},
487 traits::{Blockable, Crud, Likeable},
488 utils::{build_db_pool_for_tests, DbPool},
492 use serial_test::serial;
495 inserted_instance: Instance,
496 inserted_person: Person,
497 inserted_local_user: LocalUser,
498 inserted_blocked_person: Person,
499 inserted_bot: Person,
500 inserted_community: Community,
504 async fn init_data(pool: &DbPool) -> Data {
505 let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
509 let person_name = "tegan".to_string();
511 let new_person = PersonInsertForm::builder()
512 .name(person_name.clone())
513 .public_key("pubkey".to_string())
514 .instance_id(inserted_instance.id)
517 let inserted_person = Person::create(pool, &new_person).await.unwrap();
519 let local_user_form = LocalUserInsertForm::builder()
520 .person_id(inserted_person.id)
521 .password_encrypted(String::new())
523 let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
525 let new_bot = PersonInsertForm::builder()
526 .name("mybot".to_string())
527 .bot_account(Some(true))
528 .public_key("pubkey".to_string())
529 .instance_id(inserted_instance.id)
532 let inserted_bot = Person::create(pool, &new_bot).await.unwrap();
534 let new_community = CommunityInsertForm::builder()
535 .name("test_community_3".to_string())
536 .title("nada".to_owned())
537 .public_key("pubkey".to_string())
538 .instance_id(inserted_instance.id)
541 let inserted_community = Community::create(pool, &new_community).await.unwrap();
543 // Test a person block, make sure the post query doesn't include their post
544 let blocked_person = PersonInsertForm::builder()
546 .public_key("pubkey".to_string())
547 .instance_id(inserted_instance.id)
550 let inserted_blocked_person = Person::create(pool, &blocked_person).await.unwrap();
552 let post_from_blocked_person = PostInsertForm::builder()
553 .name("blocked_person_post".to_string())
554 .creator_id(inserted_blocked_person.id)
555 .community_id(inserted_community.id)
556 .language_id(Some(LanguageId(1)))
559 Post::create(pool, &post_from_blocked_person).await.unwrap();
562 let person_block = PersonBlockForm {
563 person_id: inserted_person.id,
564 target_id: inserted_blocked_person.id,
567 PersonBlock::block(pool, &person_block).await.unwrap();
570 let new_post = PostInsertForm::builder()
571 .name("test post 3".to_string())
572 .creator_id(inserted_person.id)
573 .community_id(inserted_community.id)
574 .language_id(Some(LanguageId(47)))
577 let inserted_post = Post::create(pool, &new_post).await.unwrap();
579 let new_bot_post = PostInsertForm::builder()
580 .name("test bot post".to_string())
581 .creator_id(inserted_bot.id)
582 .community_id(inserted_community.id)
585 let _inserted_bot_post = Post::create(pool, &new_bot_post).await.unwrap();
591 inserted_blocked_person,
600 async fn post_listing_with_person() {
601 let pool = &build_db_pool_for_tests().await;
602 let data = init_data(pool).await;
604 let local_user_form = LocalUserUpdateForm::builder()
605 .show_bot_accounts(Some(false))
607 let inserted_local_user =
608 LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
612 let read_post_listing = PostQuery::builder()
614 .sort(Some(SortType::New))
615 .community_id(Some(data.inserted_community.id))
616 .local_user(Some(&inserted_local_user))
622 let post_listing_single_with_person = PostView::read(
624 data.inserted_post.id,
625 Some(data.inserted_person.id),
631 let mut expected_post_listing_with_user = expected_post_view(&data, pool).await;
633 // Should be only one person, IE the bot post, and blocked should be missing
634 assert_eq!(1, read_post_listing.len());
636 assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
637 expected_post_listing_with_user.my_vote = Some(0);
639 expected_post_listing_with_user,
640 post_listing_single_with_person
643 let local_user_form = LocalUserUpdateForm::builder()
644 .show_bot_accounts(Some(true))
646 let inserted_local_user =
647 LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
651 let post_listings_with_bots = PostQuery::builder()
653 .sort(Some(SortType::New))
654 .community_id(Some(data.inserted_community.id))
655 .local_user(Some(&inserted_local_user))
660 // should include bot post which has "undetermined" language
661 assert_eq!(2, post_listings_with_bots.len());
663 cleanup(data, pool).await;
668 async fn post_listing_no_person() {
669 let pool = &build_db_pool_for_tests().await;
670 let data = init_data(pool).await;
672 let read_post_listing_multiple_no_person = PostQuery::builder()
674 .sort(Some(SortType::New))
675 .community_id(Some(data.inserted_community.id))
681 let read_post_listing_single_no_person =
682 PostView::read(pool, data.inserted_post.id, None, None)
686 let expected_post_listing_no_person = expected_post_view(&data, pool).await;
688 // Should be 2 posts, with the bot post, and the blocked
689 assert_eq!(3, read_post_listing_multiple_no_person.len());
692 expected_post_listing_no_person,
693 read_post_listing_multiple_no_person[1]
696 expected_post_listing_no_person,
697 read_post_listing_single_no_person
700 cleanup(data, pool).await;
705 async fn post_listing_block_community() {
706 let pool = &build_db_pool_for_tests().await;
707 let data = init_data(pool).await;
709 let community_block = CommunityBlockForm {
710 person_id: data.inserted_person.id,
711 community_id: data.inserted_community.id,
713 CommunityBlock::block(pool, &community_block).await.unwrap();
715 let read_post_listings_with_person_after_block = PostQuery::builder()
717 .sort(Some(SortType::New))
718 .community_id(Some(data.inserted_community.id))
719 .local_user(Some(&data.inserted_local_user))
724 // Should be 0 posts after the community block
725 assert_eq!(0, read_post_listings_with_person_after_block.len());
727 CommunityBlock::unblock(pool, &community_block)
730 cleanup(data, pool).await;
735 async fn post_listing_like() {
736 let pool = &build_db_pool_for_tests().await;
737 let data = init_data(pool).await;
739 let post_like_form = PostLikeForm {
740 post_id: data.inserted_post.id,
741 person_id: data.inserted_person.id,
745 let inserted_post_like = PostLike::like(pool, &post_like_form).await.unwrap();
747 let expected_post_like = PostLike {
748 id: inserted_post_like.id,
749 post_id: data.inserted_post.id,
750 person_id: data.inserted_person.id,
751 published: inserted_post_like.published,
754 assert_eq!(expected_post_like, inserted_post_like);
756 let like_removed = PostLike::remove(pool, data.inserted_person.id, data.inserted_post.id)
759 assert_eq!(1, like_removed);
760 cleanup(data, pool).await;
765 async fn post_listing_person_language() {
766 let pool = &build_db_pool_for_tests().await;
767 let data = init_data(pool).await;
769 let spanish_id = Language::read_id_from_code(pool, Some("es"))
773 let post_spanish = PostInsertForm::builder()
774 .name("asffgdsc".to_string())
775 .creator_id(data.inserted_person.id)
776 .community_id(data.inserted_community.id)
777 .language_id(Some(spanish_id))
780 Post::create(pool, &post_spanish).await.unwrap();
782 let post_listings_all = PostQuery::builder()
784 .sort(Some(SortType::New))
785 .local_user(Some(&data.inserted_local_user))
791 // no language filters specified, all posts should be returned
792 assert_eq!(3, post_listings_all.len());
794 let french_id = Language::read_id_from_code(pool, Some("fr"))
798 LocalUserLanguage::update(pool, vec![french_id], data.inserted_local_user.id)
802 let post_listing_french = PostQuery::builder()
804 .sort(Some(SortType::New))
805 .local_user(Some(&data.inserted_local_user))
811 // only one french language post should be returned
812 assert_eq!(1, post_listing_french.len());
813 assert_eq!(french_id, post_listing_french[0].post.language_id);
815 LocalUserLanguage::update(
817 vec![french_id, UNDETERMINED_ID],
818 data.inserted_local_user.id,
822 let post_listings_french_und = PostQuery::builder()
824 .sort(Some(SortType::New))
825 .local_user(Some(&data.inserted_local_user))
831 // french post and undetermined language post should be returned
832 assert_eq!(2, post_listings_french_und.len());
835 post_listings_french_und[0].post.language_id
837 assert_eq!(french_id, post_listings_french_und[1].post.language_id);
839 cleanup(data, pool).await;
842 async fn cleanup(data: Data, pool: &DbPool) {
843 let num_deleted = Post::delete(pool, data.inserted_post.id).await.unwrap();
844 Community::delete(pool, data.inserted_community.id)
847 Person::delete(pool, data.inserted_person.id).await.unwrap();
848 Person::delete(pool, data.inserted_bot.id).await.unwrap();
849 Person::delete(pool, data.inserted_blocked_person.id)
852 Instance::delete(pool, data.inserted_instance.id)
855 assert_eq!(1, num_deleted);
858 async fn expected_post_view(data: &Data, pool: &DbPool) -> PostView {
859 let (inserted_person, inserted_community, inserted_post) = (
860 &data.inserted_person,
861 &data.inserted_community,
864 let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap();
868 id: inserted_post.id,
869 name: inserted_post.name.clone(),
870 creator_id: inserted_person.id,
873 published: inserted_post.published,
875 community_id: inserted_community.id,
881 embed_description: None,
882 embed_video_url: None,
884 ap_id: inserted_post.ap_id.clone(),
886 language_id: LanguageId(47),
887 featured_community: false,
888 featured_local: false,
893 id: inserted_person.id,
894 name: inserted_person.name.clone(),
896 published: inserted_person.published,
898 actor_id: inserted_person.actor_id.clone(),
907 inbox_url: inserted_person.inbox_url.clone(),
908 shared_inbox_url: None,
909 matrix_user_id: None,
911 instance_id: data.inserted_instance.id,
912 private_key: inserted_person.private_key.clone(),
913 public_key: inserted_person.public_key.clone(),
914 last_refreshed_at: inserted_person.last_refreshed_at,
916 creator_banned_from_community: false,
917 community: Community {
918 id: inserted_community.id,
919 name: inserted_community.name.clone(),
924 actor_id: inserted_community.actor_id.clone(),
926 title: "nada".to_owned(),
931 posting_restricted_to_mods: false,
932 published: inserted_community.published,
933 instance_id: data.inserted_instance.id,
934 private_key: inserted_community.private_key.clone(),
935 public_key: inserted_community.public_key.clone(),
936 last_refreshed_at: inserted_community.last_refreshed_at,
937 followers_url: inserted_community.followers_url.clone(),
938 inbox_url: inserted_community.inbox_url.clone(),
939 shared_inbox_url: inserted_community.shared_inbox_url.clone(),
940 moderators_url: inserted_community.moderators_url.clone(),
941 featured_url: inserted_community.featured_url.clone(),
943 counts: PostAggregates {
945 post_id: inserted_post.id,
950 published: agg.published,
951 newest_comment_time_necro: inserted_post.published,
952 newest_comment_time: inserted_post.published,
953 featured_community: false,
954 featured_local: false,
956 subscribed: SubscribedType::NotSubscribed,
959 creator_blocked: false,