1 use crate::structs::PostView;
2 use diesel::{dsl::*, pg::Pg, result::Error, *};
4 aggregates::structs::PostAggregates,
5 newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
14 person_post_aggregates,
22 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
23 local_user::LocalUser,
24 person::{Person, PersonSafe},
25 person_block::PersonBlock,
26 post::{Post, PostRead, PostSaved},
28 traits::{ToSafe, ViewToVec},
29 utils::{functions::hot_rank, fuzzy_search, limit_and_offset},
34 use typed_builder::TypedBuilder;
36 type PostViewTuple = (
40 Option<CommunityPersonBan>,
42 Option<CommunityFollower>,
50 sql_function!(fn coalesce(x: sql_types::Nullable<sql_types::BigInt>, y: sql_types::BigInt) -> sql_types::BigInt);
54 conn: &mut PgConnection,
56 my_person_id: Option<PersonId>,
57 ) -> Result<Self, Error> {
58 // The left join below will return None in this case
59 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
64 creator_banned_from_community,
74 .inner_join(person::table)
75 .inner_join(community::table)
77 community_person_ban::table.on(
79 .eq(community_person_ban::community_id)
80 .and(community_person_ban::person_id.eq(post::creator_id))
82 community_person_ban::expires
84 .or(community_person_ban::expires.gt(now)),
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)),
133 Person::safe_columns_tuple(),
134 Community::safe_columns_tuple(),
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,
147 .first::<PostViewTuple>(conn)?;
149 // If a person is given, then my_vote, if None, should be 0, not null
150 // Necessary to differentiate between other person's votes
151 let my_vote = if my_person_id.is_some() && post_like.is_none() {
161 creator_banned_from_community: creator_banned_from_community.is_some(),
163 subscribed: CommunityFollower::to_subscribed_type(&follower),
164 saved: saved.is_some(),
165 read: read.is_some(),
166 creator_blocked: creator_blocked.is_some(),
173 #[derive(TypedBuilder)]
174 #[builder(field_defaults(default))]
175 pub struct PostQuery<'a> {
177 conn: &'a mut PgConnection,
178 listing_type: Option<ListingType>,
179 sort: Option<SortType>,
180 creator_id: Option<PersonId>,
181 community_id: Option<CommunityId>,
182 community_actor_id: Option<DbUrl>,
183 local_user: Option<&'a LocalUser>,
184 search_term: Option<String>,
185 url_search: Option<String>,
186 saved_only: Option<bool>,
191 impl<'a> PostQuery<'a> {
192 pub fn list(self) -> Result<Vec<PostView>, Error> {
195 // The left join below will return None in this case
196 let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1));
197 let local_user_id_join = self.local_user.map(|l| l.id).unwrap_or(LocalUserId(-1));
199 let mut query = post::table
200 .inner_join(person::table)
201 .inner_join(community::table)
203 community_person_ban::table.on(
205 .eq(community_person_ban::community_id)
206 .and(community_person_ban::person_id.eq(post::creator_id))
208 community_person_ban::expires
210 .or(community_person_ban::expires.gt(now)),
214 .inner_join(post_aggregates::table)
216 community_follower::table.on(
218 .eq(community_follower::community_id)
219 .and(community_follower::person_id.eq(person_id_join)),
223 post_saved::table.on(
225 .eq(post_saved::post_id)
226 .and(post_saved::person_id.eq(person_id_join)),
232 .eq(post_read::post_id)
233 .and(post_read::person_id.eq(person_id_join)),
237 person_block::table.on(
239 .eq(person_block::target_id)
240 .and(person_block::person_id.eq(person_id_join)),
244 community_block::table.on(
246 .eq(community_block::community_id)
247 .and(community_block::person_id.eq(person_id_join)),
253 .eq(post_like::post_id)
254 .and(post_like::person_id.eq(person_id_join)),
258 person_post_aggregates::table.on(
260 .eq(person_post_aggregates::post_id)
261 .and(person_post_aggregates::person_id.eq(person_id_join)),
265 local_user_language::table.on(
267 .eq(local_user_language::language_id)
268 .and(local_user_language::local_user_id.eq(local_user_id_join)),
273 Person::safe_columns_tuple(),
274 Community::safe_columns_tuple(),
275 community_person_ban::all_columns.nullable(),
276 post_aggregates::all_columns,
277 community_follower::all_columns.nullable(),
278 post_saved::all_columns.nullable(),
279 post_read::all_columns.nullable(),
280 person_block::all_columns.nullable(),
281 post_like::score.nullable(),
283 post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
284 post_aggregates::comments,
289 if let Some(listing_type) = self.listing_type {
291 ListingType::Subscribed => {
292 query = query.filter(community_follower::person_id.is_not_null())
294 ListingType::Local => {
295 query = query.filter(community::local.eq(true)).filter(
298 .or(community_follower::person_id.eq(person_id_join)),
301 ListingType::All => {
302 query = query.filter(
305 .or(community_follower::person_id.eq(person_id_join)),
311 if let Some(community_id) = self.community_id {
313 .filter(post::community_id.eq(community_id))
314 .then_order_by(post_aggregates::stickied.desc());
317 if let Some(community_actor_id) = self.community_actor_id {
319 .filter(community::actor_id.eq(community_actor_id))
320 .then_order_by(post_aggregates::stickied.desc());
323 if let Some(url_search) = self.url_search {
324 query = query.filter(post::url.eq(url_search));
327 if let Some(search_term) = self.search_term {
328 let searcher = fuzzy_search(&search_term);
329 query = query.filter(
331 .ilike(searcher.to_owned())
332 .or(post::body.ilike(searcher)),
336 // If its for a specific person, show the removed / deleted
337 if let Some(creator_id) = self.creator_id {
338 query = query.filter(post::creator_id.eq(creator_id));
341 if !self.local_user.map(|l| l.show_nsfw).unwrap_or(false) {
343 .filter(post::nsfw.eq(false))
344 .filter(community::nsfw.eq(false));
347 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
348 query = query.filter(person::bot_account.eq(false));
351 if self.saved_only.unwrap_or(false) {
352 query = query.filter(post_saved::id.is_not_null());
354 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
355 // setting wont be able to see saved posts.
356 else if !self.local_user.map(|l| l.show_read_posts).unwrap_or(true) {
357 query = query.filter(post_read::id.is_null());
360 if self.local_user.is_some() {
361 // Filter out the rows with missing languages
362 query = query.filter(local_user_language::id.is_not_null());
364 // Don't show blocked communities or persons
365 query = query.filter(community_block::person_id.is_null());
366 query = query.filter(person_block::person_id.is_null());
369 query = match self.sort.unwrap_or(SortType::Hot) {
370 SortType::Active => query
373 post_aggregates::score,
374 post_aggregates::newest_comment_time_necro,
378 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
379 SortType::Hot => query
380 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
381 .then_order_by(post_aggregates::published.desc()),
382 SortType::New => query.then_order_by(post_aggregates::published.desc()),
383 SortType::Old => query.then_order_by(post_aggregates::published.asc()),
384 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
385 SortType::MostComments => query
386 .then_order_by(post_aggregates::comments.desc())
387 .then_order_by(post_aggregates::published.desc()),
388 SortType::TopAll => query
389 .then_order_by(post_aggregates::score.desc())
390 .then_order_by(post_aggregates::published.desc()),
391 SortType::TopYear => query
392 .filter(post_aggregates::published.gt(now - 1.years()))
393 .then_order_by(post_aggregates::score.desc())
394 .then_order_by(post_aggregates::published.desc()),
395 SortType::TopMonth => query
396 .filter(post_aggregates::published.gt(now - 1.months()))
397 .then_order_by(post_aggregates::score.desc())
398 .then_order_by(post_aggregates::published.desc()),
399 SortType::TopWeek => query
400 .filter(post_aggregates::published.gt(now - 1.weeks()))
401 .then_order_by(post_aggregates::score.desc())
402 .then_order_by(post_aggregates::published.desc()),
403 SortType::TopDay => query
404 .filter(post_aggregates::published.gt(now - 1.days()))
405 .then_order_by(post_aggregates::score.desc())
406 .then_order_by(post_aggregates::published.desc()),
409 let (limit, offset) = limit_and_offset(self.page, self.limit)?;
414 .filter(post::removed.eq(false))
415 .filter(post::deleted.eq(false))
416 .filter(community::removed.eq(false))
417 .filter(community::deleted.eq(false));
419 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
421 let res = query.load::<PostViewTuple>(self.conn)?;
423 Ok(PostView::from_tuple_to_vec(res))
427 impl ViewToVec for PostView {
428 type DbTuple = PostViewTuple;
429 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
436 creator_banned_from_community: a.3.is_some(),
438 subscribed: CommunityFollower::to_subscribed_type(&a.5),
439 saved: a.6.is_some(),
441 creator_blocked: a.8.is_some(),
443 unread_comments: a.10,
445 .collect::<Vec<Self>>()
451 use crate::post_view::{PostQuery, PostView};
452 use diesel::PgConnection;
453 use lemmy_db_schema::{
454 aggregates::structs::PostAggregates,
455 newtypes::LanguageId,
457 actor_language::LocalUserLanguage,
459 community_block::{CommunityBlock, CommunityBlockForm},
462 local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm},
464 person_block::{PersonBlock, PersonBlockForm},
467 traits::{Blockable, Crud, Likeable},
468 utils::establish_unpooled_connection,
472 use serial_test::serial;
475 inserted_instance: Instance,
476 inserted_person: Person,
477 inserted_local_user: LocalUser,
478 inserted_blocked_person: Person,
479 inserted_bot: Person,
480 inserted_community: Community,
484 fn init_data(conn: &mut PgConnection) -> Data {
485 let inserted_instance = Instance::create(conn, "my_domain.tld").unwrap();
487 let person_name = "tegan".to_string();
489 let new_person = PersonInsertForm::builder()
490 .name(person_name.to_owned())
491 .public_key("pubkey".to_string())
492 .instance_id(inserted_instance.id)
495 let inserted_person = Person::create(conn, &new_person).unwrap();
497 let local_user_form = LocalUserInsertForm::builder()
498 .person_id(inserted_person.id)
499 .password_encrypted("".to_string())
501 let inserted_local_user = LocalUser::create(conn, &local_user_form).unwrap();
503 let new_bot = PersonInsertForm::builder()
504 .name("mybot".to_string())
505 .bot_account(Some(true))
506 .public_key("pubkey".to_string())
507 .instance_id(inserted_instance.id)
510 let inserted_bot = Person::create(conn, &new_bot).unwrap();
512 let new_community = CommunityInsertForm::builder()
513 .name("test_community_3".to_string())
514 .title("nada".to_owned())
515 .public_key("pubkey".to_string())
516 .instance_id(inserted_instance.id)
519 let inserted_community = Community::create(conn, &new_community).unwrap();
521 // Test a person block, make sure the post query doesn't include their post
522 let blocked_person = PersonInsertForm::builder()
524 .public_key("pubkey".to_string())
525 .instance_id(inserted_instance.id)
528 let inserted_blocked_person = Person::create(conn, &blocked_person).unwrap();
530 let post_from_blocked_person = PostInsertForm::builder()
531 .name("blocked_person_post".to_string())
532 .creator_id(inserted_blocked_person.id)
533 .community_id(inserted_community.id)
534 .language_id(Some(LanguageId(1)))
537 Post::create(conn, &post_from_blocked_person).unwrap();
540 let person_block = PersonBlockForm {
541 person_id: inserted_person.id,
542 target_id: inserted_blocked_person.id,
545 PersonBlock::block(conn, &person_block).unwrap();
548 let new_post = PostInsertForm::builder()
549 .name("test post 3".to_string())
550 .creator_id(inserted_person.id)
551 .community_id(inserted_community.id)
552 .language_id(Some(LanguageId(47)))
555 let inserted_post = Post::create(conn, &new_post).unwrap();
557 let new_bot_post = PostInsertForm::builder()
558 .name("test bot post".to_string())
559 .creator_id(inserted_bot.id)
560 .community_id(inserted_community.id)
563 let _inserted_bot_post = Post::create(conn, &new_bot_post).unwrap();
569 inserted_blocked_person,
578 fn post_listing_with_person() {
579 let conn = &mut establish_unpooled_connection();
580 let data = init_data(conn);
582 let local_user_form = LocalUserUpdateForm::builder()
583 .show_bot_accounts(Some(false))
585 let inserted_local_user =
586 LocalUser::update(conn, data.inserted_local_user.id, &local_user_form).unwrap();
588 let read_post_listing = PostQuery::builder()
590 .sort(Some(SortType::New))
591 .community_id(Some(data.inserted_community.id))
592 .local_user(Some(&inserted_local_user))
597 let post_listing_single_with_person =
598 PostView::read(conn, data.inserted_post.id, Some(data.inserted_person.id)).unwrap();
600 let mut expected_post_listing_with_user = expected_post_view(&data, conn);
602 // Should be only one person, IE the bot post, and blocked should be missing
603 assert_eq!(1, read_post_listing.len());
605 assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
606 expected_post_listing_with_user.my_vote = Some(0);
608 expected_post_listing_with_user,
609 post_listing_single_with_person
612 let local_user_form = LocalUserUpdateForm::builder()
613 .show_bot_accounts(Some(true))
615 let inserted_local_user =
616 LocalUser::update(conn, data.inserted_local_user.id, &local_user_form).unwrap();
618 let post_listings_with_bots = PostQuery::builder()
620 .sort(Some(SortType::New))
621 .community_id(Some(data.inserted_community.id))
622 .local_user(Some(&inserted_local_user))
626 // should include bot post which has "undetermined" language
627 assert_eq!(2, post_listings_with_bots.len());
634 fn post_listing_no_person() {
635 let conn = &mut establish_unpooled_connection();
636 let data = init_data(conn);
638 let read_post_listing_multiple_no_person = PostQuery::builder()
640 .sort(Some(SortType::New))
641 .community_id(Some(data.inserted_community.id))
646 let read_post_listing_single_no_person =
647 PostView::read(conn, data.inserted_post.id, None).unwrap();
649 let expected_post_listing_no_person = expected_post_view(&data, conn);
651 // Should be 2 posts, with the bot post, and the blocked
652 assert_eq!(3, read_post_listing_multiple_no_person.len());
655 expected_post_listing_no_person,
656 read_post_listing_multiple_no_person[1]
659 expected_post_listing_no_person,
660 read_post_listing_single_no_person
668 fn post_listing_block_community() {
669 let conn = &mut establish_unpooled_connection();
670 let data = init_data(conn);
672 let community_block = CommunityBlockForm {
673 person_id: data.inserted_person.id,
674 community_id: data.inserted_community.id,
676 CommunityBlock::block(conn, &community_block).unwrap();
678 let read_post_listings_with_person_after_block = PostQuery::builder()
680 .sort(Some(SortType::New))
681 .community_id(Some(data.inserted_community.id))
682 .local_user(Some(&data.inserted_local_user))
686 // Should be 0 posts after the community block
687 assert_eq!(0, read_post_listings_with_person_after_block.len());
689 CommunityBlock::unblock(conn, &community_block).unwrap();
695 fn post_listing_like() {
696 let conn = &mut establish_unpooled_connection();
697 let data = init_data(conn);
699 let post_like_form = PostLikeForm {
700 post_id: data.inserted_post.id,
701 person_id: data.inserted_person.id,
705 let inserted_post_like = PostLike::like(conn, &post_like_form).unwrap();
707 let expected_post_like = PostLike {
708 id: inserted_post_like.id,
709 post_id: data.inserted_post.id,
710 person_id: data.inserted_person.id,
711 published: inserted_post_like.published,
714 assert_eq!(expected_post_like, inserted_post_like);
717 PostLike::remove(conn, data.inserted_person.id, data.inserted_post.id).unwrap();
718 assert_eq!(1, like_removed);
724 fn post_listing_person_language() {
725 let conn = &mut establish_unpooled_connection();
726 let data = init_data(conn);
728 let spanish_id = Language::read_id_from_code(conn, "es").unwrap();
729 let post_spanish = PostInsertForm::builder()
730 .name("asffgdsc".to_string())
731 .creator_id(data.inserted_person.id)
732 .community_id(data.inserted_community.id)
733 .language_id(Some(spanish_id))
736 Post::create(conn, &post_spanish).unwrap();
738 let post_listings_all = PostQuery::builder()
740 .sort(Some(SortType::New))
741 .local_user(Some(&data.inserted_local_user))
746 // no language filters specified, all posts should be returned
747 assert_eq!(3, post_listings_all.len());
749 let french_id = Language::read_id_from_code(conn, "fr").unwrap();
750 LocalUserLanguage::update(conn, vec![french_id], data.inserted_local_user.id).unwrap();
752 let post_listing_french = PostQuery::builder()
754 .sort(Some(SortType::New))
755 .local_user(Some(&data.inserted_local_user))
760 // only one french language post should be returned
761 assert_eq!(1, post_listing_french.len());
762 assert_eq!(french_id, post_listing_french[0].post.language_id);
764 let undetermined_id = Language::read_id_from_code(conn, "und").unwrap();
765 LocalUserLanguage::update(
767 vec![french_id, undetermined_id],
768 data.inserted_local_user.id,
771 let post_listings_french_und = PostQuery::builder()
773 .sort(Some(SortType::New))
774 .local_user(Some(&data.inserted_local_user))
779 // french post and undetermined language post should be returned
780 assert_eq!(2, post_listings_french_und.len());
783 post_listings_french_und[0].post.language_id
785 assert_eq!(french_id, post_listings_french_und[1].post.language_id);
790 fn cleanup(data: Data, conn: &mut PgConnection) {
791 let num_deleted = Post::delete(conn, data.inserted_post.id).unwrap();
792 Community::delete(conn, data.inserted_community.id).unwrap();
793 Person::delete(conn, data.inserted_person.id).unwrap();
794 Person::delete(conn, data.inserted_bot.id).unwrap();
795 Person::delete(conn, data.inserted_blocked_person.id).unwrap();
796 Instance::delete(conn, data.inserted_instance.id).unwrap();
797 assert_eq!(1, num_deleted);
800 fn expected_post_view(data: &Data, conn: &mut PgConnection) -> PostView {
801 let (inserted_person, inserted_community, inserted_post) = (
802 &data.inserted_person,
803 &data.inserted_community,
806 let agg = PostAggregates::read(conn, inserted_post.id).unwrap();
810 id: inserted_post.id,
811 name: inserted_post.name.clone(),
812 creator_id: inserted_person.id,
815 published: inserted_post.published,
817 community_id: inserted_community.id,
824 embed_description: None,
825 embed_video_url: None,
827 ap_id: inserted_post.ap_id.to_owned(),
829 language_id: LanguageId(47),
833 creator: PersonSafe {
834 id: inserted_person.id,
835 name: inserted_person.name.clone(),
837 published: inserted_person.published,
839 actor_id: inserted_person.actor_id.to_owned(),
848 inbox_url: inserted_person.inbox_url.to_owned(),
849 shared_inbox_url: None,
850 matrix_user_id: None,
852 instance_id: data.inserted_instance.id,
854 creator_banned_from_community: false,
855 community: CommunitySafe {
856 id: inserted_community.id,
857 name: inserted_community.name.clone(),
862 actor_id: inserted_community.actor_id.to_owned(),
864 title: "nada".to_owned(),
869 posting_restricted_to_mods: false,
870 published: inserted_community.published,
871 instance_id: data.inserted_instance.id,
873 counts: PostAggregates {
875 post_id: inserted_post.id,
881 published: agg.published,
882 newest_comment_time_necro: inserted_post.published,
883 newest_comment_time: inserted_post.published,
885 subscribed: SubscribedType::NotSubscribed,
888 creator_blocked: false,