1 use diesel::{dsl::*, pg::Pg, result::Error, *};
3 aggregates::post_aggregates::PostAggregates,
7 newtypes::{CommunityId, DbUrl, PersonId, PostId},
22 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
23 person::{Person, PersonSafe},
24 person_block::PersonBlock,
25 post::{Post, PostRead, PostSaved},
27 traits::{MaybeOptional, ToSafe, ViewToVec},
31 use serde::{Deserialize, Serialize};
34 #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
37 pub creator: PersonSafe,
38 pub community: CommunitySafe,
39 pub creator_banned_from_community: bool, // Left Join to CommunityPersonBan
40 pub counts: PostAggregates,
41 pub subscribed: bool, // Left join to CommunityFollower
42 pub saved: bool, // Left join to PostSaved
43 pub read: bool, // Left join to PostRead
44 pub creator_blocked: bool, // Left join to PersonBlock
45 pub my_vote: Option<i16>, // Left join to PostLike
48 type PostViewTuple = (
52 Option<CommunityPersonBan>,
54 Option<CommunityFollower>,
65 my_person_id: Option<PersonId>,
66 ) -> Result<Self, Error> {
67 // The left join below will return None in this case
68 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
74 creator_banned_from_community,
83 .inner_join(person::table)
84 .inner_join(community::table)
86 community_person_ban::table.on(
88 .eq(community_person_ban::community_id)
89 .and(community_person_ban::person_id.eq(post::creator_id))
91 community_person_ban::expires
93 .or(community_person_ban::expires.gt(now)),
97 .inner_join(post_aggregates::table)
99 community_follower::table.on(
101 .eq(community_follower::community_id)
102 .and(community_follower::person_id.eq(person_id_join)),
106 post_saved::table.on(
108 .eq(post_saved::post_id)
109 .and(post_saved::person_id.eq(person_id_join)),
115 .eq(post_read::post_id)
116 .and(post_read::person_id.eq(person_id_join)),
120 person_block::table.on(
122 .eq(person_block::target_id)
123 .and(person_block::person_id.eq(person_id_join)),
129 .eq(post_like::post_id)
130 .and(post_like::person_id.eq(person_id_join)),
135 Person::safe_columns_tuple(),
136 Community::safe_columns_tuple(),
137 community_person_ban::all_columns.nullable(),
138 post_aggregates::all_columns,
139 community_follower::all_columns.nullable(),
140 post_saved::all_columns.nullable(),
141 post_read::all_columns.nullable(),
142 person_block::all_columns.nullable(),
143 post_like::score.nullable(),
145 .first::<PostViewTuple>(conn)?;
147 // If a person is given, then my_vote, if None, should be 0, not null
148 // Necessary to differentiate between other person's votes
149 let my_vote = if my_person_id.is_some() && post_like.is_none() {
159 creator_banned_from_community: creator_banned_from_community.is_some(),
161 subscribed: follower.is_some(),
162 saved: saved.is_some(),
163 read: read.is_some(),
164 creator_blocked: creator_blocked.is_some(),
170 pub struct PostQueryBuilder<'a> {
171 conn: &'a PgConnection,
172 listing_type: Option<ListingType>,
173 sort: Option<SortType>,
174 creator_id: Option<PersonId>,
175 community_id: Option<CommunityId>,
176 community_actor_id: Option<DbUrl>,
177 my_person_id: Option<PersonId>,
178 search_term: Option<String>,
179 url_search: Option<String>,
180 show_nsfw: Option<bool>,
181 show_bot_accounts: Option<bool>,
182 show_read_posts: Option<bool>,
183 saved_only: Option<bool>,
188 impl<'a> PostQueryBuilder<'a> {
189 pub fn create(conn: &'a PgConnection) -> Self {
196 community_actor_id: None,
201 show_bot_accounts: None,
202 show_read_posts: None,
209 pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
210 self.listing_type = listing_type.get_optional();
214 pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
215 self.sort = sort.get_optional();
219 pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
220 self.community_id = community_id.get_optional();
224 pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
225 self.my_person_id = my_person_id.get_optional();
229 pub fn community_actor_id<T: MaybeOptional<DbUrl>>(mut self, community_actor_id: T) -> Self {
230 self.community_actor_id = community_actor_id.get_optional();
234 pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
235 self.creator_id = creator_id.get_optional();
239 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
240 self.search_term = search_term.get_optional();
244 pub fn url_search<T: MaybeOptional<String>>(mut self, url_search: T) -> Self {
245 self.url_search = url_search.get_optional();
249 pub fn show_nsfw<T: MaybeOptional<bool>>(mut self, show_nsfw: T) -> Self {
250 self.show_nsfw = show_nsfw.get_optional();
254 pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
255 self.show_bot_accounts = show_bot_accounts.get_optional();
259 pub fn show_read_posts<T: MaybeOptional<bool>>(mut self, show_read_posts: T) -> Self {
260 self.show_read_posts = show_read_posts.get_optional();
264 pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
265 self.saved_only = saved_only.get_optional();
269 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
270 self.page = page.get_optional();
274 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
275 self.limit = limit.get_optional();
279 pub fn list(self) -> Result<Vec<PostView>, Error> {
282 // The left join below will return None in this case
283 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
285 let mut query = post::table
286 .inner_join(person::table)
287 .inner_join(community::table)
289 community_person_ban::table.on(
291 .eq(community_person_ban::community_id)
292 .and(community_person_ban::person_id.eq(post::creator_id))
294 community_person_ban::expires
296 .or(community_person_ban::expires.gt(now)),
300 .inner_join(post_aggregates::table)
302 community_follower::table.on(
304 .eq(community_follower::community_id)
305 .and(community_follower::person_id.eq(person_id_join)),
309 post_saved::table.on(
311 .eq(post_saved::post_id)
312 .and(post_saved::person_id.eq(person_id_join)),
318 .eq(post_read::post_id)
319 .and(post_read::person_id.eq(person_id_join)),
323 person_block::table.on(
325 .eq(person_block::target_id)
326 .and(person_block::person_id.eq(person_id_join)),
330 community_block::table.on(
332 .eq(community_block::community_id)
333 .and(community_block::person_id.eq(person_id_join)),
339 .eq(post_like::post_id)
340 .and(post_like::person_id.eq(person_id_join)),
345 Person::safe_columns_tuple(),
346 Community::safe_columns_tuple(),
347 community_person_ban::all_columns.nullable(),
348 post_aggregates::all_columns,
349 community_follower::all_columns.nullable(),
350 post_saved::all_columns.nullable(),
351 post_read::all_columns.nullable(),
352 person_block::all_columns.nullable(),
353 post_like::score.nullable(),
357 if let Some(listing_type) = self.listing_type {
358 query = match listing_type {
359 ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()),
360 ListingType::Local => query.filter(community::local.eq(true)),
365 if let Some(community_id) = self.community_id {
367 .filter(post::community_id.eq(community_id))
368 .then_order_by(post_aggregates::stickied.desc());
371 if let Some(community_actor_id) = self.community_actor_id {
373 .filter(community::actor_id.eq(community_actor_id))
374 .then_order_by(post_aggregates::stickied.desc());
377 if let Some(url_search) = self.url_search {
378 query = query.filter(post::url.eq(url_search));
381 if let Some(search_term) = self.search_term {
382 let searcher = fuzzy_search(&search_term);
383 query = query.filter(
385 .ilike(searcher.to_owned())
386 .or(post::body.ilike(searcher)),
390 // If its for a specific person, show the removed / deleted
391 if let Some(creator_id) = self.creator_id {
392 query = query.filter(post::creator_id.eq(creator_id));
395 if !self.show_nsfw.unwrap_or(false) {
397 .filter(post::nsfw.eq(false))
398 .filter(community::nsfw.eq(false));
401 if !self.show_bot_accounts.unwrap_or(true) {
402 query = query.filter(person::bot_account.eq(false));
405 if self.saved_only.unwrap_or(false) {
406 query = query.filter(post_saved::id.is_not_null());
408 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
409 // setting wont be able to see saved posts.
410 else if !self.show_read_posts.unwrap_or(true) {
411 query = query.filter(post_read::id.is_null());
414 // Don't show blocked communities or persons
415 if self.my_person_id.is_some() {
416 query = query.filter(community_block::person_id.is_null());
417 query = query.filter(person_block::person_id.is_null());
420 query = match self.sort.unwrap_or(SortType::Hot) {
421 SortType::Active => query
424 post_aggregates::score,
425 post_aggregates::newest_comment_time_necro,
429 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
430 SortType::Hot => query
431 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
432 .then_order_by(post_aggregates::published.desc()),
433 SortType::New => query.then_order_by(post_aggregates::published.desc()),
434 SortType::MostComments => query.then_order_by(post_aggregates::comments.desc()),
435 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
436 SortType::TopAll => query.then_order_by(post_aggregates::score.desc()),
437 SortType::TopYear => query
438 .filter(post::published.gt(now - 1.years()))
439 .then_order_by(post_aggregates::score.desc()),
440 SortType::TopMonth => query
441 .filter(post::published.gt(now - 1.months()))
442 .then_order_by(post_aggregates::score.desc()),
443 SortType::TopWeek => query
444 .filter(post::published.gt(now - 1.weeks()))
445 .then_order_by(post_aggregates::score.desc()),
446 SortType::TopDay => query
447 .filter(post::published.gt(now - 1.days()))
448 .then_order_by(post_aggregates::score.desc()),
451 let (limit, offset) = limit_and_offset(self.page, self.limit);
456 .filter(post::removed.eq(false))
457 .filter(post::deleted.eq(false))
458 .filter(community::removed.eq(false))
459 .filter(community::deleted.eq(false));
461 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
463 let res = query.load::<PostViewTuple>(self.conn)?;
465 Ok(PostView::from_tuple_to_vec(res))
469 impl ViewToVec for PostView {
470 type DbTuple = PostViewTuple;
471 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
475 post: a.0.to_owned(),
476 creator: a.1.to_owned(),
477 community: a.2.to_owned(),
478 creator_banned_from_community: a.3.is_some(),
479 counts: a.4.to_owned(),
480 subscribed: a.5.is_some(),
481 saved: a.6.is_some(),
483 creator_blocked: a.8.is_some(),
486 .collect::<Vec<Self>>()
492 use crate::post_view::{PostQueryBuilder, PostView};
493 use lemmy_db_schema::{
494 aggregates::post_aggregates::PostAggregates,
495 establish_unpooled_connection,
498 community_block::{CommunityBlock, CommunityBlockForm},
500 person_block::{PersonBlock, PersonBlockForm},
503 traits::{Blockable, Crud, Likeable},
507 use serial_test::serial;
512 let conn = establish_unpooled_connection();
514 let person_name = "tegan".to_string();
515 let community_name = "test_community_3".to_string();
516 let post_name = "test post 3".to_string();
517 let bot_post_name = "test bot post".to_string();
519 let new_person = PersonForm {
520 name: person_name.to_owned(),
521 ..PersonForm::default()
524 let inserted_person = Person::create(&conn, &new_person).unwrap();
526 let new_bot = PersonForm {
527 name: person_name.to_owned(),
528 bot_account: Some(true),
529 ..PersonForm::default()
532 let inserted_bot = Person::create(&conn, &new_bot).unwrap();
534 let new_community = CommunityForm {
535 name: community_name.to_owned(),
536 title: "nada".to_owned(),
537 ..CommunityForm::default()
540 let inserted_community = Community::create(&conn, &new_community).unwrap();
542 // Test a person block, make sure the post query doesn't include their post
543 let blocked_person = PersonForm {
544 name: person_name.to_owned(),
545 ..PersonForm::default()
548 let inserted_blocked_person = Person::create(&conn, &blocked_person).unwrap();
550 let post_from_blocked_person = PostForm {
551 name: "blocked_person_post".to_string(),
552 creator_id: inserted_blocked_person.id,
553 community_id: inserted_community.id,
554 ..PostForm::default()
557 Post::create(&conn, &post_from_blocked_person).unwrap();
560 let person_block = PersonBlockForm {
561 person_id: inserted_person.id,
562 target_id: inserted_blocked_person.id,
565 PersonBlock::block(&conn, &person_block).unwrap();
568 let new_post = PostForm {
569 name: post_name.to_owned(),
570 creator_id: inserted_person.id,
571 community_id: inserted_community.id,
572 ..PostForm::default()
575 let inserted_post = Post::create(&conn, &new_post).unwrap();
577 let new_bot_post = PostForm {
579 creator_id: inserted_bot.id,
580 community_id: inserted_community.id,
581 ..PostForm::default()
584 let _inserted_bot_post = Post::create(&conn, &new_bot_post).unwrap();
586 let post_like_form = PostLikeForm {
587 post_id: inserted_post.id,
588 person_id: inserted_person.id,
592 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
594 let expected_post_like = PostLike {
595 id: inserted_post_like.id,
596 post_id: inserted_post.id,
597 person_id: inserted_person.id,
598 published: inserted_post_like.published,
602 let read_post_listings_with_person = PostQueryBuilder::create(&conn)
603 .listing_type(ListingType::Community)
605 .show_bot_accounts(false)
606 .community_id(inserted_community.id)
607 .my_person_id(inserted_person.id)
611 let read_post_listings_no_person = PostQueryBuilder::create(&conn)
612 .listing_type(ListingType::Community)
614 .community_id(inserted_community.id)
618 let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
619 let read_post_listing_with_person =
620 PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
622 let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
624 // the non person version
625 let expected_post_listing_no_person = PostView {
627 id: inserted_post.id,
629 creator_id: inserted_person.id,
632 published: inserted_post.published,
634 community_id: inserted_community.id,
641 embed_description: None,
644 ap_id: inserted_post.ap_id.to_owned(),
648 creator: PersonSafe {
649 id: inserted_person.id,
652 published: inserted_person.published,
654 actor_id: inserted_person.actor_id.to_owned(),
663 inbox_url: inserted_person.inbox_url.to_owned(),
664 shared_inbox_url: None,
665 matrix_user_id: None,
668 creator_banned_from_community: false,
669 community: CommunitySafe {
670 id: inserted_community.id,
671 name: community_name,
676 actor_id: inserted_community.actor_id.to_owned(),
678 title: "nada".to_owned(),
682 published: inserted_community.published,
684 counts: PostAggregates {
686 post_id: inserted_post.id,
692 published: agg.published,
693 newest_comment_time_necro: inserted_post.published,
694 newest_comment_time: inserted_post.published,
699 creator_blocked: false,
702 // Test a community block
703 let community_block = CommunityBlockForm {
704 person_id: inserted_person.id,
705 community_id: inserted_community.id,
707 CommunityBlock::block(&conn, &community_block).unwrap();
709 let read_post_listings_with_person_after_block = PostQueryBuilder::create(&conn)
710 .listing_type(ListingType::Community)
712 .show_bot_accounts(false)
713 .community_id(inserted_community.id)
714 .my_person_id(inserted_person.id)
718 // TODO More needs to be added here
719 let mut expected_post_listing_with_user = expected_post_listing_no_person.to_owned();
720 expected_post_listing_with_user.my_vote = Some(1);
722 let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
723 let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
724 PersonBlock::unblock(&conn, &person_block).unwrap();
725 CommunityBlock::unblock(&conn, &community_block).unwrap();
726 Community::delete(&conn, inserted_community.id).unwrap();
727 Person::delete(&conn, inserted_person.id).unwrap();
728 Person::delete(&conn, inserted_bot.id).unwrap();
729 Person::delete(&conn, inserted_blocked_person.id).unwrap();
733 expected_post_listing_with_user,
734 read_post_listings_with_person[0]
737 expected_post_listing_with_user,
738 read_post_listing_with_person
741 // Should be only one person, IE the bot post, and blocked should be missing
742 assert_eq!(1, read_post_listings_with_person.len());
746 expected_post_listing_no_person,
747 read_post_listings_no_person[1]
749 assert_eq!(expected_post_listing_no_person, read_post_listing_no_person);
751 // Should be 2 posts, with the bot post, and the blocked
752 assert_eq!(3, read_post_listings_no_person.len());
754 // Should be 0 posts after the community block
755 assert_eq!(0, read_post_listings_with_person_after_block.len());
757 assert_eq!(expected_post_like, inserted_post_like);
758 assert_eq!(1, like_removed);
759 assert_eq!(1, num_deleted);