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: &'a ListingType,
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>,
173 impl<'a> PostQueryBuilder<'a> {
174 pub fn create(conn: &'a PgConnection) -> Self {
177 listing_type: &ListingType::All,
178 sort: &SortType::Hot,
181 community_name: None,
193 pub fn listing_type(mut self, listing_type: &'a ListingType) -> Self {
194 self.listing_type = listing_type;
198 pub fn sort(mut self, sort: &'a SortType) -> Self {
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_name<T: MaybeOptional<String>>(mut self, community_name: T) -> Self {
214 self.community_name = community_name.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(mut self, show_nsfw: bool) -> Self {
234 self.show_nsfw = show_nsfw;
238 pub fn saved_only(mut self, saved_only: bool) -> Self {
239 self.saved_only = saved_only;
243 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
244 self.page = page.get_optional();
248 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
249 self.limit = limit.get_optional();
253 pub fn list(self) -> Result<Vec<PostView>, Error> {
256 // The left join below will return None in this case
257 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
259 let mut query = post::table
260 .inner_join(person::table)
261 .inner_join(community::table)
263 community_person_ban::table.on(
265 .eq(community_person_ban::community_id)
266 .and(community_person_ban::person_id.eq(community::creator_id)),
269 .inner_join(post_aggregates::table)
271 community_follower::table.on(
273 .eq(community_follower::community_id)
274 .and(community_follower::person_id.eq(person_id_join)),
278 post_saved::table.on(
280 .eq(post_saved::post_id)
281 .and(post_saved::person_id.eq(person_id_join)),
287 .eq(post_read::post_id)
288 .and(post_read::person_id.eq(person_id_join)),
294 .eq(post_like::post_id)
295 .and(post_like::person_id.eq(person_id_join)),
300 Person::safe_columns_tuple(),
301 Community::safe_columns_tuple(),
302 community_person_ban::all_columns.nullable(),
303 post_aggregates::all_columns,
304 community_follower::all_columns.nullable(),
305 post_saved::all_columns.nullable(),
306 post_read::all_columns.nullable(),
307 post_like::score.nullable(),
311 query = match self.listing_type {
312 ListingType::Subscribed => query.filter(community_follower::person_id.is_not_null()), // TODO could be this: and(community_follower::person_id.eq(person_id_join)),
313 ListingType::Local => query.filter(community::local.eq(true)),
317 if let Some(community_id) = self.community_id {
319 .filter(post::community_id.eq(community_id))
320 .then_order_by(post_aggregates::stickied.desc());
323 if let Some(community_name) = self.community_name {
325 .filter(community::name.eq(community_name))
326 .filter(community::local.eq(true))
327 .then_order_by(post_aggregates::stickied.desc());
330 if let Some(url_search) = self.url_search {
331 query = query.filter(post::url.eq(url_search));
334 if let Some(search_term) = self.search_term {
335 let searcher = fuzzy_search(&search_term);
336 query = query.filter(
338 .ilike(searcher.to_owned())
339 .or(post::body.ilike(searcher)),
343 // If its for a specific person, show the removed / deleted
344 if let Some(creator_id) = self.creator_id {
345 query = query.filter(post::creator_id.eq(creator_id));
350 .filter(post::nsfw.eq(false))
351 .filter(community::nsfw.eq(false));
354 // TODO These two might be wrong
356 query = query.filter(post_saved::id.is_not_null());
359 if self.unread_only {
360 query = query.filter(post_read::id.is_not_null());
363 query = match self.sort {
364 SortType::Active => query
367 post_aggregates::score,
368 post_aggregates::newest_comment_time_necro,
372 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
373 SortType::Hot => query
374 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
375 .then_order_by(post_aggregates::published.desc()),
376 SortType::New => query.then_order_by(post_aggregates::published.desc()),
377 SortType::MostComments => query.then_order_by(post_aggregates::comments.desc()),
378 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
379 SortType::TopAll => query.then_order_by(post_aggregates::score.desc()),
380 SortType::TopYear => query
381 .filter(post::published.gt(now - 1.years()))
382 .then_order_by(post_aggregates::score.desc()),
383 SortType::TopMonth => query
384 .filter(post::published.gt(now - 1.months()))
385 .then_order_by(post_aggregates::score.desc()),
386 SortType::TopWeek => query
387 .filter(post::published.gt(now - 1.weeks()))
388 .then_order_by(post_aggregates::score.desc()),
389 SortType::TopDay => query
390 .filter(post::published.gt(now - 1.days()))
391 .then_order_by(post_aggregates::score.desc()),
394 let (limit, offset) = limit_and_offset(self.page, self.limit);
399 .filter(post::removed.eq(false))
400 .filter(post::deleted.eq(false))
401 .filter(community::removed.eq(false))
402 .filter(community::deleted.eq(false));
404 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
406 let res = query.load::<PostViewTuple>(self.conn)?;
408 Ok(PostView::from_tuple_to_vec(res))
412 impl ViewToVec for PostView {
413 type DbTuple = PostViewTuple;
414 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
418 post: a.0.to_owned(),
419 creator: a.1.to_owned(),
420 community: a.2.to_owned(),
421 creator_banned_from_community: a.3.is_some(),
422 counts: a.4.to_owned(),
423 subscribed: a.5.is_some(),
424 saved: a.6.is_some(),
428 .collect::<Vec<Self>>()
434 use crate::post_view::{PostQueryBuilder, PostView};
435 use lemmy_db_queries::{
436 aggregates::post_aggregates::PostAggregates,
437 establish_unpooled_connection,
443 use lemmy_db_schema::source::{community::*, person::*, post::*};
444 use serial_test::serial;
449 let conn = establish_unpooled_connection();
451 let person_name = "tegan".to_string();
452 let community_name = "test_community_3".to_string();
453 let post_name = "test post 3".to_string();
455 let new_person = PersonForm {
456 name: person_name.to_owned(),
457 preferred_username: None,
469 last_refreshed_at: None,
471 shared_inbox_url: None,
472 matrix_user_id: None,
475 let inserted_person = Person::create(&conn, &new_person).unwrap();
477 let new_community = CommunityForm {
478 name: community_name.to_owned(),
479 title: "nada".to_owned(),
481 creator_id: inserted_person.id,
490 last_refreshed_at: None,
496 shared_inbox_url: None,
499 let inserted_community = Community::create(&conn, &new_community).unwrap();
501 let new_post = PostForm {
502 name: post_name.to_owned(),
505 creator_id: inserted_person.id,
506 community_id: inserted_community.id,
514 embed_description: None,
522 let inserted_post = Post::create(&conn, &new_post).unwrap();
524 let post_like_form = PostLikeForm {
525 post_id: inserted_post.id,
526 person_id: inserted_person.id,
530 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
532 let expected_post_like = PostLike {
533 id: inserted_post_like.id,
534 post_id: inserted_post.id,
535 person_id: inserted_person.id,
536 published: inserted_post_like.published,
540 let read_post_listings_with_person = PostQueryBuilder::create(&conn)
541 .listing_type(&ListingType::Community)
542 .sort(&SortType::New)
543 .community_id(inserted_community.id)
544 .my_person_id(inserted_person.id)
548 let read_post_listings_no_person = PostQueryBuilder::create(&conn)
549 .listing_type(&ListingType::Community)
550 .sort(&SortType::New)
551 .community_id(inserted_community.id)
555 let read_post_listing_no_person = PostView::read(&conn, inserted_post.id, None).unwrap();
556 let read_post_listing_with_person =
557 PostView::read(&conn, inserted_post.id, Some(inserted_person.id)).unwrap();
559 let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
561 // the non person version
562 let expected_post_listing_no_person = PostView {
564 id: inserted_post.id,
566 creator_id: inserted_person.id,
569 published: inserted_post.published,
571 community_id: inserted_community.id,
578 embed_description: None,
581 ap_id: inserted_post.ap_id.to_owned(),
585 creator: PersonSafe {
586 id: inserted_person.id,
588 preferred_username: None,
589 published: inserted_person.published,
591 actor_id: inserted_person.actor_id.to_owned(),
598 inbox_url: inserted_person.inbox_url.to_owned(),
599 shared_inbox_url: None,
600 matrix_user_id: None,
602 creator_banned_from_community: false,
603 community: CommunitySafe {
604 id: inserted_community.id,
605 name: community_name,
610 actor_id: inserted_community.actor_id.to_owned(),
612 title: "nada".to_owned(),
614 creator_id: inserted_person.id,
617 published: inserted_community.published,
619 counts: PostAggregates {
621 post_id: inserted_post.id,
627 published: agg.published,
628 newest_comment_time_necro: inserted_post.published,
629 newest_comment_time: inserted_post.published,
636 // TODO More needs to be added here
637 let mut expected_post_listing_with_user = expected_post_listing_no_person.to_owned();
638 expected_post_listing_with_user.my_vote = Some(1);
640 let like_removed = PostLike::remove(&conn, inserted_person.id, inserted_post.id).unwrap();
641 let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
642 Community::delete(&conn, inserted_community.id).unwrap();
643 Person::delete(&conn, inserted_person.id).unwrap();
647 expected_post_listing_with_user,
648 read_post_listings_with_person[0]
651 expected_post_listing_with_user,
652 read_post_listing_with_person
654 assert_eq!(1, read_post_listings_with_person.len());
658 expected_post_listing_no_person,
659 read_post_listings_no_person[0]
661 assert_eq!(expected_post_listing_no_person, read_post_listing_no_person);
662 assert_eq!(1, read_post_listings_no_person.len());
664 // assert_eq!(expected_post, inserted_post);
665 // assert_eq!(expected_post, updated_post);
666 assert_eq!(expected_post_like, inserted_post_like);
667 assert_eq!(1, like_removed);
668 assert_eq!(1, num_deleted);