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},
39 use serde::{Deserialize, Serialize};
41 #[derive(Debug, PartialEq, Serialize, Deserialize, 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.saved_only.unwrap_or(false) {
403 query = query.filter(post_saved::id.is_not_null());
405 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
406 // setting wont be able to see saved posts.
407 else if !self.show_read_posts.unwrap_or(true) {
408 query = query.filter(post_read::id.is_null());
411 // Don't show blocked communities or persons
412 if self.my_person_id.is_some() {
413 query = query.filter(community_block::person_id.is_null());
414 query = query.filter(person_block::person_id.is_null());
417 query = match self.sort.unwrap_or(SortType::Hot) {
418 SortType::Active => query
421 post_aggregates::score,
422 post_aggregates::newest_comment_time_necro,
426 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
427 SortType::Hot => query
428 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
429 .then_order_by(post_aggregates::published.desc()),
430 SortType::New => query.then_order_by(post_aggregates::published.desc()),
431 SortType::MostComments => query.then_order_by(post_aggregates::comments.desc()),
432 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
433 SortType::TopAll => query.then_order_by(post_aggregates::score.desc()),
434 SortType::TopYear => query
435 .filter(post::published.gt(now - 1.years()))
436 .then_order_by(post_aggregates::score.desc()),
437 SortType::TopMonth => query
438 .filter(post::published.gt(now - 1.months()))
439 .then_order_by(post_aggregates::score.desc()),
440 SortType::TopWeek => query
441 .filter(post::published.gt(now - 1.weeks()))
442 .then_order_by(post_aggregates::score.desc()),
443 SortType::TopDay => query
444 .filter(post::published.gt(now - 1.days()))
445 .then_order_by(post_aggregates::score.desc()),
448 let (limit, offset) = limit_and_offset(self.page, self.limit);
453 .filter(post::removed.eq(false))
454 .filter(post::deleted.eq(false))
455 .filter(community::removed.eq(false))
456 .filter(community::deleted.eq(false));
458 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
460 let res = query.load::<PostViewTuple>(self.conn)?;
462 Ok(PostView::from_tuple_to_vec(res))
466 impl ViewToVec for PostView {
467 type DbTuple = PostViewTuple;
468 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
472 post: a.0.to_owned(),
473 creator: a.1.to_owned(),
474 community: a.2.to_owned(),
475 creator_banned_from_community: a.3.is_some(),
476 counts: a.4.to_owned(),
477 subscribed: a.5.is_some(),
478 saved: a.6.is_some(),
480 creator_blocked: a.8.is_some(),
483 .collect::<Vec<Self>>()
489 use crate::post_view::{PostQueryBuilder, PostView};
490 use lemmy_db_queries::{
491 aggregates::post_aggregates::PostAggregates,
492 establish_unpooled_connection,
499 use lemmy_db_schema::source::{
501 community_block::{CommunityBlock, CommunityBlockForm},
503 person_block::{PersonBlock, PersonBlockForm},
506 use serial_test::serial;
511 let conn = establish_unpooled_connection();
513 let person_name = "tegan".to_string();
514 let community_name = "test_community_3".to_string();
515 let post_name = "test post 3".to_string();
516 let bot_post_name = "test bot post".to_string();
518 let new_person = PersonForm {
519 name: person_name.to_owned(),
520 ..PersonForm::default()
523 let inserted_person = Person::create(&conn, &new_person).unwrap();
525 let new_bot = PersonForm {
526 name: person_name.to_owned(),
527 bot_account: Some(true),
528 ..PersonForm::default()
531 let inserted_bot = Person::create(&conn, &new_bot).unwrap();
533 let new_community = CommunityForm {
534 name: community_name.to_owned(),
535 title: "nada".to_owned(),
536 ..CommunityForm::default()
539 let inserted_community = Community::create(&conn, &new_community).unwrap();
541 // Test a person block, make sure the post query doesn't include their post
542 let blocked_person = PersonForm {
543 name: person_name.to_owned(),
544 ..PersonForm::default()
547 let inserted_blocked_person = Person::create(&conn, &blocked_person).unwrap();
549 let post_from_blocked_person = PostForm {
550 name: "blocked_person_post".to_string(),
551 creator_id: inserted_blocked_person.id,
552 community_id: inserted_community.id,
553 ..PostForm::default()
556 Post::create(&conn, &post_from_blocked_person).unwrap();
559 let person_block = PersonBlockForm {
560 person_id: inserted_person.id,
561 target_id: inserted_blocked_person.id,
564 PersonBlock::block(&conn, &person_block).unwrap();
567 let new_post = PostForm {
568 name: post_name.to_owned(),
569 creator_id: inserted_person.id,
570 community_id: inserted_community.id,
571 ..PostForm::default()
574 let inserted_post = Post::create(&conn, &new_post).unwrap();
576 let new_bot_post = PostForm {
578 creator_id: inserted_bot.id,
579 community_id: inserted_community.id,
580 ..PostForm::default()
583 let _inserted_bot_post = Post::create(&conn, &new_bot_post).unwrap();
585 let post_like_form = PostLikeForm {
586 post_id: inserted_post.id,
587 person_id: inserted_person.id,
591 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
593 let expected_post_like = PostLike {
594 id: inserted_post_like.id,
595 post_id: inserted_post.id,
596 person_id: inserted_person.id,
597 published: inserted_post_like.published,
601 let read_post_listings_with_person = PostQueryBuilder::create(&conn)
602 .listing_type(ListingType::Community)
604 .show_bot_accounts(false)
605 .community_id(inserted_community.id)
606 .my_person_id(inserted_person.id)
610 let read_post_listings_no_person = PostQueryBuilder::create(&conn)
611 .listing_type(ListingType::Community)
613 .community_id(inserted_community.id)
617 let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
618 let read_post_listing_with_person =
619 PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
621 let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
623 // the non person version
624 let expected_post_listing_no_person = PostView {
626 id: inserted_post.id,
628 creator_id: inserted_person.id,
631 published: inserted_post.published,
633 community_id: inserted_community.id,
640 embed_description: None,
643 ap_id: inserted_post.ap_id.to_owned(),
647 creator: PersonSafe {
648 id: inserted_person.id,
651 published: inserted_person.published,
653 actor_id: inserted_person.actor_id.to_owned(),
662 inbox_url: inserted_person.inbox_url.to_owned(),
663 shared_inbox_url: None,
664 matrix_user_id: None,
666 creator_banned_from_community: false,
667 community: CommunitySafe {
668 id: inserted_community.id,
669 name: community_name,
674 actor_id: inserted_community.actor_id.to_owned(),
676 title: "nada".to_owned(),
680 published: inserted_community.published,
682 counts: PostAggregates {
684 post_id: inserted_post.id,
690 published: agg.published,
691 newest_comment_time_necro: inserted_post.published,
692 newest_comment_time: inserted_post.published,
697 creator_blocked: false,
700 // Test a community block
701 let community_block = CommunityBlockForm {
702 person_id: inserted_person.id,
703 community_id: inserted_community.id,
705 CommunityBlock::block(&conn, &community_block).unwrap();
707 let read_post_listings_with_person_after_block = PostQueryBuilder::create(&conn)
708 .listing_type(ListingType::Community)
710 .show_bot_accounts(false)
711 .community_id(inserted_community.id)
712 .my_person_id(inserted_person.id)
716 // TODO More needs to be added here
717 let mut expected_post_listing_with_user = expected_post_listing_no_person.to_owned();
718 expected_post_listing_with_user.my_vote = Some(1);
720 let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
721 let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
722 PersonBlock::unblock(&conn, &person_block).unwrap();
723 CommunityBlock::unblock(&conn, &community_block).unwrap();
724 Community::delete(&conn, inserted_community.id).unwrap();
725 Person::delete(&conn, inserted_person.id).unwrap();
726 Person::delete(&conn, inserted_bot.id).unwrap();
727 Person::delete(&conn, inserted_blocked_person.id).unwrap();
731 expected_post_listing_with_user,
732 read_post_listings_with_person[0]
735 expected_post_listing_with_user,
736 read_post_listing_with_person
739 // Should be only one person, IE the bot post, and blocked should be missing
740 assert_eq!(1, read_post_listings_with_person.len());
744 expected_post_listing_no_person,
745 read_post_listings_no_person[1]
747 assert_eq!(expected_post_listing_no_person, read_post_listing_no_person);
749 // Should be 2 posts, with the bot post, and the blocked
750 assert_eq!(3, read_post_listings_no_person.len());
752 // Should be 0 posts after the community block
753 assert_eq!(0, read_post_listings_with_person_after_block.len());
755 assert_eq!(expected_post_like, inserted_post_like);
756 assert_eq!(1, like_removed);
757 assert_eq!(1, num_deleted);