Removing a few SuccessResponses for PostHide and MarkPostAsRead.

- This also removes the pointless multiple post_ids. These can be done
  as individual calls on the front end anyway.
- Fixes #4755
This commit is contained in:
Dessalines 2024-09-23 12:19:16 -04:00
parent 62e1790ae7
commit 10079f8295
6 changed files with 99 additions and 115 deletions

View file

@ -1,34 +1,39 @@
use actix_web::web::{Data, Json}; use actix_web::web::{Data, Json};
use lemmy_api_common::{context::LemmyContext, post::HidePost, SuccessResponse}; use lemmy_api_common::{
context::LemmyContext,
post::{HidePost, PostResponse},
};
use lemmy_db_schema::source::post::PostHide; use lemmy_db_schema::source::post::PostHide;
use lemmy_db_views::structs::LocalUserView; use lemmy_db_views::structs::{LocalUserView, PostView};
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult, MAX_API_PARAM_ELEMENTS}; use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
use std::collections::HashSet;
#[tracing::instrument(skip(context))] #[tracing::instrument(skip(context))]
pub async fn hide_post( pub async fn hide_post(
data: Json<HidePost>, data: Json<HidePost>,
context: Data<LemmyContext>, context: Data<LemmyContext>,
local_user_view: LocalUserView, local_user_view: LocalUserView,
) -> LemmyResult<Json<SuccessResponse>> { ) -> LemmyResult<Json<PostResponse>> {
let post_ids = HashSet::from_iter(data.post_ids.clone());
if post_ids.len() > MAX_API_PARAM_ELEMENTS {
Err(LemmyErrorType::TooManyItems)?;
}
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let post_id = data.post_id;
// Mark the post as hidden / unhidden // Mark the post as hidden / unhidden
if data.hide { if data.hide {
PostHide::hide(&mut context.pool(), post_ids, person_id) PostHide::hide(&mut context.pool(), post_id, person_id)
.await .await
.with_lemmy_type(LemmyErrorType::CouldntHidePost)?; .with_lemmy_type(LemmyErrorType::CouldntHidePost)?;
} else { } else {
PostHide::unhide(&mut context.pool(), post_ids, person_id) PostHide::unhide(&mut context.pool(), post_id, person_id)
.await .await
.with_lemmy_type(LemmyErrorType::CouldntHidePost)?; .with_lemmy_type(LemmyErrorType::CouldntHidePost)?;
} }
Ok(Json(SuccessResponse::default())) let post_view = PostView::read(
&mut context.pool(),
post_id,
Some(&local_user_view.local_user),
false,
)
.await?;
Ok(Json(PostResponse { post_view }))
} }

View file

@ -1,34 +1,38 @@
use actix_web::web::{Data, Json}; use actix_web::web::{Data, Json};
use lemmy_api_common::{context::LemmyContext, post::MarkPostAsRead, SuccessResponse}; use lemmy_api_common::{
context::LemmyContext,
post::{MarkPostAsRead, PostResponse},
};
use lemmy_db_schema::source::post::PostRead; use lemmy_db_schema::source::post::PostRead;
use lemmy_db_views::structs::LocalUserView; use lemmy_db_views::structs::{LocalUserView, PostView};
use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult, MAX_API_PARAM_ELEMENTS}; use lemmy_utils::error::{LemmyErrorExt, LemmyErrorType, LemmyResult};
use std::collections::HashSet;
#[tracing::instrument(skip(context))] #[tracing::instrument(skip(context))]
pub async fn mark_post_as_read( pub async fn mark_post_as_read(
data: Json<MarkPostAsRead>, data: Json<MarkPostAsRead>,
context: Data<LemmyContext>, context: Data<LemmyContext>,
local_user_view: LocalUserView, local_user_view: LocalUserView,
) -> LemmyResult<Json<SuccessResponse>> { ) -> LemmyResult<Json<PostResponse>> {
let post_ids = HashSet::from_iter(data.post_ids.clone());
if post_ids.len() > MAX_API_PARAM_ELEMENTS {
Err(LemmyErrorType::TooManyItems)?;
}
let person_id = local_user_view.person.id; let person_id = local_user_view.person.id;
let post_id = data.post_id;
// Mark the post as read / unread // Mark the post as read / unread
if data.read { if data.read {
PostRead::mark_as_read(&mut context.pool(), post_ids, person_id) PostRead::mark_as_read(&mut context.pool(), post_id, person_id)
.await .await
.with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)?; .with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)?;
} else { } else {
PostRead::mark_as_unread(&mut context.pool(), post_ids, person_id) PostRead::mark_as_unread(&mut context.pool(), post_id, person_id)
.await .await
.with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)?; .with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)?;
} }
let post_view = PostView::read(
&mut context.pool(),
post_id,
Some(&local_user_view.local_user),
false,
)
.await?;
Ok(Json(SuccessResponse::default())) Ok(Json(PostResponse { post_view }))
} }

