Fix issue with avatar / icon deletion when saving settings. (#4774)

* Fix issue with avatar / icon deletion when saving settings.

- Fixes #4763

* Update crates/api_common/src/request.rs

Co-authored-by: dullbananas <dull.bananas0@gmail.com>

* Fixing an existing test, and adding another for replace images.

---------

Co-authored-by: dullbananas <dull.bananas0@gmail.com>
This commit is contained in:
Dessalines 2024-06-04 08:28:22 -04:00 committed by GitHub
parent 9ceb5b6386
commit 8bf17946bd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 15 additions and 6 deletions

View File

@ -186,10 +186,16 @@ test("Set a new avatar, old avatar is deleted", async () => {
expect(upload2.url).toBeDefined(); expect(upload2.url).toBeDefined();
let form2 = { let form2 = {
avatar: upload1.url, avatar: upload2.url,
}; };
await saveUserSettings(alpha, form2); await saveUserSettings(alpha, form2);
// make sure only the new avatar is kept // make sure only the new avatar is kept
const listMediaRes2 = await alphaImage.listMedia(); const listMediaRes2 = await alphaImage.listMedia();
expect(listMediaRes2.images.length).toBe(1); expect(listMediaRes2.images.length).toBe(1);
// Upload that same form2 avatar, make sure it isn't replaced / deleted
await saveUserSettings(alpha, form2);
// make sure only the new avatar is kept
const listMediaRes3 = await alphaImage.listMedia();
expect(listMediaRes3.images.length).toBe(1);
}); });

View File

@ -338,16 +338,19 @@ async fn is_image_content_type(client: &ClientWithMiddleware, url: &Url) -> Lemm
} }
} }
/// When adding a new avatar or similar image, delete the old one. /// When adding a new avatar, banner or similar image, delete the old one.
pub async fn replace_image( pub async fn replace_image(
new_image: &Option<String>, new_image: &Option<String>,
old_image: &Option<DbUrl>, old_image: &Option<DbUrl>,
context: &Data<LemmyContext>, context: &Data<LemmyContext>,
) -> LemmyResult<()> { ) -> LemmyResult<()> {
if new_image.is_some() { if let (Some(new_image), Some(old_image)) = (new_image, old_image) {
// Ignore errors because image may be stored externally. // Note: Oftentimes front ends will include the current image in the form.
if let Some(avatar) = &old_image { // In this case, deleting `old_image` would also be deletion of `new_image`,
let image = LocalImage::delete_by_url(&mut context.pool(), avatar) // so the deletion must be skipped for the image to be kept.
if new_image != old_image.as_str() {
// Ignore errors because image may be stored externally.
let image = LocalImage::delete_by_url(&mut context.pool(), old_image)
.await .await
.ok(); .ok();
if let Some(image) = image { if let Some(image) = image {