diff --git a/backend/alembic/versions/0108_roms_locked_fields.py b/backend/alembic/versions/0108_roms_locked_fields.py new file mode 100644 index 000000000..c4373ca6b --- /dev/null +++ b/backend/alembic/versions/0108_roms_locked_fields.py @@ -0,0 +1,80 @@ +"""Record which rom fields a user supplied by hand + +Uploading artwork stores the file and clears `url_cover`, so a stored cover +path with no url was the only thing separating a hand-supplied cover from a +scraped one. That signal cannot survive: `get_cover` returns no path when the +file is missing, and the scan writes that straight back to `path_cover_s`, so a +single scan run while the resources volume is unavailable erases it. The next +scan then reads the row as having no cover at all, adopts the provider url, and +replaces the user's cover with provider art once storage returns. + +`locked_fields` records the same fact durably, independent of what is on disk. + +The backfill is the load-bearing part: existing uploads are recognisable only by +the old inferred marker, and reading it once here is the last chance to do so. +Without it the first scan after upgrading would replace every uploaded cover in +every library. + +Manuals are deliberately not backfilled. An uploaded manual and a scraped one +share a path and neither clears `url_manual`, so nothing distinguishes them and +any guess would be wrong for half the rows. Manuals stay pinned by the scan, and +uploads made from here on are marked as they happen. + +Revision ID: 0108_roms_locked_fields +Revises: 0107_roms_dedup_cover_index +Create Date: 2026-08-08 00:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op + +from utils.database import CustomJSON + +# revision identifiers, used by Alembic. +revision = "0108_roms_locked_fields" +down_revision = "0107_roms_dedup_cover_index" +branch_labels = None +depends_on = None + + +def _roms_table() -> sa.TableClause: + return sa.table( + "roms", + sa.column("path_cover_s", sa.Text), + sa.column("url_cover", sa.Text), + sa.column("locked_fields", CustomJSON()), + ) + + +def upgrade() -> None: + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.add_column( + sa.Column("locked_fields", CustomJSON(), nullable=True), + if_not_exists=True, + ) + + roms = _roms_table() + connection = op.get_bind() + + connection.execute(roms.update().values(locked_fields=[])) + + # A stored cover path with an empty url is the pre-migration marker for an + # upload. Values go through the JSON type rather than a literal so each + # dialect serialises its own way. + connection.execute( + roms.update() + .where( + sa.and_( + roms.c.path_cover_s.isnot(None), + roms.c.path_cover_s != "", + sa.or_(roms.c.url_cover.is_(None), roms.c.url_cover == ""), + ) + ) + .values(locked_fields=["url_cover"]) + ) + + +def downgrade() -> None: + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.drop_column("locked_fields", if_exists=True) diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index e1375e5d5..d14783f8d 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -1847,7 +1847,13 @@ async def update_rom( if remove_cover: cleaned_data.update(await fs_resource_handler.remove_cover(rom)) - cleaned_data.update({"url_cover": ""}) + # Dropping the hand-supplied cover hands the slot back to the providers. + cleaned_data.update( + { + "url_cover": "", + "locked_fields": rom.locked_fields_without("url_cover"), + } + ) else: if artwork is not None and artwork.filename is not None: file_ext = validate_image_upload(artwork, label="Artwork") @@ -1857,11 +1863,14 @@ async def update_rom( path_cover_s, ) = await fs_resource_handler.store_artwork(rom, artwork_content, file_ext) + # Supplying a file is the explicit act that locks the cover; the + # lock outlives the file, so losing it to a scan can't unlock it. cleaned_data.update( { "url_cover": "", "path_cover_s": path_cover_s, "path_cover_l": path_cover_l, + "locked_fields": rom.locked_fields_with("url_cover"), } ) else: @@ -1881,6 +1890,11 @@ async def update_rom( "path_cover_l": path_cover_l, } ) + # Naming a source url is a handover back to the providers. + if "url_cover" in provided_fields and url_cover: + cleaned_data["locked_fields"] = rom.locked_fields_without( + "url_cover" + ) except ValidationError as e: log.error(f"Invalid cover URL in update_rom: {str(e)}") raise HTTPException(status_code=400, detail=str(e)) from e diff --git a/backend/endpoints/roms/manual.py b/backend/endpoints/roms/manual.py index 94b9aecbc..34198b823 100644 --- a/backend/endpoints/roms/manual.py +++ b/backend/endpoints/roms/manual.py @@ -120,10 +120,13 @@ async def add_rom_manuals( detail="There was an error uploading the manual", ) from exc + # An uploaded manual and a scraped one share this path and neither clears + # url_manual, so the lock is the only thing that will tell them apart. db_rom_handler.update_rom( id, { "path_manual": f"{manuals_path}/{rom.id}{ext}", + "locked_fields": rom.locked_fields_with("url_manual"), }, ) @@ -163,7 +166,14 @@ async def redownload_rom_manual( overwrite=True, url_manual=str(rom.url_manual), ) - db_rom_handler.update_rom(id, {"path_manual": path_manual}) + # Asking for the provider's manual back is a handover. + db_rom_handler.update_rom( + id, + { + "path_manual": path_manual, + "locked_fields": rom.locked_fields_without("url_manual"), + }, + ) log.info( f"Re-downloaded manual for {hl(rom.name or 'ROM', color=BLUE)} " f"[{hl(rom.fs_name)}]" @@ -384,6 +394,7 @@ async def delete_rom_manuals( { "path_manual": "", "url_manual": "", + "locked_fields": rom.locked_fields_without("url_manual"), }, ) @@ -400,6 +411,7 @@ async def delete_rom_manuals( { "path_manual": "", "url_manual": "", + "locked_fields": rom.locked_fields_without("url_manual"), }, ) except Exception as exc: diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index fcd0813ac..b6be3c7dd 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -442,6 +442,7 @@ async def scan_rom( "path_cover_l": rom.path_cover_l, "path_screenshots": rom.path_screenshots, "path_manual": rom.path_manual, + "locked_fields": rom.locked_fields, "igdb_id": rom.igdb_id, "moby_id": rom.moby_id, "ss_id": rom.ss_id, @@ -996,7 +997,10 @@ async def scan_rom( if fields["metadata_field"]: rom_attrs[fields["metadata_field"]] = {} - # Reset artwork fields so stale values are cleared when no source supplies them + # Reset artwork fields so stale values are cleared when no source supplies them. + # The locks go with them: a complete rescan deletes the resource files, so + # keeping one would leave a cover locked to a file that no longer exists and + # block any replacement from being fetched. rom_attrs.update( { "url_cover": "", @@ -1006,6 +1010,7 @@ async def scan_rom( "path_cover_l": "", "path_screenshots": [], "path_manual": "", + "locked_fields": [], } ) @@ -1064,14 +1069,13 @@ async def scan_rom( { "name": existing_name or matched_name or fs_name_no_tags or None, "summary": rom.summary or rom_attrs.get("summary") or None, - # Uploading artwork clears its source url while keeping the file, - # so a stored path with no url is user-supplied and stays put. - # Artwork that still carries a url came from a provider, and the - # freshly resolved url replaces it so a changed source or source - # priority reaches the download step. + # A locked cover was supplied by hand and stays put. Anything + # else came from a provider, and the freshly resolved url + # replaces it so a changed source or source priority reaches the + # download step. "url_cover": ( "" - if rom.path_cover_s and not rom.url_cover + if rom.is_field_locked("url_cover") else rom_attrs.get("url_cover") or None ), # A manual keeps its stored url because an uploaded manual and a diff --git a/backend/models/rom.py b/backend/models/rom.py index 105ed358a..3cb767736 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -482,6 +482,12 @@ class Rom(BaseModel): CustomJSON(), default=[], doc="URLs to screenshots stored in IGDB" ) + locked_fields: Mapped[list[str] | None] = mapped_column( + CustomJSON(), + default=[], + doc="Fields a user supplied by hand, which scans must not overwrite", + ) + revision: Mapped[str | None] = mapped_column(String(length=100)) version: Mapped[str | None] = mapped_column(String(length=100)) regions: Mapped[list[str] | None] = mapped_column(CustomJSON(), default=[]) @@ -651,6 +657,18 @@ class Rom(BaseModel): or (self.launchbox_metadata or {}).get("video_path") ) + def is_field_locked(self, field: str) -> bool: + """Whether a user supplied this field by hand, so scans must leave it.""" + return field in (self.locked_fields or []) + + def locked_fields_with(self, field: str) -> list[str]: + """This rom's locks plus ``field``, for handing to an update.""" + return sorted({*(self.locked_fields or []), field}) + + def locked_fields_without(self, field: str) -> list[str]: + """This rom's locks minus ``field``, for handing to an update.""" + return [f for f in (self.locked_fields or []) if f != field] + @property def is_unidentified(self) -> bool: return ( diff --git a/backend/tests/endpoints/roms/test_manual.py b/backend/tests/endpoints/roms/test_manual.py index 31e4888fe..8334ab0fa 100644 --- a/backend/tests/endpoints/roms/test_manual.py +++ b/backend/tests/endpoints/roms/test_manual.py @@ -89,6 +89,9 @@ def test_upload_manual_to_resources_success( assert written.read_bytes() == PDF_BYTES refreshed = db_rom_handler.get_rom(rom.id) assert refreshed.path_manual == f"{rom.fs_resources_path}/manual/{rom.id}.pdf" + # An uploaded manual and a scraped one land at the same path and neither + # clears url_manual, so the lock is the only thing telling them apart. + assert refreshed.locked_fields == ["url_manual"] def test_upload_markdown_manual_to_resources_preserves_extension( @@ -252,7 +255,11 @@ def test_redownload_manual_success( monkeypatch: pytest.MonkeyPatch, ): db_rom_handler.update_rom( - rom.id, {"url_manual": "https://screenscraper.fr/api/manual.pdf"} + rom.id, + { + "url_manual": "https://screenscraper.fr/api/manual.pdf", + "locked_fields": ["url_manual"], + }, ) fake_path = f"{rom.fs_resources_path}/manual/{rom.id}.pdf" monkeypatch.setattr( @@ -269,6 +276,8 @@ def test_redownload_manual_success( assert response.status_code == status.HTTP_200_OK refreshed = db_rom_handler.get_rom(rom.id) assert refreshed.path_manual == fake_path + # Asking for the provider's manual back is a handover. + assert refreshed.locked_fields == [] # ---------- DELETE /api/roms/{id}/manuals (resources) ---------- @@ -305,6 +314,7 @@ def test_delete_manual_success( { "path_manual": f"{rom.fs_resources_path}/manual/{rom.id}.pdf", "url_manual": "https://screenscraper.fr/api/manual.pdf", + "locked_fields": ["url_manual"], }, ) monkeypatch.setattr( @@ -325,6 +335,8 @@ def test_delete_manual_success( refreshed = db_rom_handler.get_rom(rom.id) assert refreshed.path_manual == "" assert refreshed.url_manual == "" + # Deleting the hand-supplied manual hands the slot back to the providers. + assert refreshed.locked_fields == [] # ---------- DELETE /api/roms/{id}/manuals/files/{file_id} ---------- diff --git a/backend/tests/endpoints/roms/test_rom.py b/backend/tests/endpoints/roms/test_rom.py index ff191ef73..30ffcee7d 100644 --- a/backend/tests/endpoints/roms/test_rom.py +++ b/backend/tests/endpoints/roms/test_rom.py @@ -779,6 +779,55 @@ def test_update_rom_artwork_uses_detected_extension( assert file_ext == "png" +@patch.object( + FSResourcesHandler, + "store_artwork", + new_callable=AsyncMock, + return_value=("path/to/big.png", "path/to/small.png"), +) +def test_update_rom_artwork_locks_the_cover( + store_artwork_mock: AsyncMock, + client: TestClient, + access_token: str, + rom: Rom, +): + # Supplying a file is the explicit act that locks the cover. Scans read this + # rather than inferring it from path_cover_s, which they themselves clear + # whenever the file is unreadable. + response = client.put( + f"/api/roms/{rom.id}", + headers={"Authorization": f"Bearer {access_token}"}, + files={"artwork": ("cover.png", _PNG_BYTES, "image/png")}, + ) + assert response.status_code == status.HTTP_200_OK + + assert db_rom_handler.get_rom(rom.id).locked_fields == ["url_cover"] + + +@patch.object( + FSResourcesHandler, + "remove_cover", + new_callable=AsyncMock, + return_value={"path_cover_s": "", "path_cover_l": ""}, +) +def test_remove_cover_releases_the_lock( + remove_cover_mock: AsyncMock, + client: TestClient, + access_token: str, + rom: Rom, +): + # Dropping the hand-supplied cover hands the slot back to the providers. + db_rom_handler.update_rom(rom.id, {"locked_fields": ["url_cover"]}) + + response = client.put( + f"/api/roms/{rom.id}?remove_cover=true", + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == status.HTTP_200_OK + + assert db_rom_handler.get_rom(rom.id).locked_fields == [] + + def test_delete_roms(client: TestClient, access_token: str, rom: Rom): response = client.post( "/api/roms/delete", diff --git a/backend/tests/handler/test_fastapi.py b/backend/tests/handler/test_fastapi.py index 2ba6ff04e..bd7bc9393 100644 --- a/backend/tests/handler/test_fastapi.py +++ b/backend/tests/handler/test_fastapi.py @@ -567,9 +567,8 @@ async def test_update_scan_replaces_scraped_cover_url( async def test_update_scan_keeps_uploaded_cover( mock_ss_get_by_id, mock_playmatch_enabled ): - """Uploading artwork stores the file and clears url_cover. That pairing is the - only thing separating a hand-supplied cover from a scraped one, so the provider - url must not be adopted over it.""" + """Uploading artwork locks the cover, so the provider url must not be adopted + over it.""" mock_ss_get_by_id.return_value = SSRom( ss_id=321, name="Game", @@ -577,7 +576,36 @@ async def test_update_scan_keeps_uploaded_cover( ) platform = _ss_quota_platform() - rom = _scraped_cover_rom(platform, url_cover="") + rom = _scraped_cover_rom(platform, url_cover="", locked_fields=["url_cover"]) + + result = await _update_scan(platform, rom) + + assert result.url_cover == "" + assert result.locked_fields == ["url_cover"] + + +@patch.object(meta_playmatch_handler, "is_enabled", return_value=False) +@patch.object(meta_ss_handler, "get_rom_by_id", new_callable=AsyncMock) +async def test_update_scan_keeps_locked_cover_with_no_stored_path( + mock_ss_get_by_id, mock_playmatch_enabled +): + """The lock has to outlive path_cover_s. That column tracks the filesystem and + a scan clears it whenever the file is unreadable, so inferring the lock from it + meant one scan against unavailable storage handed the cover to the provider.""" + mock_ss_get_by_id.return_value = SSRom( + ss_id=321, + name="Game", + url_cover="https://ss.fr/media?media=box-2D&id=new", + ) + + platform = _ss_quota_platform() + rom = _scraped_cover_rom( + platform, + url_cover="", + path_cover_s="", + path_cover_l="", + locked_fields=["url_cover"], + ) result = await _update_scan(platform, rom)