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},
34 #[derive(Debug, PartialEq, Serialize, 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 my_vote: Option<i16>, // Left join to PostLike
47 type PostViewTuple = (
51 Option<CommunityPersonBan>,
53 Option<CommunityFollower>,
60 pub fn read(conn: &PgConnection, post_id: i32, my_person_id: Option<i32>) -> Result<Self, Error> {
61 // The left join below will return None in this case
62 let person_id_join = my_person_id.unwrap_or(-1);
68 creator_banned_from_community,
76 .inner_join(person::table)
77 .inner_join(community::table)
79 community_person_ban::table.on(
81 .eq(community_person_ban::community_id)
82 .and(community_person_ban::person_id.eq(post::creator_id)),
85 .inner_join(post_aggregates::table)
87 community_follower::table.on(
89 .eq(community_follower::community_id)
90 .and(community_follower::person_id.eq(person_id_join)),
96 .eq(post_saved::post_id)
97 .and(post_saved::person_id.eq(person_id_join)),
103 .eq(post_read::post_id)
104 .and(post_read::person_id.eq(person_id_join)),
110 .eq(post_like::post_id)
111 .and(post_like::person_id.eq(person_id_join)),
116 Person::safe_columns_tuple(),
117 Community::safe_columns_tuple(),
118 community_person_ban::all_columns.nullable(),
119 post_aggregates::all_columns,
120 community_follower::all_columns.nullable(),
121 post_saved::all_columns.nullable(),
122 post_read::all_columns.nullable(),
123 post_like::score.nullable(),
125 .first::<PostViewTuple>(conn)?;
127 // If a person is given, then my_vote, if None, should be 0, not null
128 // Necessary to differentiate between other person's votes
129 let my_vote = if my_person_id.is_some() && post_like.is_none() {
139 creator_banned_from_community: creator_banned_from_community.is_some(),
141 subscribed: follower.is_some(),
142 saved: saved.is_some(),
143 read: read.is_some(),
149 pub struct PostQueryBuilder<'a> {
150 conn: &'a PgConnection,
151 listing_type: &'a ListingType,
153 creator_id: Option<i32>,
154 community_id: Option<i32>,
155 community_name: Option<String>,
156 my_person_id: Option<i32>,
157 search_term: Option<String>,
158 url_search: Option<String>,
166 impl<'a> PostQueryBuilder<'a> {
167 pub fn create(conn: &'a PgConnection) -> Self {
170 listing_type: &ListingType::All,
171 sort: &SortType::Hot,
174 community_name: None,
186 pub fn listing_type(mut self, listing_type: &'a ListingType) -> Self {
187 self.listing_type = listing_type;
191 pub fn sort(mut self, sort: &'a SortType) -> Self {
196 pub fn community_id<T: MaybeOptional<i32>>(mut self, community_id: T) -> Self {
197 self.community_id = community_id.get_optional();
201 pub fn my_person_id<T: MaybeOptional<i32>>(mut self, my_person_id: T) -> Self {
202 self.my_person_id = my_person_id.get_optional();
206 pub fn community_name<T: MaybeOptional<String>>(mut self, community_name: T) -> Self {
207 self.community_name = community_name.get_optional();
211 pub fn creator_id<T: MaybeOptional<i32>>(mut self, creator_id: T) -> Self {
212 self.creator_id = creator_id.get_optional();
216 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
217 self.search_term = search_term.get_optional();
221 pub fn url_search<T: MaybeOptional<String>>(mut self, url_search: T) -> Self {
222 self.url_search = url_search.get_optional();
226 pub fn show_nsfw(mut self, show_nsfw: bool) -> Self {
227 self.show_nsfw = show_nsfw;
231 pub fn saved_only(mut self, saved_only: bool) -> Self {
232 self.saved_only = saved_only;
236 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
237 self.page = page.get_optional();
241 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
242 self.limit = limit.get_optional();
246 pub fn list(self) -> Result<Vec<PostView>, Error> {
249 // The left join below will return None in this case
250 let person_id_join = self.my_person_id.unwrap_or(-1);
252 let mut query = post::table
253 .inner_join(person::table)
254 .inner_join(community::table)
256 community_person_ban::table.on(
258 .eq(community_person_ban::community_id)
259 .and(community_person_ban::person_id.eq(community::creator_id)),
262 .inner_join(post_aggregates::table)
264 community_follower::table.on(
266 .eq(community_follower::community_id)
267 .and(community_follower::person_id.eq(person_id_join)),
271 post_saved::table.on(
273 .eq(post_saved::post_id)
274 .and(post_saved::person_id.eq(person_id_join)),
280 .eq(post_read::post_id)
281 .and(post_read::person_id.eq(person_id_join)),
287 .eq(post_like::post_id)
288 .and(post_like::person_id.eq(person_id_join)),
293 Person::safe_columns_tuple(),
294 Community::safe_columns_tuple(),
295 community_person_ban::all_columns.nullable(),
296 post_aggregates::all_columns,
297 community_follower::all_columns.nullable(),
298 post_saved::all_columns.nullable(),
299 post_read::all_columns.nullable(),
300 post_like::score.nullable(),
304 query = match self.listing_type {
305 ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
306 ListingType::Local => query.filter(community::local.eq(true)),
310 if let Some(community_id) = self.community_id {
312 .filter(post::community_id.eq(community_id))
313 .then_order_by(post_aggregates::stickied.desc());
316 if let Some(community_name) = self.community_name {
318 .filter(community::name.eq(community_name))
319 .filter(community::local.eq(true))
320 .then_order_by(post_aggregates::stickied.desc());
323 if let Some(url_search) = self.url_search {
324 query = query.filter(post::url.eq(url_search));
327 if let Some(search_term) = self.search_term {
328 let searcher = fuzzy_search(&search_term);
329 query = query.filter(
331 .ilike(searcher.to_owned())
332 .or(post::body.ilike(searcher)),
336 // If its for a specific person, show the removed / deleted
337 if let Some(creator_id) = self.creator_id {
338 query = query.filter(post::creator_id.eq(creator_id));
343 .filter(post::nsfw.eq(false))
344 .filter(community::nsfw.eq(false));
347 // TODO These two might be wrong
349 query = query.filter(post_saved::id.is_not_null());
352 if self.unread_only {
353 query = query.filter(post_read::id.is_not_null());
356 query = match self.sort {
357 SortType::Active => query
360 post_aggregates::score,
361 post_aggregates::newest_comment_time_necro,
365 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
366 SortType::Hot => query
367 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
368 .then_order_by(post_aggregates::published.desc()),
369 SortType::New => query.then_order_by(post_aggregates::published.desc()),
370 SortType::MostComments => query.then_order_by(post_aggregates::comments.desc()),
371 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
372 SortType::TopAll => query.then_order_by(post_aggregates::score.desc()),
373 SortType::TopYear => query
374 .filter(post::published.gt(now - 1.years()))
375 .then_order_by(post_aggregates::score.desc()),
376 SortType::TopMonth => query
377 .filter(post::published.gt(now - 1.months()))
378 .then_order_by(post_aggregates::score.desc()),
379 SortType::TopWeek => query
380 .filter(post::published.gt(now - 1.weeks()))
381 .then_order_by(post_aggregates::score.desc()),
382 SortType::TopDay => query
383 .filter(post::published.gt(now - 1.days()))
384 .then_order_by(post_aggregates::score.desc()),
387 let (limit, offset) = limit_and_offset(self.page, self.limit);
392 .filter(post::removed.eq(false))
393 .filter(post::deleted.eq(false))
394 .filter(community::removed.eq(false))
395 .filter(community::deleted.eq(false));
397 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
399 let res = query.load::<PostViewTuple>(self.conn)?;
401 Ok(PostView::from_tuple_to_vec(res))
405 impl ViewToVec for PostView {
406 type DbTuple = PostViewTuple;
407 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
411 post: a.0.to_owned(),
412 creator: a.1.to_owned(),
413 community: a.2.to_owned(),
414 creator_banned_from_community: a.3.is_some(),
415 counts: a.4.to_owned(),
416 subscribed: a.5.is_some(),
417 saved: a.6.is_some(),
421 .collect::<Vec<Self>>()
427 use crate::post_view::{PostQueryBuilder, PostView};
428 use lemmy_db_queries::{
429 aggregates::post_aggregates::PostAggregates,
430 establish_unpooled_connection,
436 use lemmy_db_schema::source::{community::*, person::*, post::*};
437 use serial_test::serial;
442 let conn = establish_unpooled_connection();
444 let person_name = "tegan".to_string();
445 let community_name = "test_community_3".to_string();
446 let post_name = "test post 3".to_string();
448 let new_person = PersonForm {
449 name: person_name.to_owned(),
450 preferred_username: None,
462 last_refreshed_at: None,
464 shared_inbox_url: None,
467 let inserted_person = Person::create(&conn, &new_person).unwrap();
469 let new_community = CommunityForm {
470 name: community_name.to_owned(),
471 title: "nada".to_owned(),
473 creator_id: inserted_person.id,
482 last_refreshed_at: None,
488 shared_inbox_url: None,
491 let inserted_community = Community::create(&conn, &new_community).unwrap();
493 let new_post = PostForm {
494 name: post_name.to_owned(),
497 creator_id: inserted_person.id,
498 community_id: inserted_community.id,
506 embed_description: None,
514 let inserted_post = Post::create(&conn, &new_post).unwrap();
516 let post_like_form = PostLikeForm {
517 post_id: inserted_post.id,
518 person_id: inserted_person.id,
522 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
524 let expected_post_like = PostLike {
525 id: inserted_post_like.id,
526 post_id: inserted_post.id,
527 person_id: inserted_person.id,
528 published: inserted_post_like.published,
532 let read_post_listings_with_person = PostQueryBuilder::create(&conn)
533 .listing_type(&ListingType::Community)
534 .sort(&SortType::New)
535 .community_id(inserted_community.id)
536 .my_person_id(inserted_person.id)
540 let read_post_listings_no_person = PostQueryBuilder::create(&conn)
541 .listing_type(&ListingType::Community)
542 .sort(&SortType::New)
543 .community_id(inserted_community.id)
547 let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
548 let read_post_listing_with_person =
549 PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
551 let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
553 // the non person version
554 let expected_post_listing_no_person = PostView {
556 id: inserted_post.id,
558 creator_id: inserted_person.id,
561 published: inserted_post.published,
563 community_id: inserted_community.id,
570 embed_description: None,
573 ap_id: inserted_post.ap_id.to_owned(),
577 creator: PersonSafe {
578 id: inserted_person.id,
580 preferred_username: None,
581 published: inserted_person.published,
583 actor_id: inserted_person.actor_id.to_owned(),
590 inbox_url: inserted_person.inbox_url.to_owned(),
591 shared_inbox_url: None,
593 creator_banned_from_community: false,
594 community: CommunitySafe {
595 id: inserted_community.id,
596 name: community_name,
601 actor_id: inserted_community.actor_id.to_owned(),
603 title: "nada".to_owned(),
605 creator_id: inserted_person.id,
608 published: inserted_community.published,
610 counts: PostAggregates {
612 post_id: inserted_post.id,
618 published: agg.published,
619 newest_comment_time_necro: inserted_post.published,
620 newest_comment_time: inserted_post.published,
627 // TODO More needs to be added here
628 let mut expected_post_listing_with_user = expected_post_listing_no_person.to_owned();
629 expected_post_listing_with_user.my_vote = Some(1);
631 let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
632 let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
633 Community::delete(&conn, inserted_community.id).unwrap();
634 Person::delete(&conn, inserted_person.id).unwrap();
638 expected_post_listing_with_user,
639 read_post_listings_with_person[0]
642 expected_post_listing_with_user,
643 read_post_listing_with_person
645 assert_eq!(1, read_post_listings_with_person.len());
649 expected_post_listing_no_person,
650 read_post_listings_no_person[0]
652 assert_eq!(expected_post_listing_no_person, read_post_listing_no_person);
653 assert_eq!(1, read_post_listings_no_person.len());
655 // assert_eq!(expected_post, inserted_post);
656 // assert_eq!(expected_post, updated_post);
657 assert_eq!(expected_post_like, inserted_post_like);
658 assert_eq!(1, like_removed);
659 assert_eq!(1, num_deleted);