1 use diesel::{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)),
92 .inner_join(post_aggregates::table)
94 community_follower::table.on(
96 .eq(community_follower::community_id)
97 .and(community_follower::person_id.eq(person_id_join)),
101 post_saved::table.on(
103 .eq(post_saved::post_id)
104 .and(post_saved::person_id.eq(person_id_join)),
110 .eq(post_read::post_id)
111 .and(post_read::person_id.eq(person_id_join)),
115 person_block::table.on(
117 .eq(person_block::target_id)
118 .and(person_block::person_id.eq(person_id_join)),
124 .eq(post_like::post_id)
125 .and(post_like::person_id.eq(person_id_join)),
130 Person::safe_columns_tuple(),
131 Community::safe_columns_tuple(),
132 community_person_ban::all_columns.nullable(),
133 post_aggregates::all_columns,
134 community_follower::all_columns.nullable(),
135 post_saved::all_columns.nullable(),
136 post_read::all_columns.nullable(),
137 person_block::all_columns.nullable(),
138 post_like::score.nullable(),
140 .first::<PostViewTuple>(conn)?;
142 // If a person is given, then my_vote, if None, should be 0, not null
143 // Necessary to differentiate between other person's votes
144 let my_vote = if my_person_id.is_some() && post_like.is_none() {
154 creator_banned_from_community: creator_banned_from_community.is_some(),
156 subscribed: follower.is_some(),
157 saved: saved.is_some(),
158 read: read.is_some(),
159 creator_blocked: creator_blocked.is_some(),
165 pub struct PostQueryBuilder<'a> {
166 conn: &'a PgConnection,
167 listing_type: Option<ListingType>,
168 sort: Option<SortType>,
169 creator_id: Option<PersonId>,
170 community_id: Option<CommunityId>,
171 community_actor_id: Option<DbUrl>,
172 my_person_id: Option<PersonId>,
173 search_term: Option<String>,
174 url_search: Option<String>,
175 show_nsfw: Option<bool>,
176 show_bot_accounts: Option<bool>,
177 show_read_posts: Option<bool>,
178 saved_only: Option<bool>,
183 impl<'a> PostQueryBuilder<'a> {
184 pub fn create(conn: &'a PgConnection) -> Self {
191 community_actor_id: None,
196 show_bot_accounts: None,
197 show_read_posts: None,
204 pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
205 self.listing_type = listing_type.get_optional();
209 pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
210 self.sort = sort.get_optional();
214 pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
215 self.community_id = community_id.get_optional();
219 pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
220 self.my_person_id = my_person_id.get_optional();
224 pub fn community_actor_id<T: MaybeOptional<DbUrl>>(mut self, community_actor_id: T) -> Self {
225 self.community_actor_id = community_actor_id.get_optional();
229 pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
230 self.creator_id = creator_id.get_optional();
234 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
235 self.search_term = search_term.get_optional();
239 pub fn url_search<T: MaybeOptional<String>>(mut self, url_search: T) -> Self {
240 self.url_search = url_search.get_optional();
244 pub fn show_nsfw<T: MaybeOptional<bool>>(mut self, show_nsfw: T) -> Self {
245 self.show_nsfw = show_nsfw.get_optional();
249 pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
250 self.show_bot_accounts = show_bot_accounts.get_optional();
254 pub fn show_read_posts<T: MaybeOptional<bool>>(mut self, show_read_posts: T) -> Self {
255 self.show_read_posts = show_read_posts.get_optional();
259 pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
260 self.saved_only = saved_only.get_optional();
264 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
265 self.page = page.get_optional();
269 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
270 self.limit = limit.get_optional();
274 pub fn list(self) -> Result<Vec<PostView>, Error> {
277 // The left join below will return None in this case
278 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
280 let mut query = post::table
281 .inner_join(person::table)
282 .inner_join(community::table)
284 community_person_ban::table.on(
286 .eq(community_person_ban::community_id)
287 .and(community_person_ban::person_id.eq(post::creator_id)),
290 .inner_join(post_aggregates::table)
292 community_follower::table.on(
294 .eq(community_follower::community_id)
295 .and(community_follower::person_id.eq(person_id_join)),
299 post_saved::table.on(
301 .eq(post_saved::post_id)
302 .and(post_saved::person_id.eq(person_id_join)),
308 .eq(post_read::post_id)
309 .and(post_read::person_id.eq(person_id_join)),
313 person_block::table.on(
315 .eq(person_block::target_id)
316 .and(person_block::person_id.eq(person_id_join)),
320 community_block::table.on(
322 .eq(community_block::community_id)
323 .and(community_block::person_id.eq(person_id_join)),
329 .eq(post_like::post_id)
330 .and(post_like::person_id.eq(person_id_join)),
335 Person::safe_columns_tuple(),
336 Community::safe_columns_tuple(),
337 community_person_ban::all_columns.nullable(),
338 post_aggregates::all_columns,
339 community_follower::all_columns.nullable(),
340 post_saved::all_columns.nullable(),
341 post_read::all_columns.nullable(),
342 person_block::all_columns.nullable(),
343 post_like::score.nullable(),
347 if let Some(listing_type) = self.listing_type {
348 query = match listing_type {
349 ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()),
350 ListingType::Local => query.filter(community::local.eq(true)),
355 if let Some(community_id) = self.community_id {
357 .filter(post::community_id.eq(community_id))
358 .then_order_by(post_aggregates::stickied.desc());
361 if let Some(community_actor_id) = self.community_actor_id {
363 .filter(community::actor_id.eq(community_actor_id))
364 .then_order_by(post_aggregates::stickied.desc());
367 if let Some(url_search) = self.url_search {
368 query = query.filter(post::url.eq(url_search));
371 if let Some(search_term) = self.search_term {
372 let searcher = fuzzy_search(&search_term);
373 query = query.filter(
375 .ilike(searcher.to_owned())
376 .or(post::body.ilike(searcher)),
380 // If its for a specific person, show the removed / deleted
381 if let Some(creator_id) = self.creator_id {
382 query = query.filter(post::creator_id.eq(creator_id));
385 if !self.show_nsfw.unwrap_or(false) {
387 .filter(post::nsfw.eq(false))
388 .filter(community::nsfw.eq(false));
391 if !self.show_bot_accounts.unwrap_or(true) {
392 query = query.filter(person::bot_account.eq(false));
395 if self.saved_only.unwrap_or(false) {
396 query = query.filter(post_saved::id.is_not_null());
398 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
399 // setting wont be able to see saved posts.
400 else if !self.show_read_posts.unwrap_or(true) {
401 query = query.filter(post_read::id.is_null());
404 // Don't show blocked communities or persons
405 if self.my_person_id.is_some() {
406 query = query.filter(community_block::person_id.is_null());
407 query = query.filter(person_block::person_id.is_null());
410 query = match self.sort.unwrap_or(SortType::Hot) {
411 SortType::Active => query
414 post_aggregates::score,
415 post_aggregates::newest_comment_time_necro,
419 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
420 SortType::Hot => query
421 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
422 .then_order_by(post_aggregates::published.desc()),
423 SortType::New => query.then_order_by(post_aggregates::published.desc()),
424 SortType::MostComments => query.then_order_by(post_aggregates::comments.desc()),
425 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
426 SortType::TopAll => query.then_order_by(post_aggregates::score.desc()),
427 SortType::TopYear => query
428 .filter(post::published.gt(now - 1.years()))
429 .then_order_by(post_aggregates::score.desc()),
430 SortType::TopMonth => query
431 .filter(post::published.gt(now - 1.months()))
432 .then_order_by(post_aggregates::score.desc()),
433 SortType::TopWeek => query
434 .filter(post::published.gt(now - 1.weeks()))
435 .then_order_by(post_aggregates::score.desc()),
436 SortType::TopDay => query
437 .filter(post::published.gt(now - 1.days()))
438 .then_order_by(post_aggregates::score.desc()),
441 let (limit, offset) = limit_and_offset(self.page, self.limit);
446 .filter(post::removed.eq(false))
447 .filter(post::deleted.eq(false))
448 .filter(community::removed.eq(false))
449 .filter(community::deleted.eq(false));
451 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
453 let res = query.load::<PostViewTuple>(self.conn)?;
455 Ok(PostView::from_tuple_to_vec(res))
459 impl ViewToVec for PostView {
460 type DbTuple = PostViewTuple;
461 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
465 post: a.0.to_owned(),
466 creator: a.1.to_owned(),
467 community: a.2.to_owned(),
468 creator_banned_from_community: a.3.is_some(),
469 counts: a.4.to_owned(),
470 subscribed: a.5.is_some(),
471 saved: a.6.is_some(),
473 creator_blocked: a.8.is_some(),
476 .collect::<Vec<Self>>()
482 use crate::post_view::{PostQueryBuilder, PostView};
483 use lemmy_db_schema::{
484 aggregates::post_aggregates::PostAggregates,
485 establish_unpooled_connection,
488 community_block::{CommunityBlock, CommunityBlockForm},
490 person_block::{PersonBlock, PersonBlockForm},
493 traits::{Blockable, Crud, Likeable},
497 use serial_test::serial;
502 let conn = establish_unpooled_connection();
504 let person_name = "tegan".to_string();
505 let community_name = "test_community_3".to_string();
506 let post_name = "test post 3".to_string();
507 let bot_post_name = "test bot post".to_string();
509 let new_person = PersonForm {
510 name: person_name.to_owned(),
511 ..PersonForm::default()
514 let inserted_person = Person::create(&conn, &new_person).unwrap();
516 let new_bot = PersonForm {
517 name: person_name.to_owned(),
518 bot_account: Some(true),
519 ..PersonForm::default()
522 let inserted_bot = Person::create(&conn, &new_bot).unwrap();
524 let new_community = CommunityForm {
525 name: community_name.to_owned(),
526 title: "nada".to_owned(),
527 ..CommunityForm::default()
530 let inserted_community = Community::create(&conn, &new_community).unwrap();
532 // Test a person block, make sure the post query doesn't include their post
533 let blocked_person = PersonForm {
534 name: person_name.to_owned(),
535 ..PersonForm::default()
538 let inserted_blocked_person = Person::create(&conn, &blocked_person).unwrap();
540 let post_from_blocked_person = PostForm {
541 name: "blocked_person_post".to_string(),
542 creator_id: inserted_blocked_person.id,
543 community_id: inserted_community.id,
544 ..PostForm::default()
547 Post::create(&conn, &post_from_blocked_person).unwrap();
550 let person_block = PersonBlockForm {
551 person_id: inserted_person.id,
552 target_id: inserted_blocked_person.id,
555 PersonBlock::block(&conn, &person_block).unwrap();
558 let new_post = PostForm {
559 name: post_name.to_owned(),
560 creator_id: inserted_person.id,
561 community_id: inserted_community.id,
562 ..PostForm::default()
565 let inserted_post = Post::create(&conn, &new_post).unwrap();
567 let new_bot_post = PostForm {
569 creator_id: inserted_bot.id,
570 community_id: inserted_community.id,
571 ..PostForm::default()
574 let _inserted_bot_post = Post::create(&conn, &new_bot_post).unwrap();
576 let post_like_form = PostLikeForm {
577 post_id: inserted_post.id,
578 person_id: inserted_person.id,
582 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
584 let expected_post_like = PostLike {
585 id: inserted_post_like.id,
586 post_id: inserted_post.id,
587 person_id: inserted_person.id,
588 published: inserted_post_like.published,
592 let read_post_listings_with_person = PostQueryBuilder::create(&conn)
593 .listing_type(ListingType::Community)
595 .show_bot_accounts(false)
596 .community_id(inserted_community.id)
597 .my_person_id(inserted_person.id)
601 let read_post_listings_no_person = PostQueryBuilder::create(&conn)
602 .listing_type(ListingType::Community)
604 .community_id(inserted_community.id)
608 let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
609 let read_post_listing_with_person =
610 PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
612 let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
614 // the non person version
615 let expected_post_listing_no_person = PostView {
617 id: inserted_post.id,
619 creator_id: inserted_person.id,
622 published: inserted_post.published,
624 community_id: inserted_community.id,
631 embed_description: None,
634 ap_id: inserted_post.ap_id.to_owned(),
638 creator: PersonSafe {
639 id: inserted_person.id,
642 published: inserted_person.published,
644 actor_id: inserted_person.actor_id.to_owned(),
653 inbox_url: inserted_person.inbox_url.to_owned(),
654 shared_inbox_url: None,
655 matrix_user_id: None,
657 creator_banned_from_community: false,
658 community: CommunitySafe {
659 id: inserted_community.id,
660 name: community_name,
665 actor_id: inserted_community.actor_id.to_owned(),
667 title: "nada".to_owned(),
671 published: inserted_community.published,
673 counts: PostAggregates {
675 post_id: inserted_post.id,
681 published: agg.published,
682 newest_comment_time_necro: inserted_post.published,
683 newest_comment_time: inserted_post.published,
688 creator_blocked: false,
691 // Test a community block
692 let community_block = CommunityBlockForm {
693 person_id: inserted_person.id,
694 community_id: inserted_community.id,
696 CommunityBlock::block(&conn, &community_block).unwrap();
698 let read_post_listings_with_person_after_block = PostQueryBuilder::create(&conn)
699 .listing_type(ListingType::Community)
701 .show_bot_accounts(false)
702 .community_id(inserted_community.id)
703 .my_person_id(inserted_person.id)
707 // TODO More needs to be added here
708 let mut expected_post_listing_with_user = expected_post_listing_no_person.to_owned();
709 expected_post_listing_with_user.my_vote = Some(1);
711 let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
712 let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
713 PersonBlock::unblock(&conn, &person_block).unwrap();
714 CommunityBlock::unblock(&conn, &community_block).unwrap();
715 Community::delete(&conn, inserted_community.id).unwrap();
716 Person::delete(&conn, inserted_person.id).unwrap();
717 Person::delete(&conn, inserted_bot.id).unwrap();
718 Person::delete(&conn, inserted_blocked_person.id).unwrap();
722 expected_post_listing_with_user,
723 read_post_listings_with_person[0]
726 expected_post_listing_with_user,
727 read_post_listing_with_person
730 // Should be only one person, IE the bot post, and blocked should be missing
731 assert_eq!(1, read_post_listings_with_person.len());
735 expected_post_listing_no_person,
736 read_post_listings_no_person[1]
738 assert_eq!(expected_post_listing_no_person, read_post_listing_no_person);
740 // Should be 2 posts, with the bot post, and the blocked
741 assert_eq!(3, read_post_listings_no_person.len());
743 // Should be 0 posts after the community block
744 assert_eq!(0, read_post_listings_with_person_after_block.len());
746 assert_eq!(expected_post_like, inserted_post_like);
747 assert_eq!(1, like_removed);
748 assert_eq!(1, num_deleted);