1 use crate::structs::PostView;
2 use diesel::{dsl::*, pg::Pg, result::Error, *};
4 aggregates::structs::PostAggregates,
5 newtypes::{CommunityId, DbUrl, PersonId, PostId},
20 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
21 person::{Person, PersonSafe},
22 person_block::PersonBlock,
23 post::{Post, PostRead, PostSaved},
25 traits::{MaybeOptional, ToSafe, ViewToVec},
26 utils::{functions::hot_rank, fuzzy_search, limit_and_offset},
32 type PostViewTuple = (
36 Option<CommunityPersonBan>,
38 Option<CommunityFollower>,
49 my_person_id: Option<PersonId>,
50 ) -> Result<Self, Error> {
51 // The left join below will return None in this case
52 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
58 creator_banned_from_community,
67 .inner_join(person::table)
68 .inner_join(community::table)
70 community_person_ban::table.on(
72 .eq(community_person_ban::community_id)
73 .and(community_person_ban::person_id.eq(post::creator_id))
75 community_person_ban::expires
77 .or(community_person_ban::expires.gt(now)),
81 .inner_join(post_aggregates::table)
83 community_follower::table.on(
85 .eq(community_follower::community_id)
86 .and(community_follower::person_id.eq(person_id_join)),
92 .eq(post_saved::post_id)
93 .and(post_saved::person_id.eq(person_id_join)),
99 .eq(post_read::post_id)
100 .and(post_read::person_id.eq(person_id_join)),
104 person_block::table.on(
106 .eq(person_block::target_id)
107 .and(person_block::person_id.eq(person_id_join)),
113 .eq(post_like::post_id)
114 .and(post_like::person_id.eq(person_id_join)),
119 Person::safe_columns_tuple(),
120 Community::safe_columns_tuple(),
121 community_person_ban::all_columns.nullable(),
122 post_aggregates::all_columns,
123 community_follower::all_columns.nullable(),
124 post_saved::all_columns.nullable(),
125 post_read::all_columns.nullable(),
126 person_block::all_columns.nullable(),
127 post_like::score.nullable(),
129 .first::<PostViewTuple>(conn)?;
131 // If a person is given, then my_vote, if None, should be 0, not null
132 // Necessary to differentiate between other person's votes
133 let my_vote = if my_person_id.is_some() && post_like.is_none() {
143 creator_banned_from_community: creator_banned_from_community.is_some(),
145 subscribed: CommunityFollower::to_subscribed_type(&follower),
146 saved: saved.is_some(),
147 read: read.is_some(),
148 creator_blocked: creator_blocked.is_some(),
154 pub struct PostQueryBuilder<'a> {
155 conn: &'a PgConnection,
156 listing_type: Option<ListingType>,
157 sort: Option<SortType>,
158 creator_id: Option<PersonId>,
159 community_id: Option<CommunityId>,
160 community_actor_id: Option<DbUrl>,
161 my_person_id: Option<PersonId>,
162 search_term: Option<String>,
163 url_search: Option<String>,
164 show_nsfw: Option<bool>,
165 show_bot_accounts: Option<bool>,
166 show_read_posts: Option<bool>,
167 saved_only: Option<bool>,
172 impl<'a> PostQueryBuilder<'a> {
173 pub fn create(conn: &'a PgConnection) -> Self {
176 listing_type: Some(ListingType::All),
180 community_actor_id: None,
185 show_bot_accounts: None,
186 show_read_posts: None,
193 pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
194 self.listing_type = listing_type.get_optional();
198 pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
199 self.sort = sort.get_optional();
203 pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
204 self.community_id = community_id.get_optional();
208 pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
209 self.my_person_id = my_person_id.get_optional();
213 pub fn community_actor_id<T: MaybeOptional<DbUrl>>(mut self, community_actor_id: T) -> Self {
214 self.community_actor_id = community_actor_id.get_optional();
218 pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
219 self.creator_id = creator_id.get_optional();
223 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
224 self.search_term = search_term.get_optional();
228 pub fn url_search<T: MaybeOptional<String>>(mut self, url_search: T) -> Self {
229 self.url_search = url_search.get_optional();
233 pub fn show_nsfw<T: MaybeOptional<bool>>(mut self, show_nsfw: T) -> Self {
234 self.show_nsfw = show_nsfw.get_optional();
238 pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
239 self.show_bot_accounts = show_bot_accounts.get_optional();
243 pub fn show_read_posts<T: MaybeOptional<bool>>(mut self, show_read_posts: T) -> Self {
244 self.show_read_posts = show_read_posts.get_optional();
248 pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
249 self.saved_only = saved_only.get_optional();
253 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
254 self.page = page.get_optional();
258 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
259 self.limit = limit.get_optional();
263 pub fn list(self) -> Result<Vec<PostView>, Error> {
266 // The left join below will return None in this case
267 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
269 let mut query = post::table
270 .inner_join(person::table)
271 .inner_join(community::table)
273 community_person_ban::table.on(
275 .eq(community_person_ban::community_id)
276 .and(community_person_ban::person_id.eq(post::creator_id))
278 community_person_ban::expires
280 .or(community_person_ban::expires.gt(now)),
284 .inner_join(post_aggregates::table)
286 community_follower::table.on(
288 .eq(community_follower::community_id)
289 .and(community_follower::person_id.eq(person_id_join)),
293 post_saved::table.on(
295 .eq(post_saved::post_id)
296 .and(post_saved::person_id.eq(person_id_join)),
302 .eq(post_read::post_id)
303 .and(post_read::person_id.eq(person_id_join)),
307 person_block::table.on(
309 .eq(person_block::target_id)
310 .and(person_block::person_id.eq(person_id_join)),
314 community_block::table.on(
316 .eq(community_block::community_id)
317 .and(community_block::person_id.eq(person_id_join)),
323 .eq(post_like::post_id)
324 .and(post_like::person_id.eq(person_id_join)),
329 Person::safe_columns_tuple(),
330 Community::safe_columns_tuple(),
331 community_person_ban::all_columns.nullable(),
332 post_aggregates::all_columns,
333 community_follower::all_columns.nullable(),
334 post_saved::all_columns.nullable(),
335 post_read::all_columns.nullable(),
336 person_block::all_columns.nullable(),
337 post_like::score.nullable(),
341 if let Some(listing_type) = self.listing_type {
343 ListingType::Subscribed => {
344 query = query.filter(community_follower::person_id.is_not_null())
346 ListingType::Local => {
347 query = query.filter(community::local.eq(true)).filter(
350 .or(community_follower::person_id.eq(person_id_join)),
353 ListingType::All => {
354 query = query.filter(
357 .or(community_follower::person_id.eq(person_id_join)),
363 if let Some(community_id) = self.community_id {
365 .filter(post::community_id.eq(community_id))
366 .then_order_by(post_aggregates::stickied.desc());
369 if let Some(community_actor_id) = self.community_actor_id {
371 .filter(community::actor_id.eq(community_actor_id))
372 .then_order_by(post_aggregates::stickied.desc());
375 if let Some(url_search) = self.url_search {
376 query = query.filter(post::url.eq(url_search));
379 if let Some(search_term) = self.search_term {
380 let searcher = fuzzy_search(&search_term);
381 query = query.filter(
383 .ilike(searcher.to_owned())
384 .or(post::body.ilike(searcher)),
388 // If its for a specific person, show the removed / deleted
389 if let Some(creator_id) = self.creator_id {
390 query = query.filter(post::creator_id.eq(creator_id));
393 if !self.show_nsfw.unwrap_or(false) {
395 .filter(post::nsfw.eq(false))
396 .filter(community::nsfw.eq(false));
399 if !self.show_bot_accounts.unwrap_or(true) {
400 query = query.filter(person::bot_account.eq(false));
403 if self.saved_only.unwrap_or(false) {
404 query = query.filter(post_saved::id.is_not_null());
406 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
407 // setting wont be able to see saved posts.
408 else if !self.show_read_posts.unwrap_or(true) {
409 query = query.filter(post_read::id.is_null());
412 // Don't show blocked communities or persons
413 if self.my_person_id.is_some() {
414 query = query.filter(community_block::person_id.is_null());
415 query = query.filter(person_block::person_id.is_null());
418 query = match self.sort.unwrap_or(SortType::Hot) {
419 SortType::Active => query
422 post_aggregates::score,
423 post_aggregates::newest_comment_time_necro,
427 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
428 SortType::Hot => query
429 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
430 .then_order_by(post_aggregates::published.desc()),
431 SortType::New => query.then_order_by(post_aggregates::published.desc()),
432 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
433 SortType::MostComments => query
434 .then_order_by(post_aggregates::comments.desc())
435 .then_order_by(post_aggregates::published.desc()),
436 SortType::TopAll => query
437 .then_order_by(post_aggregates::score.desc())
438 .then_order_by(post_aggregates::published.desc()),
439 SortType::TopYear => query
440 .filter(post_aggregates::published.gt(now - 1.years()))
441 .then_order_by(post_aggregates::score.desc())
442 .then_order_by(post_aggregates::published.desc()),
443 SortType::TopMonth => query
444 .filter(post_aggregates::published.gt(now - 1.months()))
445 .then_order_by(post_aggregates::score.desc())
446 .then_order_by(post_aggregates::published.desc()),
447 SortType::TopWeek => query
448 .filter(post_aggregates::published.gt(now - 1.weeks()))
449 .then_order_by(post_aggregates::score.desc())
450 .then_order_by(post_aggregates::published.desc()),
451 SortType::TopDay => query
452 .filter(post_aggregates::published.gt(now - 1.days()))
453 .then_order_by(post_aggregates::score.desc())
454 .then_order_by(post_aggregates::published.desc()),
457 let (limit, offset) = limit_and_offset(self.page, self.limit)?;
462 .filter(post::removed.eq(false))
463 .filter(post::deleted.eq(false))
464 .filter(community::removed.eq(false))
465 .filter(community::deleted.eq(false));
467 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
469 let res = query.load::<PostViewTuple>(self.conn)?;
471 Ok(PostView::from_tuple_to_vec(res))
475 impl ViewToVec for PostView {
476 type DbTuple = PostViewTuple;
477 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
481 post: a.0.to_owned(),
482 creator: a.1.to_owned(),
483 community: a.2.to_owned(),
484 creator_banned_from_community: a.3.is_some(),
485 counts: a.4.to_owned(),
486 subscribed: CommunityFollower::to_subscribed_type(&a.5),
487 saved: a.6.is_some(),
489 creator_blocked: a.8.is_some(),
492 .collect::<Vec<Self>>()
498 use crate::post_view::{PostQueryBuilder, PostView};
499 use lemmy_db_schema::{
500 aggregates::structs::PostAggregates,
503 community_block::{CommunityBlock, CommunityBlockForm},
505 person_block::{PersonBlock, PersonBlockForm},
508 traits::{Blockable, Crud, Likeable},
509 utils::establish_unpooled_connection,
513 use serial_test::serial;
518 let conn = establish_unpooled_connection();
520 let person_name = "tegan".to_string();
521 let community_name = "test_community_3".to_string();
522 let post_name = "test post 3".to_string();
523 let bot_post_name = "test bot post".to_string();
525 let new_person = PersonForm {
526 name: person_name.to_owned(),
527 public_key: Some("pubkey".to_string()),
528 ..PersonForm::default()
531 let inserted_person = Person::create(&conn, &new_person).unwrap();
533 let new_bot = PersonForm {
534 name: person_name.to_owned(),
535 bot_account: Some(true),
536 public_key: Some("pubkey".to_string()),
537 ..PersonForm::default()
540 let inserted_bot = Person::create(&conn, &new_bot).unwrap();
542 let new_community = CommunityForm {
543 name: community_name.to_owned(),
544 title: "nada".to_owned(),
545 public_key: Some("pubkey".to_string()),
546 ..CommunityForm::default()
549 let inserted_community = Community::create(&conn, &new_community).unwrap();
551 // Test a person block, make sure the post query doesn't include their post
552 let blocked_person = PersonForm {
553 name: person_name.to_owned(),
554 public_key: Some("pubkey".to_string()),
555 ..PersonForm::default()
558 let inserted_blocked_person = Person::create(&conn, &blocked_person).unwrap();
560 let post_from_blocked_person = PostForm {
561 name: "blocked_person_post".to_string(),
562 creator_id: inserted_blocked_person.id,
563 community_id: inserted_community.id,
564 ..PostForm::default()
567 Post::create(&conn, &post_from_blocked_person).unwrap();
570 let person_block = PersonBlockForm {
571 person_id: inserted_person.id,
572 target_id: inserted_blocked_person.id,
575 PersonBlock::block(&conn, &person_block).unwrap();
578 let new_post = PostForm {
579 name: post_name.to_owned(),
580 creator_id: inserted_person.id,
581 community_id: inserted_community.id,
582 ..PostForm::default()
585 let inserted_post = Post::create(&conn, &new_post).unwrap();
587 let new_bot_post = PostForm {
589 creator_id: inserted_bot.id,
590 community_id: inserted_community.id,
591 ..PostForm::default()
594 let _inserted_bot_post = Post::create(&conn, &new_bot_post).unwrap();
596 let post_like_form = PostLikeForm {
597 post_id: inserted_post.id,
598 person_id: inserted_person.id,
602 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
604 let expected_post_like = PostLike {
605 id: inserted_post_like.id,
606 post_id: inserted_post.id,
607 person_id: inserted_person.id,
608 published: inserted_post_like.published,
612 let read_post_listings_with_person = PostQueryBuilder::create(&conn)
614 .show_bot_accounts(false)
615 .community_id(inserted_community.id)
616 .my_person_id(inserted_person.id)
620 let read_post_listings_no_person = PostQueryBuilder::create(&conn)
622 .community_id(inserted_community.id)
626 let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
627 let read_post_listing_with_person =
628 PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
630 let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
632 // the non person version
633 let expected_post_listing_no_person = PostView {
635 id: inserted_post.id,
637 creator_id: inserted_person.id,
640 published: inserted_post.published,
642 community_id: inserted_community.id,
649 embed_description: None,
650 embed_video_url: None,
652 ap_id: inserted_post.ap_id.to_owned(),
656 creator: PersonSafe {
657 id: inserted_person.id,
660 published: inserted_person.published,
662 actor_id: inserted_person.actor_id.to_owned(),
671 inbox_url: inserted_person.inbox_url.to_owned(),
672 shared_inbox_url: None,
673 matrix_user_id: None,
676 creator_banned_from_community: false,
677 community: CommunitySafe {
678 id: inserted_community.id,
679 name: community_name,
684 actor_id: inserted_community.actor_id.to_owned(),
686 title: "nada".to_owned(),
691 posting_restricted_to_mods: false,
692 published: inserted_community.published,
694 counts: PostAggregates {
696 post_id: inserted_post.id,
702 published: agg.published,
703 newest_comment_time_necro: inserted_post.published,
704 newest_comment_time: inserted_post.published,
706 subscribed: SubscribedType::NotSubscribed,
709 creator_blocked: false,
712 // Test a community block
713 let community_block = CommunityBlockForm {
714 person_id: inserted_person.id,
715 community_id: inserted_community.id,
717 CommunityBlock::block(&conn, &community_block).unwrap();
719 let read_post_listings_with_person_after_block = PostQueryBuilder::create(&conn)
721 .show_bot_accounts(false)
722 .community_id(inserted_community.id)
723 .my_person_id(inserted_person.id)
727 // TODO More needs to be added here
728 let mut expected_post_listing_with_user = expected_post_listing_no_person.to_owned();
729 expected_post_listing_with_user.my_vote = Some(1);
731 let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
732 let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
733 PersonBlock::unblock(&conn, &person_block).unwrap();
734 CommunityBlock::unblock(&conn, &community_block).unwrap();
735 Community::delete(&conn, inserted_community.id).unwrap();
736 Person::delete(&conn, inserted_person.id).unwrap();
737 Person::delete(&conn, inserted_bot.id).unwrap();
738 Person::delete(&conn, inserted_blocked_person.id).unwrap();
742 expected_post_listing_with_user,
743 read_post_listings_with_person[0]
746 expected_post_listing_with_user,
747 read_post_listing_with_person
750 // Should be only one person, IE the bot post, and blocked should be missing
751 assert_eq!(1, read_post_listings_with_person.len());
755 expected_post_listing_no_person,
756 read_post_listings_no_person[1]
758 assert_eq!(expected_post_listing_no_person, read_post_listing_no_person);
760 // Should be 2 posts, with the bot post, and the blocked
761 assert_eq!(3, read_post_listings_no_person.len());
763 // Should be 0 posts after the community block
764 assert_eq!(0, read_post_listings_with_person_after_block.len());
766 assert_eq!(expected_post_like, inserted_post_like);
767 assert_eq!(1, like_removed);
768 assert_eq!(1, num_deleted);