1 use diesel::{pg::Pg, result::Error, *};
2 use lemmy_db_queries::{
3 aggregates::post_aggregates::PostAggregates,
13 use lemmy_db_schema::{
28 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
29 person::{Person, PersonSafe},
30 person_block::PersonBlock,
31 post::{Post, PostRead, PostSaved},
41 #[derive(Debug, PartialEq, Serialize, Clone)]
44 pub creator: PersonSafe,
45 pub community: CommunitySafe,
46 pub creator_banned_from_community: bool, // Left Join to CommunityPersonBan
47 pub counts: PostAggregates,
48 pub subscribed: bool, // Left join to CommunityFollower
49 pub saved: bool, // Left join to PostSaved
50 pub read: bool, // Left join to PostRead
51 pub creator_blocked: bool, // Left join to PersonBlock
52 pub my_vote: Option<i16>, // Left join to PostLike
55 type PostViewTuple = (
59 Option<CommunityPersonBan>,
61 Option<CommunityFollower>,
72 my_person_id: Option<PersonId>,
73 ) -> Result<Self, Error> {
74 // The left join below will return None in this case
75 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
81 creator_banned_from_community,
90 .inner_join(person::table)
91 .inner_join(community::table)
93 community_person_ban::table.on(
95 .eq(community_person_ban::community_id)
96 .and(community_person_ban::person_id.eq(post::creator_id)),
99 .inner_join(post_aggregates::table)
101 community_follower::table.on(
103 .eq(community_follower::community_id)
104 .and(community_follower::person_id.eq(person_id_join)),
108 post_saved::table.on(
110 .eq(post_saved::post_id)
111 .and(post_saved::person_id.eq(person_id_join)),
117 .eq(post_read::post_id)
118 .and(post_read::person_id.eq(person_id_join)),
122 person_block::table.on(
124 .eq(person_block::target_id)
125 .and(person_block::person_id.eq(person_id_join)),
131 .eq(post_like::post_id)
132 .and(post_like::person_id.eq(person_id_join)),
137 Person::safe_columns_tuple(),
138 Community::safe_columns_tuple(),
139 community_person_ban::all_columns.nullable(),
140 post_aggregates::all_columns,
141 community_follower::all_columns.nullable(),
142 post_saved::all_columns.nullable(),
143 post_read::all_columns.nullable(),
144 person_block::all_columns.nullable(),
145 post_like::score.nullable(),
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: follower.is_some(),
164 saved: saved.is_some(),
165 read: read.is_some(),
166 creator_blocked: creator_blocked.is_some(),
172 pub struct PostQueryBuilder<'a> {
173 conn: &'a PgConnection,
174 listing_type: Option<ListingType>,
175 sort: Option<SortType>,
176 creator_id: Option<PersonId>,
177 community_id: Option<CommunityId>,
178 community_actor_id: Option<DbUrl>,
179 my_person_id: Option<PersonId>,
180 search_term: Option<String>,
181 url_search: Option<String>,
182 show_nsfw: Option<bool>,
183 show_bot_accounts: Option<bool>,
184 show_read_posts: Option<bool>,
185 saved_only: Option<bool>,
190 impl<'a> PostQueryBuilder<'a> {
191 pub fn create(conn: &'a PgConnection) -> Self {
198 community_actor_id: None,
203 show_bot_accounts: None,
204 show_read_posts: None,
211 pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
212 self.listing_type = listing_type.get_optional();
216 pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
217 self.sort = sort.get_optional();
221 pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
222 self.community_id = community_id.get_optional();
226 pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
227 self.my_person_id = my_person_id.get_optional();
231 pub fn community_actor_id<T: MaybeOptional<DbUrl>>(mut self, community_actor_id: T) -> Self {
232 self.community_actor_id = community_actor_id.get_optional();
236 pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
237 self.creator_id = creator_id.get_optional();
241 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
242 self.search_term = search_term.get_optional();
246 pub fn url_search<T: MaybeOptional<String>>(mut self, url_search: T) -> Self {
247 self.url_search = url_search.get_optional();
251 pub fn show_nsfw<T: MaybeOptional<bool>>(mut self, show_nsfw: T) -> Self {
252 self.show_nsfw = show_nsfw.get_optional();
256 pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
257 self.show_bot_accounts = show_bot_accounts.get_optional();
261 pub fn show_read_posts<T: MaybeOptional<bool>>(mut self, show_read_posts: T) -> Self {
262 self.show_read_posts = show_read_posts.get_optional();
266 pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
267 self.saved_only = saved_only.get_optional();
271 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
272 self.page = page.get_optional();
276 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
277 self.limit = limit.get_optional();
281 pub fn list(self) -> Result<Vec<PostView>, Error> {
284 // The left join below will return None in this case
285 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
287 let mut query = post::table
288 .inner_join(person::table)
289 .inner_join(community::table)
291 community_person_ban::table.on(
293 .eq(community_person_ban::community_id)
294 .and(community_person_ban::person_id.eq(post::creator_id)),
297 .inner_join(post_aggregates::table)
299 community_follower::table.on(
301 .eq(community_follower::community_id)
302 .and(community_follower::person_id.eq(person_id_join)),
306 post_saved::table.on(
308 .eq(post_saved::post_id)
309 .and(post_saved::person_id.eq(person_id_join)),
315 .eq(post_read::post_id)
316 .and(post_read::person_id.eq(person_id_join)),
320 person_block::table.on(
322 .eq(person_block::target_id)
323 .and(person_block::person_id.eq(person_id_join)),
327 community_block::table.on(
329 .eq(community_block::community_id)
330 .and(community_block::person_id.eq(person_id_join)),
336 .eq(post_like::post_id)
337 .and(post_like::person_id.eq(person_id_join)),
342 Person::safe_columns_tuple(),
343 Community::safe_columns_tuple(),
344 community_person_ban::all_columns.nullable(),
345 post_aggregates::all_columns,
346 community_follower::all_columns.nullable(),
347 post_saved::all_columns.nullable(),
348 post_read::all_columns.nullable(),
349 person_block::all_columns.nullable(),
350 post_like::score.nullable(),
354 if let Some(listing_type) = self.listing_type {
355 query = match listing_type {
356 ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()),
357 ListingType::Local => query.filter(community::local.eq(true)),
362 if let Some(community_id) = self.community_id {
364 .filter(post::community_id.eq(community_id))
365 .then_order_by(post_aggregates::stickied.desc());
368 if let Some(community_actor_id) = self.community_actor_id {
370 .filter(community::actor_id.eq(community_actor_id))
371 .then_order_by(post_aggregates::stickied.desc());
374 if let Some(url_search) = self.url_search {
375 query = query.filter(post::url.eq(url_search));
378 if let Some(search_term) = self.search_term {
379 let searcher = fuzzy_search(&search_term);
380 query = query.filter(
382 .ilike(searcher.to_owned())
383 .or(post::body.ilike(searcher)),
387 // If its for a specific person, show the removed / deleted
388 if let Some(creator_id) = self.creator_id {
389 query = query.filter(post::creator_id.eq(creator_id));
392 if !self.show_nsfw.unwrap_or(false) {
394 .filter(post::nsfw.eq(false))
395 .filter(community::nsfw.eq(false));
398 if !self.show_bot_accounts.unwrap_or(true) {
399 query = query.filter(person::bot_account.eq(false));
402 if !self.show_read_posts.unwrap_or(true) {
403 query = query.filter(post_read::id.is_null());
406 if self.saved_only.unwrap_or(false) {
407 query = query.filter(post_saved::id.is_not_null());
410 // Don't show blocked communities or persons
411 if self.my_person_id.is_some() {
412 query = query.filter(community_block::person_id.is_null());
413 query = query.filter(person_block::person_id.is_null());
416 query = match self.sort.unwrap_or(SortType::Hot) {
417 SortType::Active => query
420 post_aggregates::score,
421 post_aggregates::newest_comment_time_necro,
425 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
426 SortType::Hot => query
427 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
428 .then_order_by(post_aggregates::published.desc()),
429 SortType::New => query.then_order_by(post_aggregates::published.desc()),
430 SortType::MostComments => query.then_order_by(post_aggregates::comments.desc()),
431 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
432 SortType::TopAll => query.then_order_by(post_aggregates::score.desc()),
433 SortType::TopYear => query
434 .filter(post::published.gt(now - 1.years()))
435 .then_order_by(post_aggregates::score.desc()),
436 SortType::TopMonth => query
437 .filter(post::published.gt(now - 1.months()))
438 .then_order_by(post_aggregates::score.desc()),
439 SortType::TopWeek => query
440 .filter(post::published.gt(now - 1.weeks()))
441 .then_order_by(post_aggregates::score.desc()),
442 SortType::TopDay => query
443 .filter(post::published.gt(now - 1.days()))
444 .then_order_by(post_aggregates::score.desc()),
447 let (limit, offset) = limit_and_offset(self.page, self.limit);
452 .filter(post::removed.eq(false))
453 .filter(post::deleted.eq(false))
454 .filter(community::removed.eq(false))
455 .filter(community::deleted.eq(false));
457 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
459 let res = query.load::<PostViewTuple>(self.conn)?;
461 Ok(PostView::from_tuple_to_vec(res))
465 impl ViewToVec for PostView {
466 type DbTuple = PostViewTuple;
467 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
471 post: a.0.to_owned(),
472 creator: a.1.to_owned(),
473 community: a.2.to_owned(),
474 creator_banned_from_community: a.3.is_some(),
475 counts: a.4.to_owned(),
476 subscribed: a.5.is_some(),
477 saved: a.6.is_some(),
479 creator_blocked: a.8.is_some(),
482 .collect::<Vec<Self>>()
488 use crate::post_view::{PostQueryBuilder, PostView};
489 use lemmy_db_queries::{
490 aggregates::post_aggregates::PostAggregates,
491 establish_unpooled_connection,
498 use lemmy_db_schema::source::{
500 community_block::{CommunityBlock, CommunityBlockForm},
502 person_block::{PersonBlock, PersonBlockForm},
505 use serial_test::serial;
510 let conn = establish_unpooled_connection();
512 let person_name = "tegan".to_string();
513 let community_name = "test_community_3".to_string();
514 let post_name = "test post 3".to_string();
515 let bot_post_name = "test bot post".to_string();
517 let new_person = PersonForm {
518 name: person_name.to_owned(),
519 ..PersonForm::default()
522 let inserted_person = Person::create(&conn, &new_person).unwrap();
524 let new_bot = PersonForm {
525 name: person_name.to_owned(),
526 bot_account: Some(true),
527 ..PersonForm::default()
530 let inserted_bot = Person::create(&conn, &new_bot).unwrap();
532 let new_community = CommunityForm {
533 name: community_name.to_owned(),
534 title: "nada".to_owned(),
535 ..CommunityForm::default()
538 let inserted_community = Community::create(&conn, &new_community).unwrap();
540 // Test a person block, make sure the post query doesn't include their post
541 let blocked_person = PersonForm {
542 name: person_name.to_owned(),
543 ..PersonForm::default()
546 let inserted_blocked_person = Person::create(&conn, &blocked_person).unwrap();
548 let post_from_blocked_person = PostForm {
549 name: "blocked_person_post".to_string(),
550 creator_id: inserted_blocked_person.id,
551 community_id: inserted_community.id,
552 ..PostForm::default()
555 Post::create(&conn, &post_from_blocked_person).unwrap();
558 let person_block = PersonBlockForm {
559 person_id: inserted_person.id,
560 target_id: inserted_blocked_person.id,
563 PersonBlock::block(&conn, &person_block).unwrap();
566 let new_post = PostForm {
567 name: post_name.to_owned(),
568 creator_id: inserted_person.id,
569 community_id: inserted_community.id,
570 ..PostForm::default()
573 let inserted_post = Post::create(&conn, &new_post).unwrap();
575 let new_bot_post = PostForm {
577 creator_id: inserted_bot.id,
578 community_id: inserted_community.id,
579 ..PostForm::default()
582 let _inserted_bot_post = Post::create(&conn, &new_bot_post).unwrap();
584 let post_like_form = PostLikeForm {
585 post_id: inserted_post.id,
586 person_id: inserted_person.id,
590 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
592 let expected_post_like = PostLike {
593 id: inserted_post_like.id,
594 post_id: inserted_post.id,
595 person_id: inserted_person.id,
596 published: inserted_post_like.published,
600 let read_post_listings_with_person = PostQueryBuilder::create(&conn)
601 .listing_type(ListingType::Community)
603 .show_bot_accounts(false)
604 .community_id(inserted_community.id)
605 .my_person_id(inserted_person.id)
609 let read_post_listings_no_person = PostQueryBuilder::create(&conn)
610 .listing_type(ListingType::Community)
612 .community_id(inserted_community.id)
616 let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
617 let read_post_listing_with_person =
618 PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
620 let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
622 // the non person version
623 let expected_post_listing_no_person = PostView {
625 id: inserted_post.id,
627 creator_id: inserted_person.id,
630 published: inserted_post.published,
632 community_id: inserted_community.id,
639 embed_description: None,
642 ap_id: inserted_post.ap_id.to_owned(),
646 creator: PersonSafe {
647 id: inserted_person.id,
650 published: inserted_person.published,
652 actor_id: inserted_person.actor_id.to_owned(),
661 inbox_url: inserted_person.inbox_url.to_owned(),
662 shared_inbox_url: None,
663 matrix_user_id: None,
665 creator_banned_from_community: false,
666 community: CommunitySafe {
667 id: inserted_community.id,
668 name: community_name,
673 actor_id: inserted_community.actor_id.to_owned(),
675 title: "nada".to_owned(),
679 published: inserted_community.published,
681 counts: PostAggregates {
683 post_id: inserted_post.id,
689 published: agg.published,
690 newest_comment_time_necro: inserted_post.published,
691 newest_comment_time: inserted_post.published,
696 creator_blocked: false,
699 // Test a community block
700 let community_block = CommunityBlockForm {
701 person_id: inserted_person.id,
702 community_id: inserted_community.id,
704 CommunityBlock::block(&conn, &community_block).unwrap();
706 let read_post_listings_with_person_after_block = PostQueryBuilder::create(&conn)
707 .listing_type(ListingType::Community)
709 .show_bot_accounts(false)
710 .community_id(inserted_community.id)
711 .my_person_id(inserted_person.id)
715 // TODO More needs to be added here
716 let mut expected_post_listing_with_user = expected_post_listing_no_person.to_owned();
717 expected_post_listing_with_user.my_vote = Some(1);
719 let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
720 let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
721 PersonBlock::unblock(&conn, &person_block).unwrap();
722 CommunityBlock::unblock(&conn, &community_block).unwrap();
723 Community::delete(&conn, inserted_community.id).unwrap();
724 Person::delete(&conn, inserted_person.id).unwrap();
725 Person::delete(&conn, inserted_bot.id).unwrap();
726 Person::delete(&conn, inserted_blocked_person.id).unwrap();
730 expected_post_listing_with_user,
731 read_post_listings_with_person[0]
734 expected_post_listing_with_user,
735 read_post_listing_with_person
738 // Should be only one person, IE the bot post, and blocked should be missing
739 assert_eq!(1, read_post_listings_with_person.len());
743 expected_post_listing_no_person,
744 read_post_listings_no_person[1]
746 assert_eq!(expected_post_listing_no_person, read_post_listing_no_person);
748 // Should be 2 posts, with the bot post, and the blocked
749 assert_eq!(3, read_post_listings_no_person.len());
751 // Should be 0 posts after the community block
752 assert_eq!(0, read_post_listings_with_person_after_block.len());
754 assert_eq!(expected_post_like, inserted_post_like);
755 assert_eq!(1, like_removed);
756 assert_eq!(1, num_deleted);