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},
461 local_user::{LocalUser, LocalUserForm},
463 person_block::{PersonBlock, PersonBlockForm},
466 traits::{Blockable, Crud, Likeable},
467 utils::establish_unpooled_connection,
471 use serial_test::serial;
474 inserted_person: Person,
475 inserted_local_user: LocalUser,
476 inserted_blocked_person: Person,
477 inserted_bot: Person,
478 inserted_community: Community,
482 fn init_data(conn: &mut PgConnection) -> Data {
483 let person_name = "tegan".to_string();
485 let new_person = PersonForm {
486 name: person_name.to_owned(),
487 public_key: Some("pubkey".to_string()),
488 ..PersonForm::default()
491 let inserted_person = Person::create(conn, &new_person).unwrap();
493 let local_user_form = LocalUserForm {
494 person_id: Some(inserted_person.id),
495 password_encrypted: Some("".to_string()),
498 let inserted_local_user = LocalUser::create(conn, &local_user_form).unwrap();
500 let new_bot = PersonForm {
501 name: "mybot".to_string(),
502 bot_account: Some(true),
503 public_key: Some("pubkey".to_string()),
504 ..PersonForm::default()
507 let inserted_bot = Person::create(conn, &new_bot).unwrap();
509 let new_community = CommunityForm {
510 name: "test_community_3".to_string(),
511 title: "nada".to_owned(),
512 public_key: Some("pubkey".to_string()),
513 ..CommunityForm::default()
516 let inserted_community = Community::create(conn, &new_community).unwrap();
518 // Test a person block, make sure the post query doesn't include their post
519 let blocked_person = PersonForm {
521 public_key: Some("pubkey".to_string()),
522 ..PersonForm::default()
525 let inserted_blocked_person = Person::create(conn, &blocked_person).unwrap();
527 let post_from_blocked_person = PostForm {
528 name: "blocked_person_post".to_string(),
529 creator_id: inserted_blocked_person.id,
530 community_id: inserted_community.id,
531 language_id: Some(LanguageId(1)),
532 ..PostForm::default()
535 Post::create(conn, &post_from_blocked_person).unwrap();
538 let person_block = PersonBlockForm {
539 person_id: inserted_person.id,
540 target_id: inserted_blocked_person.id,
543 PersonBlock::block(conn, &person_block).unwrap();
546 let new_post = PostForm {
547 name: "test post 3".to_string(),
548 creator_id: inserted_person.id,
549 community_id: inserted_community.id,
550 language_id: Some(LanguageId(47)),
551 ..PostForm::default()
554 let inserted_post = Post::create(conn, &new_post).unwrap();
556 let new_bot_post = PostForm {
557 name: "test bot post".to_string(),
558 creator_id: inserted_bot.id,
559 community_id: inserted_community.id,
560 ..PostForm::default()
563 let _inserted_bot_post = Post::create(conn, &new_bot_post).unwrap();
568 inserted_blocked_person,
577 fn post_listing_with_person() {
578 let conn = &mut establish_unpooled_connection();
579 let data = init_data(conn);
581 let local_user_form = LocalUserForm {
582 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 = LocalUserForm {
613 show_bot_accounts: Some(true),
616 let inserted_local_user =
617 LocalUser::update(conn, data.inserted_local_user.id, &local_user_form).unwrap();
619 let post_listings_with_bots = PostQuery::builder()
621 .sort(Some(SortType::New))
622 .community_id(Some(data.inserted_community.id))
623 .local_user(Some(&inserted_local_user))
627 // should include bot post which has "undetermined" language
628 assert_eq!(2, post_listings_with_bots.len());
635 fn post_listing_no_person() {
636 let conn = &mut establish_unpooled_connection();
637 let data = init_data(conn);
639 let read_post_listing_multiple_no_person = PostQuery::builder()
641 .sort(Some(SortType::New))
642 .community_id(Some(data.inserted_community.id))
647 let read_post_listing_single_no_person =
648 PostView::read(conn, data.inserted_post.id, None).unwrap();
650 let expected_post_listing_no_person = expected_post_view(&data, conn);
652 // Should be 2 posts, with the bot post, and the blocked
653 assert_eq!(3, read_post_listing_multiple_no_person.len());
656 expected_post_listing_no_person,
657 read_post_listing_multiple_no_person[1]
660 expected_post_listing_no_person,
661 read_post_listing_single_no_person
669 fn post_listing_block_community() {
670 let conn = &mut establish_unpooled_connection();
671 let data = init_data(conn);
673 let community_block = CommunityBlockForm {
674 person_id: data.inserted_person.id,
675 community_id: data.inserted_community.id,
677 CommunityBlock::block(conn, &community_block).unwrap();
679 let read_post_listings_with_person_after_block = PostQuery::builder()
681 .sort(Some(SortType::New))
682 .community_id(Some(data.inserted_community.id))
683 .local_user(Some(&data.inserted_local_user))
687 // Should be 0 posts after the community block
688 assert_eq!(0, read_post_listings_with_person_after_block.len());
690 CommunityBlock::unblock(conn, &community_block).unwrap();
696 fn post_listing_like() {
697 let conn = &mut establish_unpooled_connection();
698 let data = init_data(conn);
700 let post_like_form = PostLikeForm {
701 post_id: data.inserted_post.id,
702 person_id: data.inserted_person.id,
706 let inserted_post_like = PostLike::like(conn, &post_like_form).unwrap();
708 let expected_post_like = PostLike {
709 id: inserted_post_like.id,
710 post_id: data.inserted_post.id,
711 person_id: data.inserted_person.id,
712 published: inserted_post_like.published,
715 assert_eq!(expected_post_like, inserted_post_like);
718 PostLike::remove(conn, data.inserted_person.id, data.inserted_post.id).unwrap();
719 assert_eq!(1, like_removed);
725 fn post_listing_person_language() {
726 let conn = &mut establish_unpooled_connection();
727 let data = init_data(conn);
729 let spanish_id = Language::read_id_from_code(conn, "es").unwrap();
730 let post_spanish = PostForm {
731 name: "asffgdsc".to_string(),
732 creator_id: data.inserted_person.id,
733 community_id: data.inserted_community.id,
734 language_id: Some(spanish_id),
735 ..PostForm::default()
738 Post::create(conn, &post_spanish).unwrap();
740 let post_listings_all = PostQuery::builder()
742 .sort(Some(SortType::New))
743 .local_user(Some(&data.inserted_local_user))
748 // no language filters specified, all posts should be returned
749 assert_eq!(3, post_listings_all.len());
751 let french_id = Language::read_id_from_code(conn, "fr").unwrap();
752 LocalUserLanguage::update(conn, vec![french_id], data.inserted_local_user.id).unwrap();
754 let post_listing_french = PostQuery::builder()
756 .sort(Some(SortType::New))
757 .local_user(Some(&data.inserted_local_user))
762 // only one french language post should be returned
763 assert_eq!(1, post_listing_french.len());
764 assert_eq!(french_id, post_listing_french[0].post.language_id);
766 let undetermined_id = Language::read_id_from_code(conn, "und").unwrap();
767 LocalUserLanguage::update(
769 vec![french_id, undetermined_id],
770 data.inserted_local_user.id,
773 let post_listings_french_und = PostQuery::builder()
775 .sort(Some(SortType::New))
776 .local_user(Some(&data.inserted_local_user))
781 // french post and undetermined language post should be returned
782 assert_eq!(2, post_listings_french_und.len());
785 post_listings_french_und[0].post.language_id
787 assert_eq!(french_id, post_listings_french_und[1].post.language_id);
792 fn cleanup(data: Data, conn: &mut PgConnection) {
793 let num_deleted = Post::delete(conn, data.inserted_post.id).unwrap();
794 Community::delete(conn, data.inserted_community.id).unwrap();
795 Person::delete(conn, data.inserted_person.id).unwrap();
796 Person::delete(conn, data.inserted_bot.id).unwrap();
797 Person::delete(conn, data.inserted_blocked_person.id).unwrap();
798 assert_eq!(1, num_deleted);
801 fn expected_post_view(data: &Data, conn: &mut PgConnection) -> PostView {
802 let (inserted_person, inserted_community, inserted_post) = (
803 &data.inserted_person,
804 &data.inserted_community,
807 let agg = PostAggregates::read(conn, inserted_post.id).unwrap();
811 id: inserted_post.id,
812 name: inserted_post.name.clone(),
813 creator_id: inserted_person.id,
816 published: inserted_post.published,
818 community_id: inserted_community.id,
825 embed_description: None,
826 embed_video_url: None,
828 ap_id: inserted_post.ap_id.to_owned(),
830 language_id: LanguageId(47),
834 creator: PersonSafe {
835 id: inserted_person.id,
836 name: inserted_person.name.clone(),
838 published: inserted_person.published,
840 actor_id: inserted_person.actor_id.to_owned(),
849 inbox_url: inserted_person.inbox_url.to_owned(),
850 shared_inbox_url: None,
851 matrix_user_id: None,
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,
872 counts: PostAggregates {
874 post_id: inserted_post.id,
880 published: agg.published,
881 newest_comment_time_necro: inserted_post.published,
882 newest_comment_time: inserted_post.published,
884 subscribed: SubscribedType::NotSubscribed,
887 creator_blocked: false,