This commit is contained in:
Dessalines 2024-09-30 22:11:53 -04:00 committed by GitHub
commit 9ca78e1bc9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 107 additions and 124 deletions

View File

@ -27,7 +27,7 @@
"eslint": "^9.9.0", "eslint": "^9.9.0",
"eslint-plugin-prettier": "^5.1.3", "eslint-plugin-prettier": "^5.1.3",
"jest": "^29.5.0", "jest": "^29.5.0",
"lemmy-js-client": "0.20.0-alpha.11", "lemmy-js-client": "0.20.0-alpha.12",
"prettier": "^3.2.5", "prettier": "^3.2.5",
"ts-jest": "^29.1.0", "ts-jest": "^29.1.0",
"typescript": "^5.5.4", "typescript": "^5.5.4",

View File

@ -30,8 +30,8 @@ importers:
specifier: ^29.5.0 specifier: ^29.5.0
version: 29.7.0(@types/node@22.3.0) version: 29.7.0(@types/node@22.3.0)
lemmy-js-client: lemmy-js-client:
specifier: 0.20.0-alpha.11 specifier: 0.20.0-alpha.12
version: 0.20.0-alpha.11 version: 0.20.0-alpha.12
prettier: prettier:
specifier: ^3.2.5 specifier: ^3.2.5
version: 3.3.3 version: 3.3.3
@ -1175,8 +1175,8 @@ packages:
resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==}
engines: {node: '>=6'} engines: {node: '>=6'}
lemmy-js-client@0.20.0-alpha.11: lemmy-js-client@0.20.0-alpha.12:
resolution: {integrity: sha512-iRSG4xHMjPDIreQqVIoJ5JrMY71uk07G0Zbgyf068xKbib22J3+i1x/XgCTs6tiHlqTnw1Ig/KRq7p7qJoA4uw==} resolution: {integrity: sha512-+nknIpFAT25TnhObvPPCI0JhDxmTSfg3jbNm7f4RnwidRskjS8SraNFD4bXFfHf14lu61ZEiVe58+UhhRe2UdA==}
leven@3.1.0: leven@3.1.0:
resolution: {integrity: sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==} resolution: {integrity: sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==}
@ -3107,7 +3107,7 @@ snapshots:
kleur@3.0.3: {} kleur@3.0.3: {}
lemmy-js-client@0.20.0-alpha.11: {} lemmy-js-client@0.20.0-alpha.12: {}
leven@3.1.0: {} leven@3.1.0: {}

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

@ -156,7 +156,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,
} }
@ -166,7 +166,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;
@ -142,7 +142,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

@ -39,7 +39,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 {
@ -322,17 +321,15 @@ 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<usize, 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) .execute(conn)
.await .await
@ -340,35 +337,30 @@ impl PostRead {
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<usize, 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) .execute(conn)
.await .await
@ -376,23 +368,21 @@ impl PostHide {
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)]
#[expect(clippy::unwrap_used)] #[allow(clippy::indexing_slicing)]
mod tests { mod tests {
use crate::{ use crate::{
@ -415,24 +405,22 @@ mod tests {
utils::build_db_pool_for_tests, utils::build_db_pool_for_tests,
}; };
use chrono::DateTime; use chrono::DateTime;
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,
@ -441,27 +429,27 @@ 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 new_scheduled_post = PostInsertForm { let new_scheduled_post = PostInsertForm {
scheduled_publish_time: Some(DateTime::from_timestamp_nanos(i64::MAX)), scheduled_publish_time: Some(DateTime::from_timestamp_nanos(i64::MAX)),
..PostInsertForm::new("beans".into(), inserted_person.id, inserted_community.id) ..PostInsertForm::new("beans".into(), inserted_person.id, inserted_community.id)
}; };
let inserted_scheduled_post = Post::create(pool, &new_scheduled_post).await.unwrap(); let inserted_scheduled_post = Post::create(pool, &new_scheduled_post).await?;
let expected_post = Post { let expected_post = Post {
id: inserted_post.id, id: inserted_post.id,
@ -481,9 +469,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,
@ -499,7 +485,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,
@ -514,7 +500,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,
@ -522,63 +508,51 @@ 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();
// Scheduled post count // Scheduled post count
let scheduled_post_count = Post::user_scheduled_post_count(inserted_person.id, pool) let scheduled_post_count = Post::user_scheduled_post_count(inserted_person.id, pool).await?;
.await
.unwrap();
assert_eq!(1, scheduled_post_count); assert_eq!(1, scheduled_post_count);
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 =
+ Post::delete(pool, inserted_scheduled_post.id) PostRead::mark_as_unread(pool, inserted_post.id, inserted_person.id).await?;
.await assert_eq!(1, read_removed_1);
.unwrap(); 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?
+ Post::delete(pool, inserted_scheduled_post.id).await?;
assert_eq!(3, num_deleted); assert_eq!(3, num_deleted);
Community::delete(pool, inserted_community.id) Community::delete(pool, inserted_community.id).await?;
.await
.unwrap(); Person::delete(pool, inserted_person.id).await?;
Person::delete(pool, inserted_person.id).await.unwrap(); Instance::delete(pool, inserted_instance.id).await?;
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

@ -792,7 +792,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";
@ -1627,7 +1627,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?;
@ -1669,7 +1669,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?;