mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 10:01:00 +01:00
Keep a save's or state's thumbnail while something still shows it
Deleting a save or state removed its thumbnail row and file unconditionally, so a save and a state sharing a stem lost the shared preview when either one went. Every delete path (single and bulk deletes, slot pruning, streaming history pruning) now goes through release_thumbnail, which keeps: - a thumbnail another save or state still matches by name, checked in SQL the way their thumbnail lookup matches, so it follows the database collation; - a gallery screenshot that only shares the stem by chance; - the file, when dropping the row, if another row spells the same file in a different case on a case-insensitive filesystem. Renaming reuses the same is_bound check to decide whether a thumbnail is shared, replacing the casefold helper. Addresses Greptile's review on #4749. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,7 +13,7 @@ from endpoints.responses.assets import SaveSchema, SaveSummarySchema, SlotSummar
|
||||
from endpoints.responses.device import DeviceSyncSchema
|
||||
from endpoints.roms import refresh_affected_smart_collections
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from handler.asset_store import remove_asset_file, remove_screenshot, rename_asset
|
||||
from handler.asset_store import release_thumbnail, remove_asset_file, rename_asset
|
||||
from handler.auth.constants import Scope
|
||||
from handler.auth.dependencies import assert_rom_visible
|
||||
from handler.database import (
|
||||
@@ -110,7 +110,7 @@ async def _delete_save(save: Save) -> None:
|
||||
"""Drop a save row with its file and screenshot."""
|
||||
db_save_handler.delete_save(save.id)
|
||||
await remove_asset_file(save.full_path, "Save file")
|
||||
await remove_screenshot(save.screenshot)
|
||||
await release_thumbnail(save.screenshot)
|
||||
|
||||
|
||||
async def _prune_slot(user_id: int, rom_id: int, slot: str, keep: int) -> None:
|
||||
@@ -119,7 +119,7 @@ async def _prune_slot(user_id: int, rom_id: int, slot: str, keep: int) -> None:
|
||||
user_id=user_id, rom_id=rom_id, slot=slot, keep=keep
|
||||
):
|
||||
await remove_asset_file(f"{file_path}/{file_name}", "Save file")
|
||||
await remove_screenshot(
|
||||
await release_thumbnail(
|
||||
db_screenshot_handler.get_screenshot(
|
||||
rom_id=rom_id,
|
||||
user_id=user_id,
|
||||
|
||||
@@ -9,8 +9,8 @@ from endpoints.responses.assets import StateSchema
|
||||
from endpoints.roms import refresh_affected_smart_collections
|
||||
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
||||
from handler.asset_store import (
|
||||
release_thumbnail,
|
||||
remove_asset_file,
|
||||
remove_screenshot,
|
||||
rename_asset,
|
||||
store_screenshot,
|
||||
store_state_file,
|
||||
@@ -36,7 +36,7 @@ async def _delete_state(state: State) -> None:
|
||||
"""Drop a state row with its file and screenshot."""
|
||||
db_state_handler.delete_state(state.id)
|
||||
await remove_asset_file(state.full_path, "State file")
|
||||
await remove_screenshot(state.screenshot)
|
||||
await release_thumbnail(state.screenshot)
|
||||
|
||||
|
||||
def _owned_state_or_404(id: int, user_id: int) -> State:
|
||||
|
||||
@@ -134,14 +134,23 @@ async def remove_asset_file(file_path: str, what: str) -> None:
|
||||
log.error(f"{what} {hl(file_path)} not found on disk")
|
||||
|
||||
|
||||
async def remove_screenshot(screenshot: Screenshot | None) -> None:
|
||||
"""Drop a save's or state's screenshot row and file, if it has one."""
|
||||
if not screenshot:
|
||||
async def release_thumbnail(screenshot: Screenshot | None) -> None:
|
||||
"""Drop a deleted save's or state's thumbnail, unless something still shows it."""
|
||||
# A gallery screenshot sharing the stem is bound by chance, so it stays put.
|
||||
if not screenshot or screenshot.is_gallery:
|
||||
return
|
||||
# A save and a state of one stem share a thumbnail; the other keeps it.
|
||||
if db_screenshot_handler.is_bound(screenshot):
|
||||
return
|
||||
db_screenshot_handler.delete_screenshot(screenshot.id)
|
||||
await remove_asset_file(
|
||||
f"{screenshot.file_path}/{screenshot.file_name}", "Screenshot file"
|
||||
)
|
||||
path = f"{screenshot.file_path}/{screenshot.file_name}"
|
||||
# A filesystem that ignores case holds another row's spelling as this file.
|
||||
if any(
|
||||
fs_asset_handler.is_same_file(path, f"{variant.file_path}/{variant.file_name}")
|
||||
for variant in db_screenshot_handler.get_name_variants(screenshot)
|
||||
):
|
||||
return
|
||||
await remove_asset_file(path, "Screenshot file")
|
||||
|
||||
|
||||
def _name_taken(file_name: str) -> HTTPException:
|
||||
@@ -155,15 +164,6 @@ def _is_same(a: Save | State, b: Save | State) -> bool:
|
||||
return type(a) is type(b) and a.id == b.id
|
||||
|
||||
|
||||
def _binds(asset: Save | State, screenshot: Screenshot) -> bool:
|
||||
"""Whether `asset.screenshot` can resolve to `screenshot`, by its name match."""
|
||||
names = {asset.file_name.casefold(), asset.file_name_no_ext.casefold()}
|
||||
return (
|
||||
screenshot.file_name.casefold() in names
|
||||
or screenshot.file_name_no_ext.casefold() in names
|
||||
)
|
||||
|
||||
|
||||
async def _move_asset_files(
|
||||
asset: Save | State,
|
||||
new_name: str,
|
||||
@@ -269,8 +269,8 @@ async def rename_asset[AssetT: (Save, State)](asset: AssetT, file_name: str) ->
|
||||
f"{new_stem}{os.path.splitext(thumbnail.file_name)[1]}" if thumbnail else ""
|
||||
)
|
||||
# A save and a state of one stem share a thumbnail; the other keeps it.
|
||||
copy_thumbnail = thumbnail is not None and any(
|
||||
_binds(other, thumbnail) for other in others
|
||||
copy_thumbnail = thumbnail is not None and db_screenshot_handler.is_bound(
|
||||
thumbnail, ignoring=asset
|
||||
)
|
||||
# The new name still resolves the shared one, by stem or through a
|
||||
# collation that ignores case.
|
||||
|
||||
@@ -2,12 +2,12 @@ from collections.abc import Sequence
|
||||
from functools import partial
|
||||
|
||||
import pydash
|
||||
from sqlalchemy import case, delete, or_, select, update
|
||||
from sqlalchemy import case, delete, func, or_, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.sql import Delete, Select, Update
|
||||
|
||||
from decorators.database import begin_session
|
||||
from models.assets import Screenshot
|
||||
from models.assets import Save, Screenshot, State
|
||||
from models.base import with_file_name_parts
|
||||
|
||||
from .base_handler import DBBaseHandler
|
||||
@@ -83,6 +83,44 @@ class DBScreenshotsHandler(DBBaseHandler):
|
||||
) -> Screenshot | None:
|
||||
return session.get(Screenshot, id)
|
||||
|
||||
@begin_session
|
||||
def is_bound(
|
||||
self,
|
||||
screenshot: Screenshot,
|
||||
ignoring: Save | State | None = None,
|
||||
session: Session = None, # type: ignore
|
||||
) -> bool:
|
||||
"""Whether a save or state other than `ignoring` matches the screenshot
|
||||
by name, the way their thumbnail lookup does."""
|
||||
names = pydash.compact([screenshot.file_name, screenshot.file_name_no_ext])
|
||||
for model in (Save, State):
|
||||
query = select(model.id).filter(
|
||||
model.rom_id == screenshot.rom_id,
|
||||
model.user_id == screenshot.user_id,
|
||||
or_(model.file_name.in_(names), model.file_name_no_ext.in_(names)),
|
||||
)
|
||||
if isinstance(ignoring, model):
|
||||
query = query.filter(model.id != ignoring.id)
|
||||
if session.scalar(query.limit(1)) is not None:
|
||||
return True
|
||||
return False
|
||||
|
||||
@begin_session
|
||||
def get_name_variants(
|
||||
self,
|
||||
screenshot: Screenshot,
|
||||
session: Session = None, # type: ignore
|
||||
) -> Sequence[Screenshot]:
|
||||
"""Other screenshots in the same folder whose name differs only in case."""
|
||||
query = self.filter(
|
||||
select(Screenshot), rom_id=screenshot.rom_id, user_id=screenshot.user_id
|
||||
).filter(
|
||||
Screenshot.id != screenshot.id,
|
||||
Screenshot.file_path == screenshot.file_path,
|
||||
func.lower(Screenshot.file_name) == screenshot.file_name.lower(),
|
||||
)
|
||||
return session.scalars(query).all()
|
||||
|
||||
@begin_session
|
||||
def get_rom_gallery_screenshots(
|
||||
self,
|
||||
|
||||
@@ -29,10 +29,9 @@ from urllib.parse import quote
|
||||
from fastapi import HTTPException
|
||||
|
||||
from config import STREAMING_STATE_HISTORY_LIMIT
|
||||
from handler.asset_store import store_screenshot, store_state_file
|
||||
from handler.asset_store import release_thumbnail, store_screenshot, store_state_file
|
||||
from handler.database import (
|
||||
db_rom_handler,
|
||||
db_screenshot_handler,
|
||||
db_state_handler,
|
||||
db_user_handler,
|
||||
)
|
||||
@@ -328,9 +327,14 @@ async def prune_state_history(
|
||||
screenshot = state.screenshot
|
||||
db_state_handler.delete_state(state.id)
|
||||
await _remove_pruned_file(f"{state.file_path}/{state.file_name}")
|
||||
if screenshot is not None:
|
||||
db_screenshot_handler.delete_screenshot(screenshot.id)
|
||||
await _remove_pruned_file(f"{screenshot.file_path}/{screenshot.file_name}")
|
||||
try:
|
||||
await release_thumbnail(screenshot)
|
||||
except OSError as exc:
|
||||
log.error(
|
||||
"could not remove the pruned screenshot of %s, leaving it orphaned: %s",
|
||||
state.file_name,
|
||||
exc,
|
||||
)
|
||||
if stale:
|
||||
log.info(
|
||||
"pruned %d state(s) past the %d limit, rom=%s",
|
||||
|
||||
@@ -15,9 +15,16 @@ from handler.database import (
|
||||
db_device_save_sync_handler,
|
||||
db_save_handler,
|
||||
db_screenshot_handler,
|
||||
db_state_handler,
|
||||
)
|
||||
from handler.database.base_handler import sync_session
|
||||
from models.assets import ASSET_LABEL_MAX_LENGTH, ASSET_LABELS_MAX, Save, Screenshot
|
||||
from models.assets import (
|
||||
ASSET_LABEL_MAX_LENGTH,
|
||||
ASSET_LABELS_MAX,
|
||||
Save,
|
||||
Screenshot,
|
||||
State,
|
||||
)
|
||||
from models.device import Device
|
||||
from models.permission import HiddenEntity, PermEntity
|
||||
from models.platform import Platform
|
||||
@@ -2323,6 +2330,51 @@ class TestAutocleanupScreenshots:
|
||||
assert (screenshot is None) == (i in evicted)
|
||||
|
||||
|
||||
class TestSaveDeleteThumbnail:
|
||||
def test_a_thumbnail_a_state_still_shows_stays(
|
||||
self,
|
||||
client,
|
||||
access_token: str,
|
||||
_isolated_assets_dir,
|
||||
rom: Rom,
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
save: Save,
|
||||
):
|
||||
# Same stem as the save, so both resolve `test_save.png`.
|
||||
db_state_handler.add_state(
|
||||
State(
|
||||
rom_id=rom.id,
|
||||
user_id=admin_user.id,
|
||||
file_name="test_save.state",
|
||||
file_path=f"{platform.slug}/states",
|
||||
file_size_bytes=1,
|
||||
)
|
||||
)
|
||||
thumbnail = db_screenshot_handler.add_screenshot(
|
||||
Screenshot(
|
||||
rom_id=rom.id,
|
||||
user_id=admin_user.id,
|
||||
file_name="test_save.png",
|
||||
file_path=f"{platform.slug}/screenshots",
|
||||
file_size_bytes=3,
|
||||
)
|
||||
)
|
||||
path = _isolated_assets_dir / thumbnail.file_path / thumbnail.file_name
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_bytes(b"PNG")
|
||||
|
||||
response = client.post(
|
||||
"/api/saves/delete",
|
||||
json={"saves": [save.id]},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert db_screenshot_handler.get_screenshot_by_id(thumbnail.id) is not None
|
||||
assert path.read_bytes() == b"PNG"
|
||||
|
||||
|
||||
class TestUploadSizeLimit:
|
||||
def test_rejects_oversized_save_file(self, client, access_token: str, rom: Rom):
|
||||
with mock.patch.object(uploads, "MAX_ASSET_UPLOAD_SIZE_BYTES", 32):
|
||||
|
||||
@@ -468,6 +468,109 @@ def test_delete_state_removes_file_and_screenshot(
|
||||
assert mock_remove.call_count == 2
|
||||
|
||||
|
||||
class TestStateDeleteThumbnail:
|
||||
"""Deleting a state takes its thumbnail only when nothing else shows it."""
|
||||
|
||||
@pytest.fixture
|
||||
def screenshots_dir(self, _isolated_assets_dir, platform: Platform):
|
||||
path = _isolated_assets_dir / platform.slug / "screenshots"
|
||||
path.mkdir(parents=True)
|
||||
return path
|
||||
|
||||
def _add_screenshot(
|
||||
self, rom: Rom, user: User, platform: Platform, file_name: str, **fields
|
||||
) -> Screenshot:
|
||||
return db_screenshot_handler.add_screenshot(
|
||||
Screenshot(
|
||||
rom_id=rom.id,
|
||||
user_id=user.id,
|
||||
file_name=file_name,
|
||||
file_path=f"{platform.slug}/screenshots",
|
||||
file_size_bytes=3,
|
||||
**fields,
|
||||
)
|
||||
)
|
||||
|
||||
def _delete(self, client, token: str, state_id: int):
|
||||
return client.post(
|
||||
"/api/states/delete", json={"states": [state_id]}, headers=_auth(token)
|
||||
)
|
||||
|
||||
def test_a_thumbnail_a_save_still_shows_stays(
|
||||
self,
|
||||
client,
|
||||
access_token: str,
|
||||
rom: Rom,
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
state: State,
|
||||
screenshots_dir,
|
||||
):
|
||||
db_save_handler.add_save(
|
||||
Save(
|
||||
rom_id=rom.id,
|
||||
user_id=admin_user.id,
|
||||
file_name="test_state.srm",
|
||||
file_path=f"{platform.slug}/saves",
|
||||
file_size_bytes=1,
|
||||
)
|
||||
)
|
||||
thumbnail = self._add_screenshot(rom, admin_user, platform, "test_state.png")
|
||||
(screenshots_dir / "test_state.png").write_bytes(b"PNG")
|
||||
|
||||
response = self._delete(client, access_token, state.id)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert db_screenshot_handler.get_screenshot_by_id(thumbnail.id) is not None
|
||||
assert (screenshots_dir / "test_state.png").read_bytes() == b"PNG"
|
||||
|
||||
def test_a_gallery_screenshot_sharing_the_stem_stays(
|
||||
self,
|
||||
client,
|
||||
access_token: str,
|
||||
rom: Rom,
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
state: State,
|
||||
screenshots_dir,
|
||||
):
|
||||
gallery = self._add_screenshot(
|
||||
rom, admin_user, platform, "test_state.png", is_gallery=True
|
||||
)
|
||||
(screenshots_dir / "test_state.png").write_bytes(b"PNG")
|
||||
|
||||
response = self._delete(client, access_token, state.id)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert db_screenshot_handler.get_screenshot_by_id(gallery.id) is not None
|
||||
assert (screenshots_dir / "test_state.png").read_bytes() == b"PNG"
|
||||
|
||||
def test_a_file_another_row_spells_differently_stays(
|
||||
self,
|
||||
client,
|
||||
access_token: str,
|
||||
rom: Rom,
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
state: State,
|
||||
screenshots_dir,
|
||||
):
|
||||
variant = self._add_screenshot(rom, admin_user, platform, "Test_state.png")
|
||||
# Newer, so the state resolves it whether or not lookups ignore case.
|
||||
thumbnail = self._add_screenshot(rom, admin_user, platform, "test_state.png")
|
||||
(screenshots_dir / "test_state.png").write_bytes(b"PNG")
|
||||
# A second link stands in for a case-insensitive filesystem's alias.
|
||||
os.link(screenshots_dir / "test_state.png", screenshots_dir / "Test_state.png")
|
||||
|
||||
response = self._delete(client, access_token, state.id)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert db_screenshot_handler.get_screenshot_by_id(thumbnail.id) is None
|
||||
assert db_screenshot_handler.get_screenshot_by_id(variant.id) is not None
|
||||
assert (screenshots_dir / "test_state.png").read_bytes() == b"PNG"
|
||||
assert (screenshots_dir / "Test_state.png").read_bytes() == b"PNG"
|
||||
|
||||
|
||||
class TestStateFavoritesAndLabels:
|
||||
"""Owner-only annotations on a state: the star and the free-text labels."""
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ from handler.database import (
|
||||
db_play_session_handler,
|
||||
db_rom_handler,
|
||||
db_save_handler,
|
||||
db_screenshot_handler,
|
||||
db_state_handler,
|
||||
db_user_handler,
|
||||
)
|
||||
@@ -3532,6 +3533,30 @@ def test_prune_state_history_drops_oldest_past_limit(rom: Rom, admin_user: User)
|
||||
}
|
||||
|
||||
|
||||
def test_prune_state_history_drops_the_pruned_thumbnail(rom: Rom, admin_user: User):
|
||||
for day in range(1, 4):
|
||||
_add_state_at(rom, admin_user, f"Game.2026010{day}-000000000000.01.p2s", day)
|
||||
thumbnail = db_screenshot_handler.add_screenshot(
|
||||
Screenshot(
|
||||
rom_id=rom.id,
|
||||
user_id=admin_user.id,
|
||||
file_name="Game.20260101-000000000000.01.png",
|
||||
file_path=f"{rom.platform_slug}/screenshots",
|
||||
file_size_bytes=3,
|
||||
)
|
||||
)
|
||||
with (
|
||||
patch("handler.streaming.states.STREAMING_STATE_HISTORY_LIMIT", 2),
|
||||
patch(
|
||||
"handler.filesystem.fs_asset_handler.remove_file", new=AsyncMock()
|
||||
) as remove,
|
||||
):
|
||||
asyncio.run(states.prune_state_history(admin_user, rom, "pcsx2"))
|
||||
|
||||
assert remove.await_count == 2
|
||||
assert db_screenshot_handler.get_screenshot_by_id(thumbnail.id) is None
|
||||
|
||||
|
||||
# _store_state_screenshot rejects anything without PNG magic, so fixtures that
|
||||
# reach it need real header bytes rather than a stand-in string.
|
||||
_PNG = b"\x89PNG\r\n\x1a\n" + b"pixels"
|
||||
|
||||
Reference in New Issue
Block a user