View file

@ -152,7 +152,7 @@ pub struct RemovePost {
#[cfg_attr(feature = "full", ts(export))] #[cfg_attr(feature = "full", ts(export))]
/// Mark a post as read. /// Mark a post as read.
pub struct MarkPostAsRead { pub struct MarkPostAsRead {
pub post_ids: Vec<PostId>, pub post_id: PostId,
pub read: bool, pub read: bool,
} }
@ -162,7 +162,7 @@ pub struct MarkPostAsRead {
#[cfg_attr(feature = "full", ts(export))] #[cfg_attr(feature = "full", ts(export))]
/// Hide a post from list views /// Hide a post from list views
pub struct HidePost { pub struct HidePost {
pub post_ids: Vec<PostId>, pub post_id: PostId,
pub hide: bool, pub hide: bool,
} }

View file

@ -59,7 +59,7 @@ use lemmy_utils::{
use moka::future::Cache; use moka::future::Cache;
use regex::{escape, Regex, RegexSet}; use regex::{escape, Regex, RegexSet};
use rosetta_i18n::{Language, LanguageId}; use rosetta_i18n::{Language, LanguageId};
use std::{collections::HashSet, sync::LazyLock}; use std::sync::LazyLock;
use tracing::warn; use tracing::warn;
use url::{ParseError, Url}; use url::{ParseError, Url};
use urlencoding::encode; use urlencoding::encode;
@ -154,7 +154,7 @@ pub async fn mark_post_as_read(
post_id: PostId, post_id: PostId,
pool: &mut DbPool<'_>, pool: &mut DbPool<'_>,
) -> LemmyResult<()> { ) -> LemmyResult<()> {
PostRead::mark_as_read(pool, HashSet::from([post_id]), person_id) PostRead::mark_as_read(pool, post_id, person_id)
.await .await
.with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)?; .with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)?;
Ok(()) Ok(())

View file

@ -38,7 +38,6 @@ use diesel::{
TextExpressionMethods, TextExpressionMethods,
}; };
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use std::collections::HashSet;
#[async_trait] #[async_trait]
impl Crud for Post { impl Crud for Post {
@ -298,77 +297,67 @@ impl Saveable for PostSaved {
impl PostRead { impl PostRead {
pub async fn mark_as_read( pub async fn mark_as_read(
pool: &mut DbPool<'_>, pool: &mut DbPool<'_>,
post_ids: HashSet<PostId>, post_id: PostId,
person_id: PersonId, person_id: PersonId,
) -> Result<usize, Error> { ) -> Result<Self, Error> {
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
let forms = post_ids let form = PostReadForm { post_id, person_id };
.into_iter()
.map(|post_id| PostReadForm { post_id, person_id })
.collect::<Vec<PostReadForm>>();
insert_into(post_read::table) insert_into(post_read::table)
.values(forms) .values(form)
.on_conflict_do_nothing() .on_conflict_do_nothing()
.execute(conn) .get_result::<Self>(conn)
.await .await
} }
pub async fn mark_as_unread( pub async fn mark_as_unread(
pool: &mut DbPool<'_>, pool: &mut DbPool<'_>,
post_id_: HashSet<PostId>, post_id_: PostId,
person_id_: PersonId, person_id_: PersonId,
) -> Result<usize, Error> { ) -> Result<usize, Error> {
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::delete( let read_post = post_read::table
post_read::table .filter(post_read::post_id.eq(post_id_))
.filter(post_read::post_id.eq_any(post_id_)) .filter(post_read::person_id.eq(person_id_));
.filter(post_read::person_id.eq(person_id_)),
) diesel::delete(read_post).execute(conn).await
.execute(conn)
.await
} }
} }
impl PostHide { impl PostHide {
pub async fn hide( pub async fn hide(
pool: &mut DbPool<'_>, pool: &mut DbPool<'_>,
post_ids: HashSet<PostId>, post_id: PostId,
person_id: PersonId, person_id: PersonId,
) -> Result<usize, Error> { ) -> Result<Self, Error> {
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
let forms = post_ids let form = PostHideForm { post_id, person_id };
.into_iter()
.map(|post_id| PostHideForm { post_id, person_id })
.collect::<Vec<PostHideForm>>();
insert_into(post_hide::table) insert_into(post_hide::table)
.values(forms) .values(form)
.on_conflict_do_nothing() .on_conflict_do_nothing()
.execute(conn) .get_result::<Self>(conn)
.await .await
} }
pub async fn unhide( pub async fn unhide(
pool: &mut DbPool<'_>, pool: &mut DbPool<'_>,
post_id_: HashSet<PostId>, post_id_: PostId,
person_id_: PersonId, person_id_: PersonId,
) -> Result<usize, Error> { ) -> Result<usize, Error> {
let conn = &mut get_conn(pool).await?; let conn = &mut get_conn(pool).await?;
diesel::delete( let hidden_post = post_hide::table
post_hide::table .filter(post_hide::post_id.eq(post_id_))
.filter(post_hide::post_id.eq_any(post_id_)) .filter(post_hide::person_id.eq(person_id_));
.filter(post_hide::person_id.eq(person_id_)),
) diesel::delete(hidden_post).execute(conn).await
.execute(conn)
.await
} }
} }
#[cfg(test)] #[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(clippy::indexing_slicing)] #[allow(clippy::indexing_slicing)]
mod tests { mod tests {
@ -391,24 +380,22 @@ mod tests {
traits::{Crud, Likeable, Saveable}, traits::{Crud, Likeable, Saveable},
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,
}; };
use lemmy_utils::error::LemmyResult;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use serial_test::serial; use serial_test::serial;
use std::collections::HashSet;
use url::Url; use url::Url;
#[tokio::test] #[tokio::test]
#[serial] #[serial]
async fn test_crud() { async fn test_crud() -> LemmyResult<()> {
let pool = &build_db_pool_for_tests().await; let pool = &build_db_pool_for_tests().await;
let pool = &mut pool.into(); let pool = &mut pool.into();
let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()).await?;
.await
.unwrap();
let new_person = PersonInsertForm::test_form(inserted_instance.id, "jim"); let new_person = PersonInsertForm::test_form(inserted_instance.id, "jim");
let inserted_person = Person::create(pool, &new_person).await.unwrap(); let inserted_person = Person::create(pool, &new_person).await?;
let new_community = CommunityInsertForm::new( let new_community = CommunityInsertForm::new(
inserted_instance.id, inserted_instance.id,
@ -417,21 +404,21 @@ mod tests {
"pubkey".to_string(), "pubkey".to_string(),
); );
let inserted_community = Community::create(pool, &new_community).await.unwrap(); let inserted_community = Community::create(pool, &new_community).await?;
let new_post = PostInsertForm::new( let new_post = PostInsertForm::new(
"A test post".into(), "A test post".into(),
inserted_person.id, inserted_person.id,
inserted_community.id, inserted_community.id,
); );
let inserted_post = Post::create(pool, &new_post).await.unwrap(); let inserted_post = Post::create(pool, &new_post).await?;
let new_post2 = PostInsertForm::new( let new_post2 = PostInsertForm::new(
"A test post 2".into(), "A test post 2".into(),
inserted_person.id, inserted_person.id,
inserted_community.id, inserted_community.id,
); );
let inserted_post2 = Post::create(pool, &new_post2).await.unwrap(); let inserted_post2 = Post::create(pool, &new_post2).await?;
let expected_post = Post { let expected_post = Post {
id: inserted_post.id, id: inserted_post.id,
@ -451,9 +438,7 @@ mod tests {
embed_description: None, embed_description: None,
embed_video_url: None, embed_video_url: None,
thumbnail_url: None, thumbnail_url: None,
ap_id: Url::parse(&format!("https://lemmy-alpha/post/{}", inserted_post.id)) ap_id: Url::parse(&format!("https://lemmy-alpha/post/{}", inserted_post.id))?.into(),
.unwrap()
.into(),
local: true, local: true,
language_id: Default::default(), language_id: Default::default(),
featured_community: false, featured_community: false,
@ -468,7 +453,7 @@ mod tests {
score: 1, score: 1,
}; };
let inserted_post_like = PostLike::like(pool, &post_like_form).await.unwrap(); let inserted_post_like = PostLike::like(pool, &post_like_form).await?;
let expected_post_like = PostLike { let expected_post_like = PostLike {
post_id: inserted_post.id, post_id: inserted_post.id,
@ -483,7 +468,7 @@ mod tests {
person_id: inserted_person.id, person_id: inserted_person.id,
}; };
let inserted_post_saved = PostSaved::save(pool, &post_saved_form).await.unwrap(); let inserted_post_saved = PostSaved::save(pool, &post_saved_form).await?;
let expected_post_saved = PostSaved { let expected_post_saved = PostSaved {
post_id: inserted_post.id, post_id: inserted_post.id,
@ -491,54 +476,44 @@ mod tests {
published: inserted_post_saved.published, published: inserted_post_saved.published,
}; };
// Post Read // Mark 2 posts as read
let marked_as_read = PostRead::mark_as_read( PostRead::mark_as_read(pool, inserted_post.id, inserted_person.id).await?;
pool, PostRead::mark_as_read(pool, inserted_post2.id, inserted_person.id).await?;
HashSet::from([inserted_post.id, inserted_post2.id]),
inserted_person.id,
)
.await
.unwrap();
assert_eq!(2, marked_as_read);
let read_post = Post::read(pool, inserted_post.id).await.unwrap(); let read_post = Post::read(pool, inserted_post.id).await?;
let new_post_update = PostUpdateForm { let new_post_update = PostUpdateForm {
name: Some("A test post".into()), name: Some("A test post".into()),
..Default::default() ..Default::default()
}; };
let updated_post = Post::update(pool, inserted_post.id, &new_post_update) let updated_post = Post::update(pool, inserted_post.id, &new_post_update).await?;
.await
.unwrap();
let like_removed = PostLike::remove(pool, inserted_person.id, inserted_post.id) let like_removed = PostLike::remove(pool, inserted_person.id, inserted_post.id).await?;
.await
.unwrap();
assert_eq!(1, like_removed); assert_eq!(1, like_removed);
let saved_removed = PostSaved::unsave(pool, &post_saved_form).await.unwrap(); let saved_removed = PostSaved::unsave(pool, &post_saved_form).await?;
assert_eq!(1, saved_removed); assert_eq!(1, saved_removed);
let read_removed = PostRead::mark_as_unread(
pool,
HashSet::from([inserted_post.id, inserted_post2.id]),
inserted_person.id,
)
.await
.unwrap();
assert_eq!(2, read_removed);
let num_deleted = Post::delete(pool, inserted_post.id).await.unwrap() // mark some posts as unread
+ Post::delete(pool, inserted_post2.id).await.unwrap(); let read_removed_1 =
PostRead::mark_as_unread(pool, inserted_post.id, inserted_person.id).await?;
assert_eq!(1, read_removed_1);
let read_removed_2 =
PostRead::mark_as_unread(pool, inserted_post2.id, inserted_person.id).await?;
assert_eq!(1, read_removed_2);
let num_deleted =
Post::delete(pool, inserted_post.id).await? + Post::delete(pool, inserted_post2.id).await?;
assert_eq!(2, num_deleted); assert_eq!(2, num_deleted);
Community::delete(pool, inserted_community.id) Community::delete(pool, inserted_community.id).await?;
.await Person::delete(pool, inserted_person.id).await?;
.unwrap(); Instance::delete(pool, inserted_instance.id).await?;
Person::delete(pool, inserted_person.id).await.unwrap();
Instance::delete(pool, inserted_instance.id).await.unwrap();
assert_eq!(expected_post, read_post); assert_eq!(expected_post, read_post);
assert_eq!(expected_post, inserted_post); assert_eq!(expected_post, inserted_post);
assert_eq!(expected_post, updated_post); assert_eq!(expected_post, updated_post);
assert_eq!(expected_post_like, inserted_post_like); assert_eq!(expected_post_like, inserted_post_like);
assert_eq!(expected_post_saved, inserted_post_saved); assert_eq!(expected_post_saved, inserted_post_saved);
Ok(())
} }
} }

View file

@ -787,7 +787,7 @@ mod tests {
use lemmy_utils::error::LemmyResult; use lemmy_utils::error::LemmyResult;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use serial_test::serial; use serial_test::serial;
use std::{collections::HashSet, time::Duration}; use std::time::Duration;
use url::Url; use url::Url;
const POST_WITH_ANOTHER_TITLE: &str = "Another title"; const POST_WITH_ANOTHER_TITLE: &str = "Another title";
@ -1622,7 +1622,7 @@ mod tests {
// Mark a post as read // Mark a post as read
PostRead::mark_as_read( PostRead::mark_as_read(
pool, pool,
HashSet::from([data.inserted_bot_post.id]), data.inserted_bot_post.id,
data.local_user_view.person.id, data.local_user_view.person.id,
) )
.await?; .await?;
@ -1664,7 +1664,7 @@ mod tests {
// Mark a post as hidden // Mark a post as hidden
PostHide::hide( PostHide::hide(
pool, pool,
HashSet::from([data.inserted_bot_post.id]), data.inserted_bot_post.id,
data.local_user_view.person.id, data.local_user_view.person.id,
) )
.await?; .await?;