1 use diesel::{pg::Pg, result::Error, *};
2 use lemmy_db_queries::{
3 aggregates::post_aggregates::PostAggregates,
13 use lemmy_db_schema::{
26 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
27 person::{Person, PersonSafe},
28 post::{Post, PostRead, PostSaved},
37 #[derive(Debug, PartialEq, Serialize, Clone)]
40 pub creator: PersonSafe,
41 pub community: CommunitySafe,
42 pub creator_banned_from_community: bool, // Left Join to CommunityPersonBan
43 pub counts: PostAggregates,
44 pub subscribed: bool, // Left join to CommunityFollower
45 pub saved: bool, // Left join to PostSaved
46 pub read: bool, // Left join to PostRead
47 pub my_vote: Option<i16>, // Left join to PostLike
50 type PostViewTuple = (
54 Option<CommunityPersonBan>,
56 Option<CommunityFollower>,
66 my_person_id: Option<PersonId>,
67 ) -> Result<Self, Error> {
68 // The left join below will return None in this case
69 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
75 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)),
117 .eq(post_like::post_id)
118 .and(post_like::person_id.eq(person_id_join)),
123 Person::safe_columns_tuple(),
124 Community::safe_columns_tuple(),
125 community_person_ban::all_columns.nullable(),
126 post_aggregates::all_columns,
127 community_follower::all_columns.nullable(),
128 post_saved::all_columns.nullable(),
129 post_read::all_columns.nullable(),
130 post_like::score.nullable(),
132 .first::<PostViewTuple>(conn)?;
134 // If a person is given, then my_vote, if None, should be 0, not null
135 // Necessary to differentiate between other person's votes
136 let my_vote = if my_person_id.is_some() && post_like.is_none() {
146 creator_banned_from_community: creator_banned_from_community.is_some(),
148 subscribed: follower.is_some(),
149 saved: saved.is_some(),
150 read: read.is_some(),
156 pub struct PostQueryBuilder<'a> {
157 conn: &'a PgConnection,
158 listing_type: Option<ListingType>,
159 sort: Option<SortType>,
160 creator_id: Option<PersonId>,
161 community_id: Option<CommunityId>,
162 community_name: Option<String>,
163 my_person_id: Option<PersonId>,
164 search_term: Option<String>,
165 url_search: Option<String>,
166 show_nsfw: Option<bool>,
167 show_bot_accounts: Option<bool>,
168 saved_only: Option<bool>,
169 unread_only: Option<bool>,
174 impl<'a> PostQueryBuilder<'a> {
175 pub fn create(conn: &'a PgConnection) -> Self {
182 community_name: None,
187 show_bot_accounts: None,
195 pub fn listing_type<T: MaybeOptional<ListingType>>(mut self, listing_type: T) -> Self {
196 self.listing_type = listing_type.get_optional();
200 pub fn sort<T: MaybeOptional<SortType>>(mut self, sort: T) -> Self {
201 self.sort = sort.get_optional();
205 pub fn community_id<T: MaybeOptional<CommunityId>>(mut self, community_id: T) -> Self {
206 self.community_id = community_id.get_optional();
210 pub fn my_person_id<T: MaybeOptional<PersonId>>(mut self, my_person_id: T) -> Self {
211 self.my_person_id = my_person_id.get_optional();
215 pub fn community_name<T: MaybeOptional<String>>(mut self, community_name: T) -> Self {
216 self.community_name = community_name.get_optional();
220 pub fn creator_id<T: MaybeOptional<PersonId>>(mut self, creator_id: T) -> Self {
221 self.creator_id = creator_id.get_optional();
225 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
226 self.search_term = search_term.get_optional();
230 pub fn url_search<T: MaybeOptional<String>>(mut self, url_search: T) -> Self {
231 self.url_search = url_search.get_optional();
235 pub fn show_nsfw<T: MaybeOptional<bool>>(mut self, show_nsfw: T) -> Self {
236 self.show_nsfw = show_nsfw.get_optional();
240 pub fn show_bot_accounts<T: MaybeOptional<bool>>(mut self, show_bot_accounts: T) -> Self {
241 self.show_bot_accounts = show_bot_accounts;
245 pub fn saved_only<T: MaybeOptional<bool>>(mut self, saved_only: T) -> Self {
246 self.saved_only = saved_only.get_optional();
250 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
251 self.page = page.get_optional();
255 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
256 self.limit = limit.get_optional();
260 pub fn list(self) -> Result<Vec<PostView>, Error> {
263 // The left join below will return None in this case
264 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
266 let mut query = post::table
267 .inner_join(person::table)
268 .inner_join(community::table)
270 community_person_ban::table.on(
272 .eq(community_person_ban::community_id)
273 .and(community_person_ban::person_id.eq(post::creator_id)),
276 .inner_join(post_aggregates::table)
278 community_follower::table.on(
280 .eq(community_follower::community_id)
281 .and(community_follower::person_id.eq(person_id_join)),
285 post_saved::table.on(
287 .eq(post_saved::post_id)
288 .and(post_saved::person_id.eq(person_id_join)),
294 .eq(post_read::post_id)
295 .and(post_read::person_id.eq(person_id_join)),
301 .eq(post_like::post_id)
302 .and(post_like::person_id.eq(person_id_join)),
307 Person::safe_columns_tuple(),
308 Community::safe_columns_tuple(),
309 community_person_ban::all_columns.nullable(),
310 post_aggregates::all_columns,
311 community_follower::all_columns.nullable(),
312 post_saved::all_columns.nullable(),
313 post_read::all_columns.nullable(),
314 post_like::score.nullable(),
318 if let Some(listing_type) = self.listing_type {
319 query = match listing_type {
320 ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
321 ListingType::Local => query.filter(community::local.eq(true)),
326 if let Some(community_id) = self.community_id {
328 .filter(post::community_id.eq(community_id))
329 .then_order_by(post_aggregates::stickied.desc());
332 if let Some(community_name) = self.community_name {
334 .filter(community::name.eq(community_name))
335 .filter(community::local.eq(true))
336 .then_order_by(post_aggregates::stickied.desc());
339 if let Some(url_search) = self.url_search {
340 query = query.filter(post::url.eq(url_search));
343 if let Some(search_term) = self.search_term {
344 let searcher = fuzzy_search(&search_term);
345 query = query.filter(
347 .ilike(searcher.to_owned())
348 .or(post::body.ilike(searcher)),
352 // If its for a specific person, show the removed / deleted
353 if let Some(creator_id) = self.creator_id {
354 query = query.filter(post::creator_id.eq(creator_id));
357 if !self.show_nsfw.unwrap_or(true) {
359 .filter(post::nsfw.eq(false))
360 .filter(community::nsfw.eq(false));
363 if !self.show_bot_accounts {
364 query = query.filter(person::bot_account.eq(false));
367 // TODO These two might be wrong
368 if self.saved_only.unwrap_or_default() {
369 query = query.filter(post_saved::id.is_not_null());
372 if self.unread_only.unwrap_or_default() {
373 query = query.filter(post_read::id.is_not_null());
376 query = match self.sort.unwrap_or(SortType::Hot) {
377 SortType::Active => query
380 post_aggregates::score,
381 post_aggregates::newest_comment_time_necro,
385 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
386 SortType::Hot => query
387 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
388 .then_order_by(post_aggregates::published.desc()),
389 SortType::New => query.then_order_by(post_aggregates::published.desc()),
390 SortType::MostComments => query.then_order_by(post_aggregates::comments.desc()),
391 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
392 SortType::TopAll => query.then_order_by(post_aggregates::score.desc()),
393 SortType::TopYear => query
394 .filter(post::published.gt(now - 1.years()))
395 .then_order_by(post_aggregates::score.desc()),
396 SortType::TopMonth => query
397 .filter(post::published.gt(now - 1.months()))
398 .then_order_by(post_aggregates::score.desc()),
399 SortType::TopWeek => query
400 .filter(post::published.gt(now - 1.weeks()))
401 .then_order_by(post_aggregates::score.desc()),
402 SortType::TopDay => query
403 .filter(post::published.gt(now - 1.days()))
404 .then_order_by(post_aggregates::score.desc()),
407 let (limit, offset) = limit_and_offset(self.page, self.limit);
412 .filter(post::removed.eq(false))
413 .filter(post::deleted.eq(false))
414 .filter(community::removed.eq(false))
415 .filter(community::deleted.eq(false));
417 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
419 let res = query.load::<PostViewTuple>(self.conn)?;
421 Ok(PostView::from_tuple_to_vec(res))
425 impl ViewToVec for PostView {
426 type DbTuple = PostViewTuple;
427 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
431 post: a.0.to_owned(),
432 creator: a.1.to_owned(),
433 community: a.2.to_owned(),
434 creator_banned_from_community: a.3.is_some(),
435 counts: a.4.to_owned(),
436 subscribed: a.5.is_some(),
437 saved: a.6.is_some(),
441 .collect::<Vec<Self>>()
447 use crate::post_view::{PostQueryBuilder, PostView};
448 use lemmy_db_queries::{
449 aggregates::post_aggregates::PostAggregates,
450 establish_unpooled_connection,
456 use lemmy_db_schema::source::{community::*, person::*, post::*};
457 use serial_test::serial;
462 let conn = establish_unpooled_connection();
464 let person_name = "tegan".to_string();
465 let community_name = "test_community_3".to_string();
466 let post_name = "test post 3".to_string();
467 let bot_post_name = "test bot post".to_string();
469 let new_person = PersonForm {
470 name: person_name.to_owned(),
471 ..PersonForm::default()
474 let inserted_person = Person::create(&conn, &new_person).unwrap();
476 let new_bot = PersonForm {
477 name: person_name.to_owned(),
478 bot_account: Some(true),
479 ..PersonForm::default()
482 let inserted_bot = Person::create(&conn, &new_bot).unwrap();
484 let new_community = CommunityForm {
485 name: community_name.to_owned(),
486 title: "nada".to_owned(),
487 ..CommunityForm::default()
490 let inserted_community = Community::create(&conn, &new_community).unwrap();
492 let new_post = PostForm {
493 name: post_name.to_owned(),
494 creator_id: inserted_person.id,
495 community_id: inserted_community.id,
496 ..PostForm::default()
499 let inserted_post = Post::create(&conn, &new_post).unwrap();
501 let new_bot_post = PostForm {
503 creator_id: inserted_bot.id,
504 community_id: inserted_community.id,
505 ..PostForm::default()
508 let _inserted_bot_post = Post::create(&conn, &new_bot_post).unwrap();
510 let post_like_form = PostLikeForm {
511 post_id: inserted_post.id,
512 person_id: inserted_person.id,
516 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
518 let expected_post_like = PostLike {
519 id: inserted_post_like.id,
520 post_id: inserted_post.id,
521 person_id: inserted_person.id,
522 published: inserted_post_like.published,
526 let read_post_listings_with_person = PostQueryBuilder::create(&conn)
527 .listing_type(ListingType::Community)
529 .show_bot_accounts(false)
530 .community_id(inserted_community.id)
531 .my_person_id(inserted_person.id)
535 let read_post_listings_no_person = PostQueryBuilder::create(&conn)
536 .listing_type(ListingType::Community)
538 .community_id(inserted_community.id)
542 let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
543 let read_post_listing_with_person =
544 PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
546 let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
548 // the non person version
549 let expected_post_listing_no_person = PostView {
551 id: inserted_post.id,
553 creator_id: inserted_person.id,
556 published: inserted_post.published,
558 community_id: inserted_community.id,
565 embed_description: None,
568 ap_id: inserted_post.ap_id.to_owned(),
572 creator: PersonSafe {
573 id: inserted_person.id,
576 published: inserted_person.published,
578 actor_id: inserted_person.actor_id.to_owned(),
587 inbox_url: inserted_person.inbox_url.to_owned(),
588 shared_inbox_url: None,
589 matrix_user_id: None,
591 creator_banned_from_community: false,
592 community: CommunitySafe {
593 id: inserted_community.id,
594 name: community_name,
599 actor_id: inserted_community.actor_id.to_owned(),
601 title: "nada".to_owned(),
605 published: inserted_community.published,
607 counts: PostAggregates {
609 post_id: inserted_post.id,
615 published: agg.published,
616 newest_comment_time_necro: inserted_post.published,
617 newest_comment_time: inserted_post.published,
624 // TODO More needs to be added here
625 let mut expected_post_listing_with_user = expected_post_listing_no_person.to_owned();
626 expected_post_listing_with_user.my_vote = Some(1);
628 let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
629 let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
630 Community::delete(&conn, inserted_community.id).unwrap();
631 Person::delete(&conn, inserted_person.id).unwrap();
632 Person::delete(&conn, inserted_bot.id).unwrap();
636 expected_post_listing_with_user,
637 read_post_listings_with_person[0]
640 expected_post_listing_with_user,
641 read_post_listing_with_person
644 // Should be only one person, IE the bot post should be missing
645 assert_eq!(1, read_post_listings_with_person.len());
649 expected_post_listing_no_person,
650 read_post_listings_no_person[1]
652 assert_eq!(expected_post_listing_no_person, read_post_listing_no_person);
654 // Should be 2 posts, with the bot post
655 assert_eq!(2, read_post_listings_no_person.len());
657 assert_eq!(expected_post_like, inserted_post_like);
658 assert_eq!(1, like_removed);
659 assert_eq!(1, num_deleted);