1 use crate::structs::PostView;
2 use diesel::{dsl::*, pg::Pg, result::Error, *};
4 aggregates::structs::PostAggregates,
5 newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
22 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
24 local_user::LocalUser,
25 person::{Person, PersonSafe},
26 person_block::PersonBlock,
27 post::{Post, PostRead, PostSaved},
29 traits::{ToSafe, ViewToVec},
30 utils::{functions::hot_rank, fuzzy_search, limit_and_offset},
35 use typed_builder::TypedBuilder;
37 type PostViewTuple = (
41 Option<CommunityPersonBan>,
43 Option<CommunityFollower>,
55 my_person_id: Option<PersonId>,
56 ) -> Result<Self, Error> {
57 // The left join below will return None in this case
58 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
63 creator_banned_from_community,
73 .inner_join(person::table)
74 .inner_join(community::table)
76 community_person_ban::table.on(
78 .eq(community_person_ban::community_id)
79 .and(community_person_ban::person_id.eq(post::creator_id))
81 community_person_ban::expires
83 .or(community_person_ban::expires.gt(now)),
87 .inner_join(post_aggregates::table)
89 community_follower::table.on(
91 .eq(community_follower::community_id)
92 .and(community_follower::person_id.eq(person_id_join)),
98 .eq(post_saved::post_id)
99 .and(post_saved::person_id.eq(person_id_join)),
105 .eq(post_read::post_id)
106 .and(post_read::person_id.eq(person_id_join)),
110 person_block::table.on(
112 .eq(person_block::target_id)
113 .and(person_block::person_id.eq(person_id_join)),
119 .eq(post_like::post_id)
120 .and(post_like::person_id.eq(person_id_join)),
123 .inner_join(language::table)
126 Person::safe_columns_tuple(),
127 Community::safe_columns_tuple(),
128 community_person_ban::all_columns.nullable(),
129 post_aggregates::all_columns,
130 community_follower::all_columns.nullable(),
131 post_saved::all_columns.nullable(),
132 post_read::all_columns.nullable(),
133 person_block::all_columns.nullable(),
134 post_like::score.nullable(),
135 language::all_columns,
137 .first::<PostViewTuple>(conn)?;
139 // If a person is given, then my_vote, if None, should be 0, not null
140 // Necessary to differentiate between other person's votes
141 let my_vote = if my_person_id.is_some() && post_like.is_none() {
151 creator_banned_from_community: creator_banned_from_community.is_some(),
153 subscribed: CommunityFollower::to_subscribed_type(&follower),
154 saved: saved.is_some(),
155 read: read.is_some(),
156 creator_blocked: creator_blocked.is_some(),
163 #[derive(TypedBuilder)]
164 #[builder(field_defaults(default))]
165 pub struct PostQuery<'a> {
167 conn: &'a PgConnection,
168 listing_type: Option<ListingType>,
169 sort: Option<SortType>,
170 creator_id: Option<PersonId>,
171 community_id: Option<CommunityId>,
172 community_actor_id: Option<DbUrl>,
173 local_user: Option<&'a LocalUser>,
174 search_term: Option<String>,
175 url_search: Option<String>,
176 saved_only: Option<bool>,
181 impl<'a> PostQuery<'a> {
182 pub fn list(self) -> Result<Vec<PostView>, Error> {
185 // The left join below will return None in this case
186 let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1));
187 let local_user_id_join = self.local_user.map(|l| l.id).unwrap_or(LocalUserId(-1));
189 let mut query = post::table
190 .inner_join(person::table)
191 .inner_join(community::table)
193 community_person_ban::table.on(
195 .eq(community_person_ban::community_id)
196 .and(community_person_ban::person_id.eq(post::creator_id))
198 community_person_ban::expires
200 .or(community_person_ban::expires.gt(now)),
204 .inner_join(post_aggregates::table)
206 community_follower::table.on(
208 .eq(community_follower::community_id)
209 .and(community_follower::person_id.eq(person_id_join)),
213 post_saved::table.on(
215 .eq(post_saved::post_id)
216 .and(post_saved::person_id.eq(person_id_join)),
222 .eq(post_read::post_id)
223 .and(post_read::person_id.eq(person_id_join)),
227 person_block::table.on(
229 .eq(person_block::target_id)
230 .and(person_block::person_id.eq(person_id_join)),
234 community_block::table.on(
236 .eq(community_block::community_id)
237 .and(community_block::person_id.eq(person_id_join)),
243 .eq(post_like::post_id)
244 .and(post_like::person_id.eq(person_id_join)),
247 .inner_join(language::table)
249 local_user_language::table.on(
251 .eq(local_user_language::language_id)
252 .and(local_user_language::local_user_id.eq(local_user_id_join)),
257 Person::safe_columns_tuple(),
258 Community::safe_columns_tuple(),
259 community_person_ban::all_columns.nullable(),
260 post_aggregates::all_columns,
261 community_follower::all_columns.nullable(),
262 post_saved::all_columns.nullable(),
263 post_read::all_columns.nullable(),
264 person_block::all_columns.nullable(),
265 post_like::score.nullable(),
266 language::all_columns,
270 if let Some(listing_type) = self.listing_type {
272 ListingType::Subscribed => {
273 query = query.filter(community_follower::person_id.is_not_null())
275 ListingType::Local => {
276 query = query.filter(community::local.eq(true)).filter(
279 .or(community_follower::person_id.eq(person_id_join)),
282 ListingType::All => {
283 query = query.filter(
286 .or(community_follower::person_id.eq(person_id_join)),
292 if let Some(community_id) = self.community_id {
294 .filter(post::community_id.eq(community_id))
295 .then_order_by(post_aggregates::stickied.desc());
298 if let Some(community_actor_id) = self.community_actor_id {
300 .filter(community::actor_id.eq(community_actor_id))
301 .then_order_by(post_aggregates::stickied.desc());
304 if let Some(url_search) = self.url_search {
305 query = query.filter(post::url.eq(url_search));
308 if let Some(search_term) = self.search_term {
309 let searcher = fuzzy_search(&search_term);
310 query = query.filter(
312 .ilike(searcher.to_owned())
313 .or(post::body.ilike(searcher)),
317 // If its for a specific person, show the removed / deleted
318 if let Some(creator_id) = self.creator_id {
319 query = query.filter(post::creator_id.eq(creator_id));
322 if !self.local_user.map(|l| l.show_nsfw).unwrap_or(false) {
324 .filter(post::nsfw.eq(false))
325 .filter(community::nsfw.eq(false));
328 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
329 query = query.filter(person::bot_account.eq(false));
332 if self.saved_only.unwrap_or(false) {
333 query = query.filter(post_saved::id.is_not_null());
335 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
336 // setting wont be able to see saved posts.
337 else if !self.local_user.map(|l| l.show_read_posts).unwrap_or(true) {
338 query = query.filter(post_read::id.is_null());
341 if self.local_user.is_some() {
342 // Filter out the rows with missing languages
343 query = query.filter(local_user_language::id.is_not_null());
345 // Don't show blocked communities or persons
346 query = query.filter(community_block::person_id.is_null());
347 query = query.filter(person_block::person_id.is_null());
350 query = match self.sort.unwrap_or(SortType::Hot) {
351 SortType::Active => query
354 post_aggregates::score,
355 post_aggregates::newest_comment_time_necro,
359 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
360 SortType::Hot => query
361 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
362 .then_order_by(post_aggregates::published.desc()),
363 SortType::New => query.then_order_by(post_aggregates::published.desc()),
364 SortType::Old => query.then_order_by(post_aggregates::published.asc()),
365 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
366 SortType::MostComments => query
367 .then_order_by(post_aggregates::comments.desc())
368 .then_order_by(post_aggregates::published.desc()),
369 SortType::TopAll => query
370 .then_order_by(post_aggregates::score.desc())
371 .then_order_by(post_aggregates::published.desc()),
372 SortType::TopYear => query
373 .filter(post_aggregates::published.gt(now - 1.years()))
374 .then_order_by(post_aggregates::score.desc())
375 .then_order_by(post_aggregates::published.desc()),
376 SortType::TopMonth => query
377 .filter(post_aggregates::published.gt(now - 1.months()))
378 .then_order_by(post_aggregates::score.desc())
379 .then_order_by(post_aggregates::published.desc()),
380 SortType::TopWeek => query
381 .filter(post_aggregates::published.gt(now - 1.weeks()))
382 .then_order_by(post_aggregates::score.desc())
383 .then_order_by(post_aggregates::published.desc()),
384 SortType::TopDay => query
385 .filter(post_aggregates::published.gt(now - 1.days()))
386 .then_order_by(post_aggregates::score.desc())
387 .then_order_by(post_aggregates::published.desc()),
390 let (limit, offset) = limit_and_offset(self.page, self.limit)?;
395 .filter(post::removed.eq(false))
396 .filter(post::deleted.eq(false))
397 .filter(community::removed.eq(false))
398 .filter(community::deleted.eq(false));
400 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
402 let res = query.load::<PostViewTuple>(self.conn)?;
404 Ok(PostView::from_tuple_to_vec(res))
408 impl ViewToVec for PostView {
409 type DbTuple = PostViewTuple;
410 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
417 creator_banned_from_community: a.3.is_some(),
419 subscribed: CommunityFollower::to_subscribed_type(&a.5),
420 saved: a.6.is_some(),
422 creator_blocked: a.8.is_some(),
426 .collect::<Vec<Self>>()
432 use crate::post_view::{PostQuery, PostView};
433 use diesel::PgConnection;
434 use lemmy_db_schema::{
435 aggregates::structs::PostAggregates,
436 newtypes::LanguageId,
439 community_block::{CommunityBlock, CommunityBlockForm},
441 local_user::{LocalUser, LocalUserForm},
442 local_user_language::LocalUserLanguage,
444 person_block::{PersonBlock, PersonBlockForm},
447 traits::{Blockable, Crud, Likeable},
448 utils::establish_unpooled_connection,
452 use serial_test::serial;
455 inserted_person: Person,
456 inserted_local_user: LocalUser,
457 inserted_blocked_person: Person,
458 inserted_bot: Person,
459 inserted_community: Community,
463 fn init_data(conn: &PgConnection) -> Data {
464 let person_name = "tegan".to_string();
466 let new_person = PersonForm {
467 name: person_name.to_owned(),
468 public_key: Some("pubkey".to_string()),
469 ..PersonForm::default()
472 let inserted_person = Person::create(conn, &new_person).unwrap();
474 let local_user_form = LocalUserForm {
475 person_id: Some(inserted_person.id),
476 password_encrypted: Some("".to_string()),
479 let inserted_local_user = LocalUser::create(conn, &local_user_form).unwrap();
480 // update user languages to all
481 LocalUserLanguage::update_user_languages(conn, None, inserted_local_user.id).unwrap();
483 let new_bot = PersonForm {
484 name: "mybot".to_string(),
485 bot_account: Some(true),
486 public_key: Some("pubkey".to_string()),
487 ..PersonForm::default()
490 let inserted_bot = Person::create(conn, &new_bot).unwrap();
492 let new_community = CommunityForm {
493 name: "test_community_3".to_string(),
494 title: "nada".to_owned(),
495 public_key: Some("pubkey".to_string()),
496 ..CommunityForm::default()
499 let inserted_community = Community::create(conn, &new_community).unwrap();
501 // Test a person block, make sure the post query doesn't include their post
502 let blocked_person = PersonForm {
504 public_key: Some("pubkey".to_string()),
505 ..PersonForm::default()
508 let inserted_blocked_person = Person::create(conn, &blocked_person).unwrap();
510 let post_from_blocked_person = PostForm {
511 name: "blocked_person_post".to_string(),
512 creator_id: inserted_blocked_person.id,
513 community_id: inserted_community.id,
514 language_id: Some(LanguageId(1)),
515 ..PostForm::default()
518 Post::create(conn, &post_from_blocked_person).unwrap();
521 let person_block = PersonBlockForm {
522 person_id: inserted_person.id,
523 target_id: inserted_blocked_person.id,
526 PersonBlock::block(conn, &person_block).unwrap();
529 let new_post = PostForm {
530 name: "test post 3".to_string(),
531 creator_id: inserted_person.id,
532 community_id: inserted_community.id,
533 language_id: Some(LanguageId(47)),
534 ..PostForm::default()
537 let inserted_post = Post::create(conn, &new_post).unwrap();
539 let new_bot_post = PostForm {
540 name: "test bot post".to_string(),
541 creator_id: inserted_bot.id,
542 community_id: inserted_community.id,
543 ..PostForm::default()
546 let _inserted_bot_post = Post::create(conn, &new_bot_post).unwrap();
551 inserted_blocked_person,
560 fn post_listing_with_person() {
561 let conn = establish_unpooled_connection();
562 let data = init_data(&conn);
564 let local_user_form = LocalUserForm {
565 show_bot_accounts: Some(false),
568 let inserted_local_user =
569 LocalUser::update(&conn, data.inserted_local_user.id, &local_user_form).unwrap();
571 let read_post_listing = PostQuery::builder()
573 .sort(Some(SortType::New))
574 .community_id(Some(data.inserted_community.id))
575 .local_user(Some(&inserted_local_user))
580 let post_listing_single_with_person =
581 PostView::read(&conn, data.inserted_post.id, Some(data.inserted_person.id)).unwrap();
583 let mut expected_post_listing_with_user = expected_post_view(&data, &conn);
585 // Should be only one person, IE the bot post, and blocked should be missing
586 assert_eq!(1, read_post_listing.len());
588 assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
589 expected_post_listing_with_user.my_vote = Some(0);
591 expected_post_listing_with_user,
592 post_listing_single_with_person
595 let local_user_form = LocalUserForm {
596 show_bot_accounts: Some(true),
599 let inserted_local_user =
600 LocalUser::update(&conn, data.inserted_local_user.id, &local_user_form).unwrap();
602 let post_listings_with_bots = PostQuery::builder()
604 .sort(Some(SortType::New))
605 .community_id(Some(data.inserted_community.id))
606 .local_user(Some(&inserted_local_user))
610 // should include bot post which has "undetermined" language
611 assert_eq!(2, post_listings_with_bots.len());
613 cleanup(data, &conn);
618 fn post_listing_no_person() {
619 let conn = establish_unpooled_connection();
620 let data = init_data(&conn);
622 let read_post_listing_multiple_no_person = PostQuery::builder()
624 .sort(Some(SortType::New))
625 .community_id(Some(data.inserted_community.id))
630 let read_post_listing_single_no_person =
631 PostView::read(&conn, data.inserted_post.id, None).unwrap();
633 let expected_post_listing_no_person = expected_post_view(&data, &conn);
635 // Should be 2 posts, with the bot post, and the blocked
636 assert_eq!(3, read_post_listing_multiple_no_person.len());
639 expected_post_listing_no_person,
640 read_post_listing_multiple_no_person[1]
643 expected_post_listing_no_person,
644 read_post_listing_single_no_person
647 cleanup(data, &conn);
652 fn post_listing_block_community() {
653 let conn = establish_unpooled_connection();
654 let data = init_data(&conn);
656 let community_block = CommunityBlockForm {
657 person_id: data.inserted_person.id,
658 community_id: data.inserted_community.id,
660 CommunityBlock::block(&conn, &community_block).unwrap();
662 let read_post_listings_with_person_after_block = PostQuery::builder()
664 .sort(Some(SortType::New))
665 .community_id(Some(data.inserted_community.id))
666 .local_user(Some(&data.inserted_local_user))
670 // Should be 0 posts after the community block
671 assert_eq!(0, read_post_listings_with_person_after_block.len());
673 CommunityBlock::unblock(&conn, &community_block).unwrap();
674 cleanup(data, &conn);
679 fn post_listing_like() {
680 let conn = establish_unpooled_connection();
681 let data = init_data(&conn);
683 let post_like_form = PostLikeForm {
684 post_id: data.inserted_post.id,
685 person_id: data.inserted_person.id,
689 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
691 let expected_post_like = PostLike {
692 id: inserted_post_like.id,
693 post_id: data.inserted_post.id,
694 person_id: data.inserted_person.id,
695 published: inserted_post_like.published,
698 assert_eq!(expected_post_like, inserted_post_like);
701 PostLike::remove(&conn, data.inserted_person.id, data.inserted_post.id).unwrap();
702 assert_eq!(1, like_removed);
703 cleanup(data, &conn);
708 fn post_listing_person_language() {
709 let conn = establish_unpooled_connection();
710 let data = init_data(&conn);
712 let spanish_id = Language::read_id_from_code(&conn, "es").unwrap();
713 let post_spanish = PostForm {
714 name: "asffgdsc".to_string(),
715 creator_id: data.inserted_person.id,
716 community_id: data.inserted_community.id,
717 language_id: Some(spanish_id),
718 ..PostForm::default()
721 Post::create(&conn, &post_spanish).unwrap();
723 let post_listings_all = PostQuery::builder()
725 .sort(Some(SortType::New))
726 .local_user(Some(&data.inserted_local_user))
731 // no language filters specified, all posts should be returned
732 assert_eq!(3, post_listings_all.len());
734 let french_id = Language::read_id_from_code(&conn, "fr").unwrap();
735 LocalUserLanguage::update_user_languages(
737 Some(vec![french_id]),
738 data.inserted_local_user.id,
742 let post_listing_french = PostQuery::builder()
744 .sort(Some(SortType::New))
745 .local_user(Some(&data.inserted_local_user))
750 // only one french language post should be returned
751 assert_eq!(1, post_listing_french.len());
752 assert_eq!(french_id, post_listing_french[0].post.language_id);
754 let undetermined_id = Language::read_id_from_code(&conn, "und").unwrap();
755 LocalUserLanguage::update_user_languages(
757 Some(vec![french_id, undetermined_id]),
758 data.inserted_local_user.id,
761 let post_listings_french_und = PostQuery::builder()
763 .sort(Some(SortType::New))
764 .local_user(Some(&data.inserted_local_user))
769 // french post and undetermined language post should be returned
770 assert_eq!(2, post_listings_french_und.len());
773 post_listings_french_und[0].post.language_id
775 assert_eq!(french_id, post_listings_french_und[1].post.language_id);
777 cleanup(data, &conn);
780 fn cleanup(data: Data, conn: &PgConnection) {
781 let num_deleted = Post::delete(conn, data.inserted_post.id).unwrap();
782 Community::delete(conn, data.inserted_community.id).unwrap();
783 Person::delete(conn, data.inserted_person.id).unwrap();
784 Person::delete(conn, data.inserted_bot.id).unwrap();
785 Person::delete(conn, data.inserted_blocked_person.id).unwrap();
786 assert_eq!(1, num_deleted);
789 fn expected_post_view(data: &Data, conn: &PgConnection) -> PostView {
790 let (inserted_person, inserted_community, inserted_post) = (
791 &data.inserted_person,
792 &data.inserted_community,
795 let agg = PostAggregates::read(conn, inserted_post.id).unwrap();
799 id: inserted_post.id,
800 name: inserted_post.name.clone(),
801 creator_id: inserted_person.id,
804 published: inserted_post.published,
806 community_id: inserted_community.id,
813 embed_description: None,
814 embed_video_url: None,
816 ap_id: inserted_post.ap_id.to_owned(),
818 language_id: LanguageId(47),
821 creator: PersonSafe {
822 id: inserted_person.id,
823 name: inserted_person.name.clone(),
825 published: inserted_person.published,
827 actor_id: inserted_person.actor_id.to_owned(),
836 inbox_url: inserted_person.inbox_url.to_owned(),
837 shared_inbox_url: None,
838 matrix_user_id: None,
841 creator_banned_from_community: false,
842 community: CommunitySafe {
843 id: inserted_community.id,
844 name: inserted_community.name.clone(),
849 actor_id: inserted_community.actor_id.to_owned(),
851 title: "nada".to_owned(),
856 posting_restricted_to_mods: false,
857 published: inserted_community.published,
859 counts: PostAggregates {
861 post_id: inserted_post.id,
867 published: agg.published,
868 newest_comment_time_necro: inserted_post.published,
869 newest_comment_time: inserted_post.published,
871 subscribed: SubscribedType::NotSubscribed,
874 creator_blocked: false,
877 code: "fr".to_string(),
878 name: "Français".to_string(),