1 use crate::structs::PostView;
5 result::{Error, Error::QueryBuilderError},
9 aggregates::structs::PostAggregates,
10 newtypes::{CommunityId, DbUrl, PersonId, PostId},
25 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
26 person::{Person, PersonSafe},
27 person_block::PersonBlock,
28 post::{Post, PostRead, PostSaved},
30 traits::{MaybeOptional, ToSafe, ViewToVec},
31 utils::{functions::hot_rank, fuzzy_search, limit_and_offset},
37 type PostViewTuple = (
41 Option<CommunityPersonBan>,
43 Option<CommunityFollower>,
54 my_person_id: Option<PersonId>,
55 ) -> Result<Self, Error> {
56 // The left join below will return None in this case
57 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
63 creator_banned_from_community,
72 .inner_join(person::table)
73 .inner_join(community::table)
75 community_person_ban::table.on(
77 .eq(community_person_ban::community_id)
78 .and(community_person_ban::person_id.eq(post::creator_id))
80 community_person_ban::expires
82 .or(community_person_ban::expires.gt(now)),
86 .inner_join(post_aggregates::table)
88 community_follower::table.on(
90 .eq(community_follower::community_id)
91 .and(community_follower::person_id.eq(person_id_join)),
97 .eq(post_saved::post_id)
98 .and(post_saved::person_id.eq(person_id_join)),
104 .eq(post_read::post_id)
105 .and(post_read::person_id.eq(person_id_join)),
109 person_block::table.on(
111 .eq(person_block::target_id)
112 .and(person_block::person_id.eq(person_id_join)),
118 .eq(post_like::post_id)
119 .and(post_like::person_id.eq(person_id_join)),
124 Person::safe_columns_tuple(),
125 Community::safe_columns_tuple(),
126 community_person_ban::all_columns.nullable(),
127 post_aggregates::all_columns,
128 community_follower::all_columns.nullable(),
129 post_saved::all_columns.nullable(),
130 post_read::all_columns.nullable(),
131 person_block::all_columns.nullable(),
132 post_like::score.nullable(),
134 .first::<PostViewTuple>(conn)?;
136 // If a person is given, then my_vote, if None, should be 0, not null
137 // Necessary to differentiate between other person's votes
138 let my_vote = if my_person_id.is_some() && post_like.is_none() {
148 creator_banned_from_community: creator_banned_from_community.is_some(),
150 subscribed: CommunityFollower::to_subscribed_type(&follower),
151 saved: saved.is_some(),
152 read: read.is_some(),
153 creator_blocked: creator_blocked.is_some(),
159 pub struct PostQueryBuilder<'a> {
160 conn: &'a 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 my_person_id: Option<PersonId>,
167 search_term: Option<String>,
168 url_search: Option<String>,
169 show_nsfw: Option<bool>,
170 show_bot_accounts: Option<bool>,
171 show_read_posts: Option<bool>,
172 saved_only: Option<bool>,
177 impl<'a> PostQueryBuilder<'a> {
178 pub fn create(conn: &'a PgConnection) -> Self {
185 community_actor_id: None,
190 show_bot_accounts: None,
191 show_read_posts: None,
198 pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
199 self.listing_type = listing_type.get_optional();
203 pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
204 self.sort = sort.get_optional();
208 pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
209 self.community_id = community_id.get_optional();
213 pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
214 self.my_person_id = my_person_id.get_optional();
218 pub fn community_actor_id<T: MaybeOptional<DbUrl>>(mut self, community_actor_id: T) -> Self {
219 self.community_actor_id = community_actor_id.get_optional();
223 pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
224 self.creator_id = creator_id.get_optional();
228 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
229 self.search_term = search_term.get_optional();
233 pub fn url_search<T: MaybeOptional<String>>(mut self, url_search: T) -> Self {
234 self.url_search = url_search.get_optional();
238 pub fn show_nsfw<T: MaybeOptional<bool>>(mut self, show_nsfw: T) -> Self {
239 self.show_nsfw = show_nsfw.get_optional();
243 pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
244 self.show_bot_accounts = show_bot_accounts.get_optional();
248 pub fn show_read_posts<T: MaybeOptional<bool>>(mut self, show_read_posts: T) -> Self {
249 self.show_read_posts = show_read_posts.get_optional();
253 pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
254 self.saved_only = saved_only.get_optional();
258 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
259 self.page = page.get_optional();
263 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
264 self.limit = limit.get_optional();
268 pub fn list(self) -> Result<Vec<PostView>, Error> {
271 // The left join below will return None in this case
272 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
274 let mut query = post::table
275 .inner_join(person::table)
276 .inner_join(community::table)
278 community_person_ban::table.on(
280 .eq(community_person_ban::community_id)
281 .and(community_person_ban::person_id.eq(post::creator_id))
283 community_person_ban::expires
285 .or(community_person_ban::expires.gt(now)),
289 .inner_join(post_aggregates::table)
291 community_follower::table.on(
293 .eq(community_follower::community_id)
294 .and(community_follower::person_id.eq(person_id_join)),
298 post_saved::table.on(
300 .eq(post_saved::post_id)
301 .and(post_saved::person_id.eq(person_id_join)),
307 .eq(post_read::post_id)
308 .and(post_read::person_id.eq(person_id_join)),
312 person_block::table.on(
314 .eq(person_block::target_id)
315 .and(person_block::person_id.eq(person_id_join)),
319 community_block::table.on(
321 .eq(community_block::community_id)
322 .and(community_block::person_id.eq(person_id_join)),
328 .eq(post_like::post_id)
329 .and(post_like::person_id.eq(person_id_join)),
334 Person::safe_columns_tuple(),
335 Community::safe_columns_tuple(),
336 community_person_ban::all_columns.nullable(),
337 post_aggregates::all_columns,
338 community_follower::all_columns.nullable(),
339 post_saved::all_columns.nullable(),
340 post_read::all_columns.nullable(),
341 person_block::all_columns.nullable(),
342 post_like::score.nullable(),
346 if let Some(listing_type) = self.listing_type {
348 ListingType::Subscribed => {
349 query = query.filter(community_follower::person_id.is_not_null())
351 ListingType::Local => {
352 query = query.filter(community::local.eq(true)).filter(
355 .or(community_follower::person_id.eq(person_id_join)),
358 ListingType::All => {
359 query = query.filter(
362 .or(community_follower::person_id.eq(person_id_join)),
365 ListingType::Community => {
366 if self.community_actor_id.is_none() && self.community_id.is_none() {
367 return Err(QueryBuilderError("No community actor or id given".into()));
369 if let Some(community_id) = self.community_id {
371 .filter(post::community_id.eq(community_id))
372 .then_order_by(post_aggregates::stickied.desc());
375 if let Some(community_actor_id) = self.community_actor_id {
377 .filter(community::actor_id.eq(community_actor_id))
378 .then_order_by(post_aggregates::stickied.desc());
385 if let Some(url_search) = self.url_search {
386 query = query.filter(post::url.eq(url_search));
389 if let Some(search_term) = self.search_term {
390 let searcher = fuzzy_search(&search_term);
391 query = query.filter(
393 .ilike(searcher.to_owned())
394 .or(post::body.ilike(searcher)),
398 // If its for a specific person, show the removed / deleted
399 if let Some(creator_id) = self.creator_id {
400 query = query.filter(post::creator_id.eq(creator_id));
403 if !self.show_nsfw.unwrap_or(false) {
405 .filter(post::nsfw.eq(false))
406 .filter(community::nsfw.eq(false));
409 if !self.show_bot_accounts.unwrap_or(true) {
410 query = query.filter(person::bot_account.eq(false));
413 if self.saved_only.unwrap_or(false) {
414 query = query.filter(post_saved::id.is_not_null());
416 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
417 // setting wont be able to see saved posts.
418 else if !self.show_read_posts.unwrap_or(true) {
419 query = query.filter(post_read::id.is_null());
422 // Don't show blocked communities or persons
423 if self.my_person_id.is_some() {
424 query = query.filter(community_block::person_id.is_null());
425 query = query.filter(person_block::person_id.is_null());
428 query = match self.sort.unwrap_or(SortType::Hot) {
429 SortType::Active => query
432 post_aggregates::score,
433 post_aggregates::newest_comment_time_necro,
437 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
438 SortType::Hot => query
439 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
440 .then_order_by(post_aggregates::published.desc()),
441 SortType::New => query.then_order_by(post_aggregates::published.desc()),
442 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
443 SortType::MostComments => query
444 .then_order_by(post_aggregates::comments.desc())
445 .then_order_by(post_aggregates::published.desc()),
446 SortType::TopAll => query
447 .then_order_by(post_aggregates::score.desc())
448 .then_order_by(post_aggregates::published.desc()),
449 SortType::TopYear => query
450 .filter(post_aggregates::published.gt(now - 1.years()))
451 .then_order_by(post_aggregates::score.desc())
452 .then_order_by(post_aggregates::published.desc()),
453 SortType::TopMonth => query
454 .filter(post_aggregates::published.gt(now - 1.months()))
455 .then_order_by(post_aggregates::score.desc())
456 .then_order_by(post_aggregates::published.desc()),
457 SortType::TopWeek => query
458 .filter(post_aggregates::published.gt(now - 1.weeks()))
459 .then_order_by(post_aggregates::score.desc())
460 .then_order_by(post_aggregates::published.desc()),
461 SortType::TopDay => query
462 .filter(post_aggregates::published.gt(now - 1.days()))
463 .then_order_by(post_aggregates::score.desc())
464 .then_order_by(post_aggregates::published.desc()),
467 let (limit, offset) = limit_and_offset(self.page, self.limit)?;
472 .filter(post::removed.eq(false))
473 .filter(post::deleted.eq(false))
474 .filter(community::removed.eq(false))
475 .filter(community::deleted.eq(false));
477 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
479 let res = query.load::<PostViewTuple>(self.conn)?;
481 Ok(PostView::from_tuple_to_vec(res))
485 impl ViewToVec for PostView {
486 type DbTuple = PostViewTuple;
487 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
491 post: a.0.to_owned(),
492 creator: a.1.to_owned(),
493 community: a.2.to_owned(),
494 creator_banned_from_community: a.3.is_some(),
495 counts: a.4.to_owned(),
496 subscribed: CommunityFollower::to_subscribed_type(&a.5),
497 saved: a.6.is_some(),
499 creator_blocked: a.8.is_some(),
502 .collect::<Vec<Self>>()
508 use crate::post_view::{PostQueryBuilder, PostView};
509 use lemmy_db_schema::{
510 aggregates::structs::PostAggregates,
513 community_block::{CommunityBlock, CommunityBlockForm},
515 person_block::{PersonBlock, PersonBlockForm},
518 traits::{Blockable, Crud, Likeable},
519 utils::establish_unpooled_connection,
524 use serial_test::serial;
529 let conn = establish_unpooled_connection();
531 let person_name = "tegan".to_string();
532 let community_name = "test_community_3".to_string();
533 let post_name = "test post 3".to_string();
534 let bot_post_name = "test bot post".to_string();
536 let new_person = PersonForm {
537 name: person_name.to_owned(),
538 public_key: Some("pubkey".to_string()),
539 ..PersonForm::default()
542 let inserted_person = Person::create(&conn, &new_person).unwrap();
544 let new_bot = PersonForm {
545 name: person_name.to_owned(),
546 bot_account: Some(true),
547 public_key: Some("pubkey".to_string()),
548 ..PersonForm::default()
551 let inserted_bot = Person::create(&conn, &new_bot).unwrap();
553 let new_community = CommunityForm {
554 name: community_name.to_owned(),
555 title: "nada".to_owned(),
556 public_key: Some("pubkey".to_string()),
557 ..CommunityForm::default()
560 let inserted_community = Community::create(&conn, &new_community).unwrap();
562 // Test a person block, make sure the post query doesn't include their post
563 let blocked_person = PersonForm {
564 name: person_name.to_owned(),
565 public_key: Some("pubkey".to_string()),
566 ..PersonForm::default()
569 let inserted_blocked_person = Person::create(&conn, &blocked_person).unwrap();
571 let post_from_blocked_person = PostForm {
572 name: "blocked_person_post".to_string(),
573 creator_id: inserted_blocked_person.id,
574 community_id: inserted_community.id,
575 ..PostForm::default()
578 Post::create(&conn, &post_from_blocked_person).unwrap();
581 let person_block = PersonBlockForm {
582 person_id: inserted_person.id,
583 target_id: inserted_blocked_person.id,
586 PersonBlock::block(&conn, &person_block).unwrap();
589 let new_post = PostForm {
590 name: post_name.to_owned(),
591 creator_id: inserted_person.id,
592 community_id: inserted_community.id,
593 ..PostForm::default()
596 let inserted_post = Post::create(&conn, &new_post).unwrap();
598 let new_bot_post = PostForm {
600 creator_id: inserted_bot.id,
601 community_id: inserted_community.id,
602 ..PostForm::default()
605 let _inserted_bot_post = Post::create(&conn, &new_bot_post).unwrap();
607 let post_like_form = PostLikeForm {
608 post_id: inserted_post.id,
609 person_id: inserted_person.id,
613 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
615 let expected_post_like = PostLike {
616 id: inserted_post_like.id,
617 post_id: inserted_post.id,
618 person_id: inserted_person.id,
619 published: inserted_post_like.published,
623 let read_post_listings_with_person = PostQueryBuilder::create(&conn)
624 .listing_type(ListingType::Community)
626 .show_bot_accounts(false)
627 .community_id(inserted_community.id)
628 .my_person_id(inserted_person.id)
632 let read_post_listings_no_person = PostQueryBuilder::create(&conn)
633 .listing_type(ListingType::Community)
635 .community_id(inserted_community.id)
639 let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
640 let read_post_listing_with_person =
641 PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
643 let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
645 // the non person version
646 let expected_post_listing_no_person = PostView {
648 id: inserted_post.id,
650 creator_id: inserted_person.id,
653 published: inserted_post.published,
655 community_id: inserted_community.id,
662 embed_description: None,
663 embed_video_url: None,
665 ap_id: inserted_post.ap_id.to_owned(),
669 creator: PersonSafe {
670 id: inserted_person.id,
673 published: inserted_person.published,
675 actor_id: inserted_person.actor_id.to_owned(),
684 inbox_url: inserted_person.inbox_url.to_owned(),
685 shared_inbox_url: None,
686 matrix_user_id: None,
689 creator_banned_from_community: false,
690 community: CommunitySafe {
691 id: inserted_community.id,
692 name: community_name,
697 actor_id: inserted_community.actor_id.to_owned(),
699 title: "nada".to_owned(),
704 posting_restricted_to_mods: false,
705 published: inserted_community.published,
707 counts: PostAggregates {
709 post_id: inserted_post.id,
715 published: agg.published,
716 newest_comment_time_necro: inserted_post.published,
717 newest_comment_time: inserted_post.published,
719 subscribed: SubscribedType::NotSubscribed,
722 creator_blocked: false,
725 // Test a community block
726 let community_block = CommunityBlockForm {
727 person_id: inserted_person.id,
728 community_id: inserted_community.id,
730 CommunityBlock::block(&conn, &community_block).unwrap();
732 let read_post_listings_with_person_after_block = PostQueryBuilder::create(&conn)
733 .listing_type(ListingType::Community)
735 .show_bot_accounts(false)
736 .community_id(inserted_community.id)
737 .my_person_id(inserted_person.id)
741 // TODO More needs to be added here
742 let mut expected_post_listing_with_user = expected_post_listing_no_person.to_owned();
743 expected_post_listing_with_user.my_vote = Some(1);
745 let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
746 let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
747 PersonBlock::unblock(&conn, &person_block).unwrap();
748 CommunityBlock::unblock(&conn, &community_block).unwrap();
749 Community::delete(&conn, inserted_community.id).unwrap();
750 Person::delete(&conn, inserted_person.id).unwrap();
751 Person::delete(&conn, inserted_bot.id).unwrap();
752 Person::delete(&conn, inserted_blocked_person.id).unwrap();
756 expected_post_listing_with_user,
757 read_post_listings_with_person[0]
760 expected_post_listing_with_user,
761 read_post_listing_with_person
764 // Should be only one person, IE the bot post, and blocked should be missing
765 assert_eq!(1, read_post_listings_with_person.len());
769 expected_post_listing_no_person,
770 read_post_listings_no_person[1]
772 assert_eq!(expected_post_listing_no_person, read_post_listing_no_person);
774 // Should be 2 posts, with the bot post, and the blocked
775 assert_eq!(3, read_post_listings_no_person.len());
777 // Should be 0 posts after the community block
778 assert_eq!(0, read_post_listings_with_person_after_block.len());
780 assert_eq!(expected_post_like, inserted_post_like);
781 assert_eq!(1, like_removed);
782 assert_eq!(1, num_deleted);