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: follower.is_some(),
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 {
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)),
360 ListingType::Community => {
361 if let Some(community_id) = self.community_id {
363 .filter(post::community_id.eq(community_id))
364 .then_order_by(post_aggregates::stickied.desc());
370 if let Some(community_actor_id) = self.community_actor_id {
372 .filter(community::actor_id.eq(community_actor_id))
373 .then_order_by(post_aggregates::stickied.desc());
376 if let Some(url_search) = self.url_search {
377 query = query.filter(post::url.eq(url_search));
380 if let Some(search_term) = self.search_term {
381 let searcher = fuzzy_search(&search_term);
382 query = query.filter(
384 .ilike(searcher.to_owned())
385 .or(post::body.ilike(searcher)),
389 // If its for a specific person, show the removed / deleted
390 if let Some(creator_id) = self.creator_id {
391 query = query.filter(post::creator_id.eq(creator_id));
394 if !self.show_nsfw.unwrap_or(false) {
396 .filter(post::nsfw.eq(false))
397 .filter(community::nsfw.eq(false));
400 if !self.show_bot_accounts.unwrap_or(true) {
401 query = query.filter(person::bot_account.eq(false));
404 if self.saved_only.unwrap_or(false) {
405 query = query.filter(post_saved::id.is_not_null());
407 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
408 // setting wont be able to see saved posts.
409 else if !self.show_read_posts.unwrap_or(true) {
410 query = query.filter(post_read::id.is_null());
413 // Don't show blocked communities or persons
414 if self.my_person_id.is_some() {
415 query = query.filter(community_block::person_id.is_null());
416 query = query.filter(person_block::person_id.is_null());
419 query = match self.sort.unwrap_or(SortType::Hot) {
420 SortType::Active => query
423 post_aggregates::score,
424 post_aggregates::newest_comment_time_necro,
428 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
429 SortType::Hot => query
430 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
431 .then_order_by(post_aggregates::published.desc()),
432 SortType::New => query.then_order_by(post_aggregates::published.desc()),
433 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
434 SortType::MostComments => query
435 .then_order_by(post_aggregates::comments.desc())
436 .then_order_by(post_aggregates::published.desc()),
437 SortType::TopAll => query
438 .then_order_by(post_aggregates::score.desc())
439 .then_order_by(post_aggregates::published.desc()),
440 SortType::TopYear => query
441 .filter(post_aggregates::published.gt(now - 1.years()))
442 .then_order_by(post_aggregates::score.desc())
443 .then_order_by(post_aggregates::published.desc()),
444 SortType::TopMonth => query
445 .filter(post_aggregates::published.gt(now - 1.months()))
446 .then_order_by(post_aggregates::score.desc())
447 .then_order_by(post_aggregates::published.desc()),
448 SortType::TopWeek => query
449 .filter(post_aggregates::published.gt(now - 1.weeks()))
450 .then_order_by(post_aggregates::score.desc())
451 .then_order_by(post_aggregates::published.desc()),
452 SortType::TopDay => query
453 .filter(post_aggregates::published.gt(now - 1.days()))
454 .then_order_by(post_aggregates::score.desc())
455 .then_order_by(post_aggregates::published.desc()),
458 let (limit, offset) = limit_and_offset(self.page, self.limit);
463 .filter(post::removed.eq(false))
464 .filter(post::deleted.eq(false))
465 .filter(community::removed.eq(false))
466 .filter(community::deleted.eq(false));
468 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
470 let res = query.load::<PostViewTuple>(self.conn)?;
472 Ok(PostView::from_tuple_to_vec(res))
476 impl ViewToVec for PostView {
477 type DbTuple = PostViewTuple;
478 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
482 post: a.0.to_owned(),
483 creator: a.1.to_owned(),
484 community: a.2.to_owned(),
485 creator_banned_from_community: a.3.is_some(),
486 counts: a.4.to_owned(),
487 subscribed: a.5.is_some(),
488 saved: a.6.is_some(),
490 creator_blocked: a.8.is_some(),
493 .collect::<Vec<Self>>()
499 use crate::post_view::{PostQueryBuilder, PostView};
500 use lemmy_db_schema::{
501 aggregates::structs::PostAggregates,
504 community_block::{CommunityBlock, CommunityBlockForm},
506 person_block::{PersonBlock, PersonBlockForm},
509 traits::{Blockable, Crud, Likeable},
510 utils::establish_unpooled_connection,
514 use serial_test::serial;
519 let conn = establish_unpooled_connection();
521 let person_name = "tegan".to_string();
522 let community_name = "test_community_3".to_string();
523 let post_name = "test post 3".to_string();
524 let bot_post_name = "test bot post".to_string();
526 let new_person = PersonForm {
527 name: person_name.to_owned(),
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 ..PersonForm::default()
539 let inserted_bot = Person::create(&conn, &new_bot).unwrap();
541 let new_community = CommunityForm {
542 name: community_name.to_owned(),
543 title: "nada".to_owned(),
544 ..CommunityForm::default()
547 let inserted_community = Community::create(&conn, &new_community).unwrap();
549 // Test a person block, make sure the post query doesn't include their post
550 let blocked_person = PersonForm {
551 name: person_name.to_owned(),
552 ..PersonForm::default()
555 let inserted_blocked_person = Person::create(&conn, &blocked_person).unwrap();
557 let post_from_blocked_person = PostForm {
558 name: "blocked_person_post".to_string(),
559 creator_id: inserted_blocked_person.id,
560 community_id: inserted_community.id,
561 ..PostForm::default()
564 Post::create(&conn, &post_from_blocked_person).unwrap();
567 let person_block = PersonBlockForm {
568 person_id: inserted_person.id,
569 target_id: inserted_blocked_person.id,
572 PersonBlock::block(&conn, &person_block).unwrap();
575 let new_post = PostForm {
576 name: post_name.to_owned(),
577 creator_id: inserted_person.id,
578 community_id: inserted_community.id,
579 ..PostForm::default()
582 let inserted_post = Post::create(&conn, &new_post).unwrap();
584 let new_bot_post = PostForm {
586 creator_id: inserted_bot.id,
587 community_id: inserted_community.id,
588 ..PostForm::default()
591 let _inserted_bot_post = Post::create(&conn, &new_bot_post).unwrap();
593 let post_like_form = PostLikeForm {
594 post_id: inserted_post.id,
595 person_id: inserted_person.id,
599 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
601 let expected_post_like = PostLike {
602 id: inserted_post_like.id,
603 post_id: inserted_post.id,
604 person_id: inserted_person.id,
605 published: inserted_post_like.published,
609 let read_post_listings_with_person = PostQueryBuilder::create(&conn)
610 .listing_type(ListingType::Community)
612 .show_bot_accounts(false)
613 .community_id(inserted_community.id)
614 .my_person_id(inserted_person.id)
618 let read_post_listings_no_person = PostQueryBuilder::create(&conn)
619 .listing_type(ListingType::Community)
621 .community_id(inserted_community.id)
625 let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
626 let read_post_listing_with_person =
627 PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
629 let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
631 // the non person version
632 let expected_post_listing_no_person = PostView {
634 id: inserted_post.id,
636 creator_id: inserted_person.id,
639 published: inserted_post.published,
641 community_id: inserted_community.id,
648 embed_description: None,
651 ap_id: inserted_post.ap_id.to_owned(),
655 creator: PersonSafe {
656 id: inserted_person.id,
659 published: inserted_person.published,
661 actor_id: inserted_person.actor_id.to_owned(),
670 inbox_url: inserted_person.inbox_url.to_owned(),
671 shared_inbox_url: None,
672 matrix_user_id: None,
675 creator_banned_from_community: false,
676 community: CommunitySafe {
677 id: inserted_community.id,
678 name: community_name,
683 actor_id: inserted_community.actor_id.to_owned(),
685 title: "nada".to_owned(),
690 posting_restricted_to_mods: false,
691 published: inserted_community.published,
693 counts: PostAggregates {
695 post_id: inserted_post.id,
701 published: agg.published,
702 newest_comment_time_necro: inserted_post.published,
703 newest_comment_time: inserted_post.published,
708 creator_blocked: false,
711 // Test a community block
712 let community_block = CommunityBlockForm {
713 person_id: inserted_person.id,
714 community_id: inserted_community.id,
716 CommunityBlock::block(&conn, &community_block).unwrap();
718 let read_post_listings_with_person_after_block = PostQueryBuilder::create(&conn)
719 .listing_type(ListingType::Community)
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);