1 use crate::structs::PostView;
2 use diesel::{dsl::*, pg::Pg, result::Error, *};
4 aggregates::structs::PostAggregates,
5 newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
22 community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
24 local_user::LocalUser,
25 person::{Person, PersonSafe},
26 person_block::PersonBlock,
27 post::{Post, PostRead, PostSaved},
29 traits::{ToSafe, ViewToVec},
30 utils::{functions::hot_rank, fuzzy_search, limit_and_offset},
35 use typed_builder::TypedBuilder;
37 type PostViewTuple = (
41 Option<CommunityPersonBan>,
43 Option<CommunityFollower>,
55 my_person_id: Option<PersonId>,
56 ) -> Result<Self, Error> {
57 // The left join below will return None in this case
58 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
63 creator_banned_from_community,
73 .inner_join(person::table)
74 .inner_join(community::table)
76 community_person_ban::table.on(
78 .eq(community_person_ban::community_id)
79 .and(community_person_ban::person_id.eq(post::creator_id))
81 community_person_ban::expires
83 .or(community_person_ban::expires.gt(now)),
87 .inner_join(post_aggregates::table)
89 community_follower::table.on(
91 .eq(community_follower::community_id)
92 .and(community_follower::person_id.eq(person_id_join)),
98 .eq(post_saved::post_id)
99 .and(post_saved::person_id.eq(person_id_join)),
105 .eq(post_read::post_id)
106 .and(post_read::person_id.eq(person_id_join)),
110 person_block::table.on(
112 .eq(person_block::target_id)
113 .and(person_block::person_id.eq(person_id_join)),
119 .eq(post_like::post_id)
120 .and(post_like::person_id.eq(person_id_join)),
123 .inner_join(language::table)
126 Person::safe_columns_tuple(),
127 Community::safe_columns_tuple(),
128 community_person_ban::all_columns.nullable(),
129 post_aggregates::all_columns,
130 community_follower::all_columns.nullable(),
131 post_saved::all_columns.nullable(),
132 post_read::all_columns.nullable(),
133 person_block::all_columns.nullable(),
134 post_like::score.nullable(),
135 language::all_columns,
137 .first::<PostViewTuple>(conn)?;
139 // If a person is given, then my_vote, if None, should be 0, not null
140 // Necessary to differentiate between other person's votes
141 let my_vote = if my_person_id.is_some() && post_like.is_none() {
151 creator_banned_from_community: creator_banned_from_community.is_some(),
153 subscribed: CommunityFollower::to_subscribed_type(&follower),
154 saved: saved.is_some(),
155 read: read.is_some(),
156 creator_blocked: creator_blocked.is_some(),
163 #[derive(TypedBuilder)]
164 #[builder(field_defaults(default))]
165 pub struct PostQuery<'a> {
167 conn: &'a PgConnection,
168 listing_type: Option<ListingType>,
169 sort: Option<SortType>,
170 creator_id: Option<PersonId>,
171 community_id: Option<CommunityId>,
172 community_actor_id: Option<DbUrl>,
173 local_user: Option<&'a LocalUser>,
174 search_term: Option<String>,
175 url_search: Option<String>,
176 saved_only: Option<bool>,
181 impl<'a> PostQuery<'a> {
182 pub fn list(self) -> Result<Vec<PostView>, Error> {
185 // The left join below will return None in this case
186 let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1));
187 let local_user_id_join = self.local_user.map(|l| l.id).unwrap_or(LocalUserId(-1));
189 let mut query = post::table
190 .inner_join(person::table)
191 .inner_join(community::table)
193 community_person_ban::table.on(
195 .eq(community_person_ban::community_id)
196 .and(community_person_ban::person_id.eq(post::creator_id))
198 community_person_ban::expires
200 .or(community_person_ban::expires.gt(now)),
204 .inner_join(post_aggregates::table)
206 community_follower::table.on(
208 .eq(community_follower::community_id)
209 .and(community_follower::person_id.eq(person_id_join)),
213 post_saved::table.on(
215 .eq(post_saved::post_id)
216 .and(post_saved::person_id.eq(person_id_join)),
222 .eq(post_read::post_id)
223 .and(post_read::person_id.eq(person_id_join)),
227 person_block::table.on(
229 .eq(person_block::target_id)
230 .and(person_block::person_id.eq(person_id_join)),
234 community_block::table.on(
236 .eq(community_block::community_id)
237 .and(community_block::person_id.eq(person_id_join)),
243 .eq(post_like::post_id)
244 .and(post_like::person_id.eq(person_id_join)),
247 .inner_join(language::table)
249 local_user_language::table.on(
251 .eq(local_user_language::language_id)
252 .and(local_user_language::local_user_id.eq(local_user_id_join)),
257 Person::safe_columns_tuple(),
258 Community::safe_columns_tuple(),
259 community_person_ban::all_columns.nullable(),
260 post_aggregates::all_columns,
261 community_follower::all_columns.nullable(),
262 post_saved::all_columns.nullable(),
263 post_read::all_columns.nullable(),
264 person_block::all_columns.nullable(),
265 post_like::score.nullable(),
266 language::all_columns,
270 if let Some(listing_type) = self.listing_type {
272 ListingType::Subscribed => {
273 query = query.filter(community_follower::person_id.is_not_null())
275 ListingType::Local => {
276 query = query.filter(community::local.eq(true)).filter(
279 .or(community_follower::person_id.eq(person_id_join)),
282 ListingType::All => {
283 query = query.filter(
286 .or(community_follower::person_id.eq(person_id_join)),
292 if let Some(community_id) = self.community_id {
294 .filter(post::community_id.eq(community_id))
295 .then_order_by(post_aggregates::stickied.desc());
298 if let Some(community_actor_id) = self.community_actor_id {
300 .filter(community::actor_id.eq(community_actor_id))
301 .then_order_by(post_aggregates::stickied.desc());
304 if let Some(url_search) = self.url_search {
305 query = query.filter(post::url.eq(url_search));
308 if let Some(search_term) = self.search_term {
309 let searcher = fuzzy_search(&search_term);
310 query = query.filter(
312 .ilike(searcher.to_owned())
313 .or(post::body.ilike(searcher)),
317 // If its for a specific person, show the removed / deleted
318 if let Some(creator_id) = self.creator_id {
319 query = query.filter(post::creator_id.eq(creator_id));
322 if !self.local_user.map(|l| l.show_nsfw).unwrap_or(false) {
324 .filter(post::nsfw.eq(false))
325 .filter(community::nsfw.eq(false));
328 if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
329 query = query.filter(person::bot_account.eq(false));
332 if self.saved_only.unwrap_or(false) {
333 query = query.filter(post_saved::id.is_not_null());
335 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
336 // setting wont be able to see saved posts.
337 else if !self.local_user.map(|l| l.show_read_posts).unwrap_or(true) {
338 query = query.filter(post_read::id.is_null());
341 if self.local_user.is_some() {
342 // Filter out the rows with missing languages
343 query = query.filter(local_user_language::id.is_not_null());
345 // Don't show blocked communities or persons
346 query = query.filter(community_block::person_id.is_null());
347 query = query.filter(person_block::person_id.is_null());
350 query = match self.sort.unwrap_or(SortType::Hot) {
351 SortType::Active => query
354 post_aggregates::score,
355 post_aggregates::newest_comment_time_necro,
359 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
360 SortType::Hot => query
361 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
362 .then_order_by(post_aggregates::published.desc()),
363 SortType::New => query.then_order_by(post_aggregates::published.desc()),
364 SortType::Old => query.then_order_by(post_aggregates::published.asc()),
365 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
366 SortType::MostComments => query
367 .then_order_by(post_aggregates::comments.desc())
368 .then_order_by(post_aggregates::published.desc()),
369 SortType::TopAll => query
370 .then_order_by(post_aggregates::score.desc())
371 .then_order_by(post_aggregates::published.desc()),
372 SortType::TopYear => query
373 .filter(post_aggregates::published.gt(now - 1.years()))
374 .then_order_by(post_aggregates::score.desc())
375 .then_order_by(post_aggregates::published.desc()),
376 SortType::TopMonth => query
377 .filter(post_aggregates::published.gt(now - 1.months()))
378 .then_order_by(post_aggregates::score.desc())
379 .then_order_by(post_aggregates::published.desc()),
380 SortType::TopWeek => query
381 .filter(post_aggregates::published.gt(now - 1.weeks()))
382 .then_order_by(post_aggregates::score.desc())
383 .then_order_by(post_aggregates::published.desc()),
384 SortType::TopDay => query
385 .filter(post_aggregates::published.gt(now - 1.days()))
386 .then_order_by(post_aggregates::score.desc())
387 .then_order_by(post_aggregates::published.desc()),
390 let (limit, offset) = limit_and_offset(self.page, self.limit)?;
395 .filter(post::removed.eq(false))
396 .filter(post::deleted.eq(false))
397 .filter(community::removed.eq(false))
398 .filter(community::deleted.eq(false));
400 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
402 let res = query.load::<PostViewTuple>(self.conn)?;
404 Ok(PostView::from_tuple_to_vec(res))
408 impl ViewToVec for PostView {
409 type DbTuple = PostViewTuple;
410 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
417 creator_banned_from_community: a.3.is_some(),
419 subscribed: CommunityFollower::to_subscribed_type(&a.5),
420 saved: a.6.is_some(),
422 creator_blocked: a.8.is_some(),
426 .collect::<Vec<Self>>()
432 use crate::post_view::{PostQuery, PostView};
433 use diesel::PgConnection;
434 use lemmy_db_schema::{
435 aggregates::structs::PostAggregates,
436 newtypes::LanguageId,
439 community_block::{CommunityBlock, CommunityBlockForm},
441 local_user::{LocalUser, LocalUserForm},
442 local_user_language::LocalUserLanguage,
444 person_block::{PersonBlock, PersonBlockForm},
447 traits::{Blockable, Crud, Likeable},
448 utils::establish_unpooled_connection,
452 use serial_test::serial;
455 inserted_person: Person,
456 inserted_local_user: LocalUser,
457 inserted_blocked_person: Person,
458 inserted_bot: Person,
459 inserted_community: Community,
463 fn init_data(conn: &PgConnection) -> Data {
464 let person_name = "tegan".to_string();
466 let new_person = PersonForm {
467 name: person_name.to_owned(),
468 public_key: Some("pubkey".to_string()),
469 ..PersonForm::default()
472 let inserted_person = Person::create(conn, &new_person).unwrap();
474 let local_user_form = LocalUserForm {
475 person_id: Some(inserted_person.id),
476 password_encrypted: Some("".to_string()),
479 let inserted_local_user = LocalUser::create(conn, &local_user_form).unwrap();
481 let new_bot = PersonForm {
482 name: "mybot".to_string(),
483 bot_account: Some(true),
484 public_key: Some("pubkey".to_string()),
485 ..PersonForm::default()
488 let inserted_bot = Person::create(conn, &new_bot).unwrap();
490 let new_community = CommunityForm {
491 name: "test_community_3".to_string(),
492 title: "nada".to_owned(),
493 public_key: Some("pubkey".to_string()),
494 ..CommunityForm::default()
497 let inserted_community = Community::create(conn, &new_community).unwrap();
499 // Test a person block, make sure the post query doesn't include their post
500 let blocked_person = PersonForm {
502 public_key: Some("pubkey".to_string()),
503 ..PersonForm::default()
506 let inserted_blocked_person = Person::create(conn, &blocked_person).unwrap();
508 let post_from_blocked_person = PostForm {
509 name: "blocked_person_post".to_string(),
510 creator_id: inserted_blocked_person.id,
511 community_id: inserted_community.id,
512 language_id: Some(LanguageId(1)),
513 ..PostForm::default()
516 Post::create(conn, &post_from_blocked_person).unwrap();
519 let person_block = PersonBlockForm {
520 person_id: inserted_person.id,
521 target_id: inserted_blocked_person.id,
524 PersonBlock::block(conn, &person_block).unwrap();
527 let new_post = PostForm {
528 name: "test post 3".to_string(),
529 creator_id: inserted_person.id,
530 community_id: inserted_community.id,
531 language_id: Some(LanguageId(47)),
532 ..PostForm::default()
535 let inserted_post = Post::create(conn, &new_post).unwrap();
537 let new_bot_post = PostForm {
538 name: "test bot post".to_string(),
539 creator_id: inserted_bot.id,
540 community_id: inserted_community.id,
541 ..PostForm::default()
544 let _inserted_bot_post = Post::create(conn, &new_bot_post).unwrap();
549 inserted_blocked_person,
558 fn post_listing_with_person() {
559 let conn = establish_unpooled_connection();
560 let data = init_data(&conn);
562 let local_user_form = LocalUserForm {
563 show_bot_accounts: Some(false),
566 let inserted_local_user =
567 LocalUser::update(&conn, data.inserted_local_user.id, &local_user_form).unwrap();
569 let read_post_listing = PostQuery::builder()
571 .sort(Some(SortType::New))
572 .community_id(Some(data.inserted_community.id))
573 .local_user(Some(&inserted_local_user))
578 let post_listing_single_with_person =
579 PostView::read(&conn, data.inserted_post.id, Some(data.inserted_person.id)).unwrap();
581 let mut expected_post_listing_with_user = expected_post_view(&data, &conn);
583 // Should be only one person, IE the bot post, and blocked should be missing
584 assert_eq!(1, read_post_listing.len());
586 assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
587 expected_post_listing_with_user.my_vote = Some(0);
589 expected_post_listing_with_user,
590 post_listing_single_with_person
593 let local_user_form = LocalUserForm {
594 show_bot_accounts: Some(true),
597 let inserted_local_user =
598 LocalUser::update(&conn, data.inserted_local_user.id, &local_user_form).unwrap();
600 let post_listings_with_bots = PostQuery::builder()
602 .sort(Some(SortType::New))
603 .community_id(Some(data.inserted_community.id))
604 .local_user(Some(&inserted_local_user))
608 // should include bot post which has "undetermined" language
609 assert_eq!(2, post_listings_with_bots.len());
611 cleanup(data, &conn);
616 fn post_listing_no_person() {
617 let conn = establish_unpooled_connection();
618 let data = init_data(&conn);
620 let read_post_listing_multiple_no_person = PostQuery::builder()
622 .sort(Some(SortType::New))
623 .community_id(Some(data.inserted_community.id))
628 let read_post_listing_single_no_person =
629 PostView::read(&conn, data.inserted_post.id, None).unwrap();
631 let expected_post_listing_no_person = expected_post_view(&data, &conn);
633 // Should be 2 posts, with the bot post, and the blocked
634 assert_eq!(3, read_post_listing_multiple_no_person.len());
637 expected_post_listing_no_person,
638 read_post_listing_multiple_no_person[1]
641 expected_post_listing_no_person,
642 read_post_listing_single_no_person
645 cleanup(data, &conn);
650 fn post_listing_block_community() {
651 let conn = establish_unpooled_connection();
652 let data = init_data(&conn);
654 let community_block = CommunityBlockForm {
655 person_id: data.inserted_person.id,
656 community_id: data.inserted_community.id,
658 CommunityBlock::block(&conn, &community_block).unwrap();
660 let read_post_listings_with_person_after_block = PostQuery::builder()
662 .sort(Some(SortType::New))
663 .community_id(Some(data.inserted_community.id))
664 .local_user(Some(&data.inserted_local_user))
668 // Should be 0 posts after the community block
669 assert_eq!(0, read_post_listings_with_person_after_block.len());
671 CommunityBlock::unblock(&conn, &community_block).unwrap();
672 cleanup(data, &conn);
677 fn post_listing_like() {
678 let conn = establish_unpooled_connection();
679 let data = init_data(&conn);
681 let post_like_form = PostLikeForm {
682 post_id: data.inserted_post.id,
683 person_id: data.inserted_person.id,
687 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
689 let expected_post_like = PostLike {
690 id: inserted_post_like.id,
691 post_id: data.inserted_post.id,
692 person_id: data.inserted_person.id,
693 published: inserted_post_like.published,
696 assert_eq!(expected_post_like, inserted_post_like);
699 PostLike::remove(&conn, data.inserted_person.id, data.inserted_post.id).unwrap();
700 assert_eq!(1, like_removed);
701 cleanup(data, &conn);
706 fn post_listing_person_language() {
707 let conn = establish_unpooled_connection();
708 let data = init_data(&conn);
710 let spanish_id = Language::read_id_from_code(&conn, "es").unwrap();
711 let post_spanish = PostForm {
712 name: "asffgdsc".to_string(),
713 creator_id: data.inserted_person.id,
714 community_id: data.inserted_community.id,
715 language_id: Some(spanish_id),
716 ..PostForm::default()
719 Post::create(&conn, &post_spanish).unwrap();
721 let post_listings_all = PostQuery::builder()
723 .sort(Some(SortType::New))
724 .local_user(Some(&data.inserted_local_user))
729 // no language filters specified, all posts should be returned
730 assert_eq!(3, post_listings_all.len());
732 let french_id = Language::read_id_from_code(&conn, "fr").unwrap();
733 LocalUserLanguage::update_user_languages(
735 Some(vec![french_id]),
736 data.inserted_local_user.id,
740 let post_listing_french = PostQuery::builder()
742 .sort(Some(SortType::New))
743 .local_user(Some(&data.inserted_local_user))
748 // only one french language post should be returned
749 assert_eq!(1, post_listing_french.len());
750 assert_eq!(french_id, post_listing_french[0].post.language_id);
752 let undetermined_id = Language::read_id_from_code(&conn, "und").unwrap();
753 LocalUserLanguage::update_user_languages(
755 Some(vec![french_id, undetermined_id]),
756 data.inserted_local_user.id,
759 let post_listings_french_und = PostQuery::builder()
761 .sort(Some(SortType::New))
762 .local_user(Some(&data.inserted_local_user))
767 // french post and undetermined language post should be returned
768 assert_eq!(2, post_listings_french_und.len());
771 post_listings_french_und[0].post.language_id
773 assert_eq!(french_id, post_listings_french_und[1].post.language_id);
775 cleanup(data, &conn);
778 fn cleanup(data: Data, conn: &PgConnection) {
779 let num_deleted = Post::delete(conn, data.inserted_post.id).unwrap();
780 Community::delete(conn, data.inserted_community.id).unwrap();
781 Person::delete(conn, data.inserted_person.id).unwrap();
782 Person::delete(conn, data.inserted_bot.id).unwrap();
783 Person::delete(conn, data.inserted_blocked_person.id).unwrap();
784 assert_eq!(1, num_deleted);
787 fn expected_post_view(data: &Data, conn: &PgConnection) -> PostView {
788 let (inserted_person, inserted_community, inserted_post) = (
789 &data.inserted_person,
790 &data.inserted_community,
793 let agg = PostAggregates::read(conn, inserted_post.id).unwrap();
797 id: inserted_post.id,
798 name: inserted_post.name.clone(),
799 creator_id: inserted_person.id,
802 published: inserted_post.published,
804 community_id: inserted_community.id,
811 embed_description: None,
812 embed_video_url: None,
814 ap_id: inserted_post.ap_id.to_owned(),
816 language_id: LanguageId(47),
819 creator: PersonSafe {
820 id: inserted_person.id,
821 name: inserted_person.name.clone(),
823 published: inserted_person.published,
825 actor_id: inserted_person.actor_id.to_owned(),
834 inbox_url: inserted_person.inbox_url.to_owned(),
835 shared_inbox_url: None,
836 matrix_user_id: None,
839 creator_banned_from_community: false,
840 community: CommunitySafe {
841 id: inserted_community.id,
842 name: inserted_community.name.clone(),
847 actor_id: inserted_community.actor_id.to_owned(),
849 title: "nada".to_owned(),
854 posting_restricted_to_mods: false,
855 published: inserted_community.published,
857 counts: PostAggregates {
859 post_id: inserted_post.id,
865 published: agg.published,
866 newest_comment_time_necro: inserted_post.published,
867 newest_comment_time: inserted_post.published,
869 subscribed: SubscribedType::NotSubscribed,
872 creator_blocked: false,
875 code: "fr".to_string(),
876 name: "Français".to_string(),