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 person::{Person, PersonSafe},
25 person_block::PersonBlock,
26 post::{Post, PostRead, PostSaved},
28 traits::{ToSafe, ViewToVec},
29 utils::{functions::hot_rank, fuzzy_search, limit_and_offset},
34 use typed_builder::TypedBuilder;
36 type PostViewTuple = (
40 Option<CommunityPersonBan>,
42 Option<CommunityFollower>,
54 my_person_id: Option<PersonId>,
55 ) -> Result<Self, Error> {
56 // The left join below will return None in this case
57 let person_id_join = my_person_id.unwrap_or(PersonId(-1));
62 creator_banned_from_community,
72 .inner_join(person::table)
73 .inner_join(community::table)
75 community_person_ban::table.on(
77 .eq(community_person_ban::community_id)
78 .and(community_person_ban::person_id.eq(post::creator_id))
80 community_person_ban::expires
82 .or(community_person_ban::expires.gt(now)),
86 .inner_join(post_aggregates::table)
88 community_follower::table.on(
90 .eq(community_follower::community_id)
91 .and(community_follower::person_id.eq(person_id_join)),
97 .eq(post_saved::post_id)
98 .and(post_saved::person_id.eq(person_id_join)),
104 .eq(post_read::post_id)
105 .and(post_read::person_id.eq(person_id_join)),
109 person_block::table.on(
111 .eq(person_block::target_id)
112 .and(person_block::person_id.eq(person_id_join)),
118 .eq(post_like::post_id)
119 .and(post_like::person_id.eq(person_id_join)),
122 .inner_join(language::table)
125 Person::safe_columns_tuple(),
126 Community::safe_columns_tuple(),
127 community_person_ban::all_columns.nullable(),
128 post_aggregates::all_columns,
129 community_follower::all_columns.nullable(),
130 post_saved::all_columns.nullable(),
131 post_read::all_columns.nullable(),
132 person_block::all_columns.nullable(),
133 post_like::score.nullable(),
134 language::all_columns,
136 .first::<PostViewTuple>(conn)?;
138 // If a person is given, then my_vote, if None, should be 0, not null
139 // Necessary to differentiate between other person's votes
140 let my_vote = if my_person_id.is_some() && post_like.is_none() {
150 creator_banned_from_community: creator_banned_from_community.is_some(),
152 subscribed: CommunityFollower::to_subscribed_type(&follower),
153 saved: saved.is_some(),
154 read: read.is_some(),
155 creator_blocked: creator_blocked.is_some(),
162 #[derive(TypedBuilder)]
163 #[builder(field_defaults(default))]
164 pub struct PostQuery<'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 my_local_user_id: Option<LocalUserId>,
174 search_term: Option<String>,
175 url_search: Option<String>,
176 show_nsfw: Option<bool>,
177 show_bot_accounts: Option<bool>,
178 show_read_posts: Option<bool>,
179 saved_only: Option<bool>,
184 impl<'a> PostQuery<'a> {
185 pub fn list(self) -> Result<Vec<PostView>, Error> {
188 // The left join below will return None in this case
189 let person_id_join = self.my_person_id.unwrap_or(PersonId(-1));
190 let local_user_id_join = self.my_local_user_id.unwrap_or(LocalUserId(-1));
192 let mut query = post::table
193 .inner_join(person::table)
194 .inner_join(community::table)
196 community_person_ban::table.on(
198 .eq(community_person_ban::community_id)
199 .and(community_person_ban::person_id.eq(post::creator_id))
201 community_person_ban::expires
203 .or(community_person_ban::expires.gt(now)),
207 .inner_join(post_aggregates::table)
209 community_follower::table.on(
211 .eq(community_follower::community_id)
212 .and(community_follower::person_id.eq(person_id_join)),
216 post_saved::table.on(
218 .eq(post_saved::post_id)
219 .and(post_saved::person_id.eq(person_id_join)),
225 .eq(post_read::post_id)
226 .and(post_read::person_id.eq(person_id_join)),
230 person_block::table.on(
232 .eq(person_block::target_id)
233 .and(person_block::person_id.eq(person_id_join)),
237 community_block::table.on(
239 .eq(community_block::community_id)
240 .and(community_block::person_id.eq(person_id_join)),
246 .eq(post_like::post_id)
247 .and(post_like::person_id.eq(person_id_join)),
250 .inner_join(language::table)
252 local_user_language::table.on(
254 .eq(local_user_language::language_id)
255 .and(local_user_language::local_user_id.eq(local_user_id_join)),
260 Person::safe_columns_tuple(),
261 Community::safe_columns_tuple(),
262 community_person_ban::all_columns.nullable(),
263 post_aggregates::all_columns,
264 community_follower::all_columns.nullable(),
265 post_saved::all_columns.nullable(),
266 post_read::all_columns.nullable(),
267 person_block::all_columns.nullable(),
268 post_like::score.nullable(),
269 language::all_columns,
273 if let Some(listing_type) = self.listing_type {
275 ListingType::Subscribed => {
276 query = query.filter(community_follower::person_id.is_not_null())
278 ListingType::Local => {
279 query = query.filter(community::local.eq(true)).filter(
282 .or(community_follower::person_id.eq(person_id_join)),
285 ListingType::All => {
286 query = query.filter(
289 .or(community_follower::person_id.eq(person_id_join)),
295 if let Some(community_id) = self.community_id {
297 .filter(post::community_id.eq(community_id))
298 .then_order_by(post_aggregates::stickied.desc());
301 if let Some(community_actor_id) = self.community_actor_id {
303 .filter(community::actor_id.eq(community_actor_id))
304 .then_order_by(post_aggregates::stickied.desc());
307 if let Some(url_search) = self.url_search {
308 query = query.filter(post::url.eq(url_search));
311 if let Some(search_term) = self.search_term {
312 let searcher = fuzzy_search(&search_term);
313 query = query.filter(
315 .ilike(searcher.to_owned())
316 .or(post::body.ilike(searcher)),
320 // If its for a specific person, show the removed / deleted
321 if let Some(creator_id) = self.creator_id {
322 query = query.filter(post::creator_id.eq(creator_id));
325 if !self.show_nsfw.unwrap_or(false) {
327 .filter(post::nsfw.eq(false))
328 .filter(community::nsfw.eq(false));
331 if !self.show_bot_accounts.unwrap_or(true) {
332 query = query.filter(person::bot_account.eq(false));
335 if self.saved_only.unwrap_or(false) {
336 query = query.filter(post_saved::id.is_not_null());
338 // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
339 // setting wont be able to see saved posts.
340 else if !self.show_read_posts.unwrap_or(true) {
341 query = query.filter(post_read::id.is_null());
344 // Filter out the rows with missing languages
345 if self.my_local_user_id.is_some() {
346 query = query.filter(local_user_language::id.is_not_null());
349 // Don't show blocked communities or persons
350 if self.my_person_id.is_some() {
351 query = query.filter(community_block::person_id.is_null());
352 query = query.filter(person_block::person_id.is_null());
355 query = match self.sort.unwrap_or(SortType::Hot) {
356 SortType::Active => query
359 post_aggregates::score,
360 post_aggregates::newest_comment_time_necro,
364 .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
365 SortType::Hot => query
366 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
367 .then_order_by(post_aggregates::published.desc()),
368 SortType::New => query.then_order_by(post_aggregates::published.desc()),
369 SortType::Old => query.then_order_by(post_aggregates::published.asc()),
370 SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
371 SortType::MostComments => query
372 .then_order_by(post_aggregates::comments.desc())
373 .then_order_by(post_aggregates::published.desc()),
374 SortType::TopAll => query
375 .then_order_by(post_aggregates::score.desc())
376 .then_order_by(post_aggregates::published.desc()),
377 SortType::TopYear => query
378 .filter(post_aggregates::published.gt(now - 1.years()))
379 .then_order_by(post_aggregates::score.desc())
380 .then_order_by(post_aggregates::published.desc()),
381 SortType::TopMonth => query
382 .filter(post_aggregates::published.gt(now - 1.months()))
383 .then_order_by(post_aggregates::score.desc())
384 .then_order_by(post_aggregates::published.desc()),
385 SortType::TopWeek => query
386 .filter(post_aggregates::published.gt(now - 1.weeks()))
387 .then_order_by(post_aggregates::score.desc())
388 .then_order_by(post_aggregates::published.desc()),
389 SortType::TopDay => query
390 .filter(post_aggregates::published.gt(now - 1.days()))
391 .then_order_by(post_aggregates::score.desc())
392 .then_order_by(post_aggregates::published.desc()),
395 let (limit, offset) = limit_and_offset(self.page, self.limit)?;
400 .filter(post::removed.eq(false))
401 .filter(post::deleted.eq(false))
402 .filter(community::removed.eq(false))
403 .filter(community::deleted.eq(false));
405 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
407 let res = query.load::<PostViewTuple>(self.conn)?;
409 Ok(PostView::from_tuple_to_vec(res))
413 impl ViewToVec for PostView {
414 type DbTuple = PostViewTuple;
415 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
422 creator_banned_from_community: a.3.is_some(),
424 subscribed: CommunityFollower::to_subscribed_type(&a.5),
425 saved: a.6.is_some(),
427 creator_blocked: a.8.is_some(),
431 .collect::<Vec<Self>>()
437 use crate::post_view::{PostQuery, PostView};
438 use diesel::PgConnection;
439 use lemmy_db_schema::{
440 aggregates::structs::PostAggregates,
441 newtypes::LanguageId,
444 community_block::{CommunityBlock, CommunityBlockForm},
446 local_user::{LocalUser, LocalUserForm},
447 local_user_language::LocalUserLanguage,
449 person_block::{PersonBlock, PersonBlockForm},
452 traits::{Blockable, Crud, Likeable},
453 utils::establish_unpooled_connection,
457 use serial_test::serial;
460 inserted_person: Person,
461 inserted_blocked_person: Person,
462 inserted_bot: Person,
463 inserted_community: Community,
467 fn init_data(conn: &PgConnection) -> Data {
468 let person_name = "tegan".to_string();
470 let new_person = PersonForm {
471 name: person_name.to_owned(),
472 public_key: Some("pubkey".to_string()),
473 ..PersonForm::default()
476 let inserted_person = Person::create(conn, &new_person).unwrap();
478 let new_bot = PersonForm {
479 name: "mybot".to_string(),
480 bot_account: Some(true),
481 public_key: Some("pubkey".to_string()),
482 ..PersonForm::default()
485 let inserted_bot = Person::create(conn, &new_bot).unwrap();
487 let new_community = CommunityForm {
488 name: "test_community_3".to_string(),
489 title: "nada".to_owned(),
490 public_key: Some("pubkey".to_string()),
491 ..CommunityForm::default()
494 let inserted_community = Community::create(conn, &new_community).unwrap();
496 // Test a person block, make sure the post query doesn't include their post
497 let blocked_person = PersonForm {
499 public_key: Some("pubkey".to_string()),
500 ..PersonForm::default()
503 let inserted_blocked_person = Person::create(conn, &blocked_person).unwrap();
505 let post_from_blocked_person = PostForm {
506 name: "blocked_person_post".to_string(),
507 creator_id: inserted_blocked_person.id,
508 community_id: inserted_community.id,
509 language_id: Some(LanguageId(1)),
510 ..PostForm::default()
513 Post::create(conn, &post_from_blocked_person).unwrap();
516 let person_block = PersonBlockForm {
517 person_id: inserted_person.id,
518 target_id: inserted_blocked_person.id,
521 PersonBlock::block(conn, &person_block).unwrap();
524 let new_post = PostForm {
525 name: "test post 3".to_string(),
526 creator_id: inserted_person.id,
527 community_id: inserted_community.id,
528 language_id: Some(LanguageId(47)),
529 ..PostForm::default()
532 let inserted_post = Post::create(conn, &new_post).unwrap();
534 let new_bot_post = PostForm {
535 name: "test bot post".to_string(),
536 creator_id: inserted_bot.id,
537 community_id: inserted_community.id,
538 ..PostForm::default()
541 let _inserted_bot_post = Post::create(conn, &new_bot_post).unwrap();
545 inserted_blocked_person,
552 fn cleanup(data: Data, conn: &PgConnection) {
553 let num_deleted = Post::delete(conn, data.inserted_post.id).unwrap();
554 Community::delete(conn, data.inserted_community.id).unwrap();
555 Person::delete(conn, data.inserted_person.id).unwrap();
556 Person::delete(conn, data.inserted_bot.id).unwrap();
557 Person::delete(conn, data.inserted_blocked_person.id).unwrap();
558 assert_eq!(1, num_deleted);
561 fn expected_post_listing(data: &Data, conn: &PgConnection) -> PostView {
562 let (inserted_person, inserted_community, inserted_post) = (
563 &data.inserted_person,
564 &data.inserted_community,
567 let agg = PostAggregates::read(conn, inserted_post.id).unwrap();
571 id: inserted_post.id,
572 name: inserted_post.name.clone(),
573 creator_id: inserted_person.id,
576 published: inserted_post.published,
578 community_id: inserted_community.id,
585 embed_description: None,
586 embed_video_url: None,
588 ap_id: inserted_post.ap_id.to_owned(),
590 language_id: LanguageId(47),
593 creator: PersonSafe {
594 id: inserted_person.id,
595 name: inserted_person.name.clone(),
597 published: inserted_person.published,
599 actor_id: inserted_person.actor_id.to_owned(),
608 inbox_url: inserted_person.inbox_url.to_owned(),
609 shared_inbox_url: None,
610 matrix_user_id: None,
613 creator_banned_from_community: false,
614 community: CommunitySafe {
615 id: inserted_community.id,
616 name: inserted_community.name.clone(),
621 actor_id: inserted_community.actor_id.to_owned(),
623 title: "nada".to_owned(),
628 posting_restricted_to_mods: false,
629 published: inserted_community.published,
631 counts: PostAggregates {
633 post_id: inserted_post.id,
639 published: agg.published,
640 newest_comment_time_necro: inserted_post.published,
641 newest_comment_time: inserted_post.published,
643 subscribed: SubscribedType::NotSubscribed,
646 creator_blocked: false,
649 code: "fr".to_string(),
650 name: "Français".to_string(),
657 fn post_listing_with_person() {
658 let conn = establish_unpooled_connection();
659 let data = init_data(&conn);
661 let read_post_listing = PostQuery::builder()
663 .sort(Some(SortType::New))
664 .community_id(Some(data.inserted_community.id))
665 .show_bot_accounts(Some(false))
666 .my_person_id(Some(data.inserted_person.id))
671 let post_listing_single_with_person =
672 PostView::read(&conn, data.inserted_post.id, Some(data.inserted_person.id)).unwrap();
674 let mut expected_post_listing_with_user = expected_post_listing(&data, &conn);
676 // Should be only one person, IE the bot post, and blocked should be missing
677 assert_eq!(1, read_post_listing.len());
679 assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
680 expected_post_listing_with_user.my_vote = Some(0);
682 expected_post_listing_with_user,
683 post_listing_single_with_person
686 let post_listings_with_bots = PostQuery::builder()
688 .sort(Some(SortType::New))
689 .community_id(Some(data.inserted_community.id))
690 .show_bot_accounts(Some(true))
691 .my_person_id(Some(data.inserted_person.id))
695 // should include bot post which has "undetermined" language
696 assert_eq!(2, post_listings_with_bots.len());
698 cleanup(data, &conn);
703 fn post_listing_no_person() {
704 let conn = establish_unpooled_connection();
705 let data = init_data(&conn);
707 let read_post_listing_multiple_no_person = PostQuery::builder()
709 .sort(Some(SortType::New))
710 .community_id(Some(data.inserted_community.id))
715 let read_post_listing_single_no_person =
716 PostView::read(&conn, data.inserted_post.id, None).unwrap();
718 let expected_post_listing_no_person = expected_post_listing(&data, &conn);
720 // Should be 2 posts, with the bot post, and the blocked
721 assert_eq!(3, read_post_listing_multiple_no_person.len());
724 expected_post_listing_no_person,
725 read_post_listing_multiple_no_person[1]
728 expected_post_listing_no_person,
729 read_post_listing_single_no_person
732 cleanup(data, &conn);
737 fn post_listing_block_community() {
738 let conn = establish_unpooled_connection();
739 let data = init_data(&conn);
741 let community_block = CommunityBlockForm {
742 person_id: data.inserted_person.id,
743 community_id: data.inserted_community.id,
745 CommunityBlock::block(&conn, &community_block).unwrap();
747 let read_post_listings_with_person_after_block = PostQuery::builder()
749 .sort(Some(SortType::New))
750 .community_id(Some(data.inserted_community.id))
751 .show_bot_accounts(Some(true))
752 .my_person_id(Some(data.inserted_person.id))
756 // Should be 0 posts after the community block
757 assert_eq!(0, read_post_listings_with_person_after_block.len());
759 CommunityBlock::unblock(&conn, &community_block).unwrap();
760 cleanup(data, &conn);
765 fn post_listing_like() {
766 let conn = establish_unpooled_connection();
767 let data = init_data(&conn);
769 let post_like_form = PostLikeForm {
770 post_id: data.inserted_post.id,
771 person_id: data.inserted_person.id,
775 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
777 let expected_post_like = PostLike {
778 id: inserted_post_like.id,
779 post_id: data.inserted_post.id,
780 person_id: data.inserted_person.id,
781 published: inserted_post_like.published,
784 assert_eq!(expected_post_like, inserted_post_like);
787 PostLike::remove(&conn, data.inserted_person.id, data.inserted_post.id).unwrap();
788 assert_eq!(1, like_removed);
789 cleanup(data, &conn);
794 fn post_listing_person_language() {
795 let conn = establish_unpooled_connection();
796 let data = init_data(&conn);
798 let spanish_id = Language::read_id_from_code(&conn, "es").unwrap();
799 let post_spanish = PostForm {
800 name: "asffgdsc".to_string(),
801 creator_id: data.inserted_person.id,
802 community_id: data.inserted_community.id,
803 language_id: Some(spanish_id),
804 ..PostForm::default()
807 Post::create(&conn, &post_spanish).unwrap();
809 let my_person_form = PersonForm {
810 name: "Reverie Toiba".to_string(),
811 public_key: Some("pubkey".to_string()),
812 ..PersonForm::default()
814 let my_person = Person::create(&conn, &my_person_form).unwrap();
815 let local_user_form = LocalUserForm {
816 person_id: Some(my_person.id),
817 password_encrypted: Some("".to_string()),
820 let local_user = LocalUser::create(&conn, &local_user_form).unwrap();
822 // Update the users languages to all
823 LocalUserLanguage::update_user_languages(&conn, None, local_user.id).unwrap();
825 let post_listings_all = PostQuery::builder()
827 .sort(Some(SortType::New))
828 .show_bot_accounts(Some(true))
829 .my_person_id(Some(my_person.id))
830 .my_local_user_id(Some(local_user.id))
835 // no language filters specified, all posts should be returned
836 assert_eq!(4, post_listings_all.len());
838 let french_id = Language::read_id_from_code(&conn, "fr").unwrap();
839 LocalUserLanguage::update_user_languages(&conn, Some(vec![french_id]), local_user.id).unwrap();
841 let post_listing_french = PostQuery::builder()
843 .sort(Some(SortType::New))
844 .show_bot_accounts(Some(true))
845 .my_person_id(Some(my_person.id))
846 .my_local_user_id(Some(local_user.id))
851 // only one french language post should be returned
852 assert_eq!(1, post_listing_french.len());
853 assert_eq!(french_id, post_listing_french[0].post.language_id);
855 let undetermined_id = Language::read_id_from_code(&conn, "und").unwrap();
856 LocalUserLanguage::update_user_languages(
858 Some(vec![french_id, undetermined_id]),
862 let post_listings_french_und = PostQuery::builder()
864 .sort(Some(SortType::New))
865 .show_bot_accounts(Some(true))
866 .my_person_id(Some(my_person.id))
867 .my_local_user_id(Some(local_user.id))
872 // french post and undetermined language post should be returned
873 assert_eq!(2, post_listings_french_und.len());
876 post_listings_french_und[0].post.language_id
878 assert_eq!(french_id, post_listings_french_und[1].post.language_id);
880 cleanup(data, &conn);