1 use crate::structs::PostView;
2 use diesel::{dsl::*, pg::Pg, result::Error, *};
4 aggregates::structs::PostAggregates,
5 newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
21 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
22 local_user::LocalUser,
23 person::{Person, PersonSafe},
24 person_block::PersonBlock,
25 post::{Post, PostRead, PostSaved},
27 traits::{ToSafe, ViewToVec},
28 utils::{functions::hot_rank, fuzzy_search, limit_and_offset},
33 use typed_builder::TypedBuilder;
35 type PostViewTuple = (
39 Option<CommunityPersonBan>,
41 Option<CommunityFollower>,
50 conn: &mut PgConnection,
52 my_person_id: Option<PersonId>,
53 ) -> Result<Self, Error> {
54 // The left join below will return None in this case
55 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
60 creator_banned_from_community,
69 .inner_join(person::table)
70 .inner_join(community::table)
72 community_person_ban::table.on(
74 .eq(community_person_ban::community_id)
75 .and(community_person_ban::person_id.eq(post::creator_id))
77 community_person_ban::expires
79 .or(community_person_ban::expires.gt(now)),
83 .inner_join(post_aggregates::table)
85 community_follower::table.on(
87 .eq(community_follower::community_id)
88 .and(community_follower::person_id.eq(person_id_join)),
94 .eq(post_saved::post_id)
95 .and(post_saved::person_id.eq(person_id_join)),
101 .eq(post_read::post_id)
102 .and(post_read::person_id.eq(person_id_join)),
106 person_block::table.on(
108 .eq(person_block::target_id)
109 .and(person_block::person_id.eq(person_id_join)),
115 .eq(post_like::post_id)
116 .and(post_like::person_id.eq(person_id_join)),
121 Person::safe_columns_tuple(),
122 Community::safe_columns_tuple(),
123 community_person_ban::all_columns.nullable(),
124 post_aggregates::all_columns,
125 community_follower::all_columns.nullable(),
126 post_saved::all_columns.nullable(),
127 post_read::all_columns.nullable(),
128 person_block::all_columns.nullable(),
129 post_like::score.nullable(),
131 .first::<PostViewTuple>(conn)?;
133 // If a person is given, then my_vote, if None, should be 0, not null
134 // Necessary to differentiate between other person's votes
135 let my_vote = if my_person_id.is_some() && post_like.is_none() {
145 creator_banned_from_community: creator_banned_from_community.is_some(),
147 subscribed: CommunityFollower::to_subscribed_type(&follower),
148 saved: saved.is_some(),
149 read: read.is_some(),
150 creator_blocked: creator_blocked.is_some(),
156 #[derive(TypedBuilder)]
157 #[builder(field_defaults(default))]
158 pub struct PostQuery<'a> {
160 conn: &'a mut PgConnection,
161 listing_type: Option<ListingType>,
162 sort: Option<SortType>,
163 creator_id: Option<PersonId>,
164 community_id: Option<CommunityId>,
165 community_actor_id: Option<DbUrl>,
166 local_user: Option<&'a LocalUser>,
167 search_term: Option<String>,
168 url_search: Option<String>,
169 saved_only: Option<bool>,
174 impl<'a> PostQuery<'a> {
175 pub fn list(self) -> Result<Vec<PostView>, Error> {
178 // The left join below will return None in this case
179 let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1));
180 let local_user_id_join = self.local_user.map(|l| l.id).unwrap_or(LocalUserId(-1));
182 let mut query = post::table
183 .inner_join(person::table)
184 .inner_join(community::table)
186 community_person_ban::table.on(
188 .eq(community_person_ban::community_id)
189 .and(community_person_ban::person_id.eq(post::creator_id))
191 community_person_ban::expires
193 .or(community_person_ban::expires.gt(now)),
197 .inner_join(post_aggregates::table)
199 community_follower::table.on(
201 .eq(community_follower::community_id)
202 .and(community_follower::person_id.eq(person_id_join)),
206 post_saved::table.on(
208 .eq(post_saved::post_id)
209 .and(post_saved::person_id.eq(person_id_join)),
215 .eq(post_read::post_id)
216 .and(post_read::person_id.eq(person_id_join)),
220 person_block::table.on(
222 .eq(person_block::target_id)
223 .and(person_block::person_id.eq(person_id_join)),
227 community_block::table.on(
229 .eq(community_block::community_id)
230 .and(community_block::person_id.eq(person_id_join)),
236 .eq(post_like::post_id)
237 .and(post_like::person_id.eq(person_id_join)),
241 local_user_language::table.on(
243 .eq(local_user_language::language_id)
244 .and(local_user_language::local_user_id.eq(local_user_id_join)),
249 Person::safe_columns_tuple(),
250 Community::safe_columns_tuple(),
251 community_person_ban::all_columns.nullable(),
252 post_aggregates::all_columns,
253 community_follower::all_columns.nullable(),
254 post_saved::all_columns.nullable(),
255 post_read::all_columns.nullable(),
256 person_block::all_columns.nullable(),
257 post_like::score.nullable(),
261 if let Some(listing_type) = self.listing_type {
263 ListingType::Subscribed => {
264 query = query.filter(community_follower::person_id.is_not_null())
266 ListingType::Local => {
267 query = query.filter(community::local.eq(true)).filter(
270 .or(community_follower::person_id.eq(person_id_join)),
273 ListingType::All => {
274 query = query.filter(
277 .or(community_follower::person_id.eq(person_id_join)),
283 if let Some(community_id) = self.community_id {
285 .filter(post::community_id.eq(community_id))
286 .then_order_by(post_aggregates::stickied.desc());
289 if let Some(community_actor_id) = self.community_actor_id {
291 .filter(community::actor_id.eq(community_actor_id))
292 .then_order_by(post_aggregates::stickied.desc());
295 if let Some(url_search) = self.url_search {
296 query = query.filter(post::url.eq(url_search));
299 if let Some(search_term) = self.search_term {
300 let searcher = fuzzy_search(&search_term);
301 query = query.filter(
303 .ilike(searcher.to_owned())
304 .or(post::body.ilike(searcher)),
308 // If its for a specific person, show the removed / deleted
309 if let Some(creator_id) = self.creator_id {
310 query = query.filter(post::creator_id.eq(creator_id));
313 if !self.local_user.map(|l| l.show_nsfw).unwrap_or(false) {
315 .filter(post::nsfw.eq(false))
316 .filter(community::nsfw.eq(false));
319 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
320 query = query.filter(person::bot_account.eq(false));
323 if self.saved_only.unwrap_or(false) {
324 query = query.filter(post_saved::id.is_not_null());
326 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
327 // setting wont be able to see saved posts.
328 else if !self.local_user.map(|l| l.show_read_posts).unwrap_or(true) {
329 query = query.filter(post_read::id.is_null());
332 if self.local_user.is_some() {
333 // Filter out the rows with missing languages
334 query = query.filter(local_user_language::id.is_not_null());
336 // Don't show blocked communities or persons
337 query = query.filter(community_block::person_id.is_null());
338 query = query.filter(person_block::person_id.is_null());
341 query = match self.sort.unwrap_or(SortType::Hot) {
342 SortType::Active => query
345 post_aggregates::score,
346 post_aggregates::newest_comment_time_necro,
350 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
351 SortType::Hot => query
352 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
353 .then_order_by(post_aggregates::published.desc()),
354 SortType::New => query.then_order_by(post_aggregates::published.desc()),
355 SortType::Old => query.then_order_by(post_aggregates::published.asc()),
356 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
357 SortType::MostComments => query
358 .then_order_by(post_aggregates::comments.desc())
359 .then_order_by(post_aggregates::published.desc()),
360 SortType::TopAll => query
361 .then_order_by(post_aggregates::score.desc())
362 .then_order_by(post_aggregates::published.desc()),
363 SortType::TopYear => query
364 .filter(post_aggregates::published.gt(now - 1.years()))
365 .then_order_by(post_aggregates::score.desc())
366 .then_order_by(post_aggregates::published.desc()),
367 SortType::TopMonth => query
368 .filter(post_aggregates::published.gt(now - 1.months()))
369 .then_order_by(post_aggregates::score.desc())
370 .then_order_by(post_aggregates::published.desc()),
371 SortType::TopWeek => query
372 .filter(post_aggregates::published.gt(now - 1.weeks()))
373 .then_order_by(post_aggregates::score.desc())
374 .then_order_by(post_aggregates::published.desc()),
375 SortType::TopDay => query
376 .filter(post_aggregates::published.gt(now - 1.days()))
377 .then_order_by(post_aggregates::score.desc())
378 .then_order_by(post_aggregates::published.desc()),
381 let (limit, offset) = limit_and_offset(self.page, self.limit)?;
386 .filter(post::removed.eq(false))
387 .filter(post::deleted.eq(false))
388 .filter(community::removed.eq(false))
389 .filter(community::deleted.eq(false));
391 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
393 let res = query.load::<PostViewTuple>(self.conn)?;
395 Ok(PostView::from_tuple_to_vec(res))
399 impl ViewToVec for PostView {
400 type DbTuple = PostViewTuple;
401 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
408 creator_banned_from_community: a.3.is_some(),
410 subscribed: CommunityFollower::to_subscribed_type(&a.5),
411 saved: a.6.is_some(),
413 creator_blocked: a.8.is_some(),
416 .collect::<Vec<Self>>()
422 use crate::post_view::{PostQuery, PostView};
423 use diesel::PgConnection;
424 use lemmy_db_schema::{
425 aggregates::structs::PostAggregates,
426 newtypes::LanguageId,
429 community_block::{CommunityBlock, CommunityBlockForm},
431 local_user::{LocalUser, LocalUserForm},
432 local_user_language::LocalUserLanguage,
434 person_block::{PersonBlock, PersonBlockForm},
437 traits::{Blockable, Crud, Likeable},
438 utils::establish_unpooled_connection,
442 use serial_test::serial;
445 inserted_person: Person,
446 inserted_local_user: LocalUser,
447 inserted_blocked_person: Person,
448 inserted_bot: Person,
449 inserted_community: Community,
453 fn init_data(conn: &mut PgConnection) -> Data {
454 let person_name = "tegan".to_string();
456 let new_person = PersonForm {
457 name: person_name.to_owned(),
458 public_key: Some("pubkey".to_string()),
459 ..PersonForm::default()
462 let inserted_person = Person::create(conn, &new_person).unwrap();
464 let local_user_form = LocalUserForm {
465 person_id: Some(inserted_person.id),
466 password_encrypted: Some("".to_string()),
469 let inserted_local_user = LocalUser::create(conn, &local_user_form).unwrap();
471 let new_bot = PersonForm {
472 name: "mybot".to_string(),
473 bot_account: Some(true),
474 public_key: Some("pubkey".to_string()),
475 ..PersonForm::default()
478 let inserted_bot = Person::create(conn, &new_bot).unwrap();
480 let new_community = CommunityForm {
481 name: "test_community_3".to_string(),
482 title: "nada".to_owned(),
483 public_key: Some("pubkey".to_string()),
484 ..CommunityForm::default()
487 let inserted_community = Community::create(conn, &new_community).unwrap();
489 // Test a person block, make sure the post query doesn't include their post
490 let blocked_person = PersonForm {
492 public_key: Some("pubkey".to_string()),
493 ..PersonForm::default()
496 let inserted_blocked_person = Person::create(conn, &blocked_person).unwrap();
498 let post_from_blocked_person = PostForm {
499 name: "blocked_person_post".to_string(),
500 creator_id: inserted_blocked_person.id,
501 community_id: inserted_community.id,
502 language_id: Some(LanguageId(1)),
503 ..PostForm::default()
506 Post::create(conn, &post_from_blocked_person).unwrap();
509 let person_block = PersonBlockForm {
510 person_id: inserted_person.id,
511 target_id: inserted_blocked_person.id,
514 PersonBlock::block(conn, &person_block).unwrap();
517 let new_post = PostForm {
518 name: "test post 3".to_string(),
519 creator_id: inserted_person.id,
520 community_id: inserted_community.id,
521 language_id: Some(LanguageId(47)),
522 ..PostForm::default()
525 let inserted_post = Post::create(conn, &new_post).unwrap();
527 let new_bot_post = PostForm {
528 name: "test bot post".to_string(),
529 creator_id: inserted_bot.id,
530 community_id: inserted_community.id,
531 ..PostForm::default()
534 let _inserted_bot_post = Post::create(conn, &new_bot_post).unwrap();
539 inserted_blocked_person,
548 fn post_listing_with_person() {
549 let conn = &mut establish_unpooled_connection();
550 let data = init_data(conn);
552 let local_user_form = LocalUserForm {
553 show_bot_accounts: Some(false),
556 let inserted_local_user =
557 LocalUser::update(conn, data.inserted_local_user.id, &local_user_form).unwrap();
559 let read_post_listing = PostQuery::builder()
561 .sort(Some(SortType::New))
562 .community_id(Some(data.inserted_community.id))
563 .local_user(Some(&inserted_local_user))
568 let post_listing_single_with_person =
569 PostView::read(conn, data.inserted_post.id, Some(data.inserted_person.id)).unwrap();
571 let mut expected_post_listing_with_user = expected_post_view(&data, conn);
573 // Should be only one person, IE the bot post, and blocked should be missing
574 assert_eq!(1, read_post_listing.len());
576 assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
577 expected_post_listing_with_user.my_vote = Some(0);
579 expected_post_listing_with_user,
580 post_listing_single_with_person
583 let local_user_form = LocalUserForm {
584 show_bot_accounts: Some(true),
587 let inserted_local_user =
588 LocalUser::update(conn, data.inserted_local_user.id, &local_user_form).unwrap();
590 let post_listings_with_bots = PostQuery::builder()
592 .sort(Some(SortType::New))
593 .community_id(Some(data.inserted_community.id))
594 .local_user(Some(&inserted_local_user))
598 // should include bot post which has "undetermined" language
599 assert_eq!(2, post_listings_with_bots.len());
606 fn post_listing_no_person() {
607 let conn = &mut establish_unpooled_connection();
608 let data = init_data(conn);
610 let read_post_listing_multiple_no_person = PostQuery::builder()
612 .sort(Some(SortType::New))
613 .community_id(Some(data.inserted_community.id))
618 let read_post_listing_single_no_person =
619 PostView::read(conn, data.inserted_post.id, None).unwrap();
621 let expected_post_listing_no_person = expected_post_view(&data, conn);
623 // Should be 2 posts, with the bot post, and the blocked
624 assert_eq!(3, read_post_listing_multiple_no_person.len());
627 expected_post_listing_no_person,
628 read_post_listing_multiple_no_person[1]
631 expected_post_listing_no_person,
632 read_post_listing_single_no_person
640 fn post_listing_block_community() {
641 let conn = &mut establish_unpooled_connection();
642 let data = init_data(conn);
644 let community_block = CommunityBlockForm {
645 person_id: data.inserted_person.id,
646 community_id: data.inserted_community.id,
648 CommunityBlock::block(conn, &community_block).unwrap();
650 let read_post_listings_with_person_after_block = PostQuery::builder()
652 .sort(Some(SortType::New))
653 .community_id(Some(data.inserted_community.id))
654 .local_user(Some(&data.inserted_local_user))
658 // Should be 0 posts after the community block
659 assert_eq!(0, read_post_listings_with_person_after_block.len());
661 CommunityBlock::unblock(conn, &community_block).unwrap();
667 fn post_listing_like() {
668 let conn = &mut establish_unpooled_connection();
669 let data = init_data(conn);
671 let post_like_form = PostLikeForm {
672 post_id: data.inserted_post.id,
673 person_id: data.inserted_person.id,
677 let inserted_post_like = PostLike::like(conn, &post_like_form).unwrap();
679 let expected_post_like = PostLike {
680 id: inserted_post_like.id,
681 post_id: data.inserted_post.id,
682 person_id: data.inserted_person.id,
683 published: inserted_post_like.published,
686 assert_eq!(expected_post_like, inserted_post_like);
689 PostLike::remove(conn, data.inserted_person.id, data.inserted_post.id).unwrap();
690 assert_eq!(1, like_removed);
696 fn post_listing_person_language() {
697 let conn = &mut establish_unpooled_connection();
698 let data = init_data(conn);
700 let spanish_id = Language::read_id_from_code(conn, "es").unwrap();
701 let post_spanish = PostForm {
702 name: "asffgdsc".to_string(),
703 creator_id: data.inserted_person.id,
704 community_id: data.inserted_community.id,
705 language_id: Some(spanish_id),
706 ..PostForm::default()
709 Post::create(conn, &post_spanish).unwrap();
711 let post_listings_all = PostQuery::builder()
713 .sort(Some(SortType::New))
714 .local_user(Some(&data.inserted_local_user))
719 // no language filters specified, all posts should be returned
720 assert_eq!(3, post_listings_all.len());
722 let french_id = Language::read_id_from_code(conn, "fr").unwrap();
723 LocalUserLanguage::update_user_languages(
725 Some(vec![french_id]),
726 data.inserted_local_user.id,
730 let post_listing_french = PostQuery::builder()
732 .sort(Some(SortType::New))
733 .local_user(Some(&data.inserted_local_user))
738 // only one french language post should be returned
739 assert_eq!(1, post_listing_french.len());
740 assert_eq!(french_id, post_listing_french[0].post.language_id);
742 let undetermined_id = Language::read_id_from_code(conn, "und").unwrap();
743 LocalUserLanguage::update_user_languages(
745 Some(vec![french_id, undetermined_id]),
746 data.inserted_local_user.id,
749 let post_listings_french_und = PostQuery::builder()
751 .sort(Some(SortType::New))
752 .local_user(Some(&data.inserted_local_user))
757 // french post and undetermined language post should be returned
758 assert_eq!(2, post_listings_french_und.len());
761 post_listings_french_und[0].post.language_id
763 assert_eq!(french_id, post_listings_french_und[1].post.language_id);
768 fn cleanup(data: Data, conn: &mut PgConnection) {
769 let num_deleted = Post::delete(conn, data.inserted_post.id).unwrap();
770 Community::delete(conn, data.inserted_community.id).unwrap();
771 Person::delete(conn, data.inserted_person.id).unwrap();
772 Person::delete(conn, data.inserted_bot.id).unwrap();
773 Person::delete(conn, data.inserted_blocked_person.id).unwrap();
774 assert_eq!(1, num_deleted);
777 fn expected_post_view(data: &Data, conn: &mut PgConnection) -> PostView {
778 let (inserted_person, inserted_community, inserted_post) = (
779 &data.inserted_person,
780 &data.inserted_community,
783 let agg = PostAggregates::read(conn, inserted_post.id).unwrap();
787 id: inserted_post.id,
788 name: inserted_post.name.clone(),
789 creator_id: inserted_person.id,
792 published: inserted_post.published,
794 community_id: inserted_community.id,
801 embed_description: None,
802 embed_video_url: None,
804 ap_id: inserted_post.ap_id.to_owned(),
806 language_id: LanguageId(47),
809 creator: PersonSafe {
810 id: inserted_person.id,
811 name: inserted_person.name.clone(),
813 published: inserted_person.published,
815 actor_id: inserted_person.actor_id.to_owned(),
824 inbox_url: inserted_person.inbox_url.to_owned(),
825 shared_inbox_url: None,
826 matrix_user_id: None,
829 creator_banned_from_community: false,
830 community: CommunitySafe {
831 id: inserted_community.id,
832 name: inserted_community.name.clone(),
837 actor_id: inserted_community.actor_id.to_owned(),
839 title: "nada".to_owned(),
844 posting_restricted_to_mods: false,
845 published: inserted_community.published,
847 counts: PostAggregates {
849 post_id: inserted_post.id,
855 published: agg.published,
856 newest_comment_time_necro: inserted_post.published,
857 newest_comment_time: inserted_post.published,
859 subscribed: SubscribedType::NotSubscribed,
862 creator_blocked: false,