Files
romm/backend/endpoints/configs.py
Georges-Antoine Assi 05bf29fe09 feat(converto): read per-file title ids with rom-converto during scans (#5031)
* feat(converto): read per-file title ids with rom-converto during scans

The title-id half of #5002: rom-converto's info runs fill rom_files.title_id
and title_version, sigil fills what rom-converto can't read and keeps owning
save targets, and roms in a scan batch share info runs of up to 64 files.
A converto_read_at marker lets quick scans backfill files rom-converto has
not read yet. converto.scan_metadata (config.yml only) turns it off.

The other per-file fields and embedded images stay out until a UI reads them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): name the same-content check that keeps unread title ids

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): queue unread files in one pass over the built rows

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(converto): address Greptile review on #5031

- A file refresh now persists converto_read_at when rom-converto's read
  confirms a reused row's stored title id, so the file isn't re-read on
  every refresh.
- RomConvertoService.read_infos splits its paths into info runs of at
  most INFO_BATCH_SIZE, so a rom with many files can't send them all
  through one run.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(converto): apply code-review fixes

- A stored file title id counts as rom-converto's only once rom-converto
  has read the row, so a stale sigil id can't override a fresh extraction.
- Fresh hashes decide whether unread title ids still describe a file,
  ahead of a size and mtime a copy can preserve.
- One rom's failed candidate listing no longer aborts its scan batch.
- The info paths file's cleanup can't raise out of read_infos.
- _rom_file_order sorts by Path like _TitleIdSource.order.
- Restored the in-place reconcile test for _identify_rom.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): apply simplify pass

- sync_rom_files reads 'rom-converto read this pass' off converto_read_at
  instead of an inspected set threaded through ParsedRomFiles, FSRom, the
  scan socket and the refresh.
- One _converto_may_read check serves the scan and the batch candidates.
- converto_candidates reuses _list_rom_dir, validates paths off the event
  loop and is best-effort itself, so the scan socket gathers it plainly.
- get_rom_files builds rom-converto paths from the validated rom dir
  instead of validating each file again.
- _rom_level_identity returns early on sigil's extraction.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(converto): apply review-polish pass

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): drop the shared info batch

Sharing rom-converto info runs across a scan batch saved about 2 ms per
rom (one process start) in exchange for a second directory walk per
rebuilt rom, the RomConvertoInfoBatch bookkeeping and the scan socket
wiring. Each rom now reads its own files; read_infos still caps a run
at INFO_RUN_MAX_FILES.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): name the rom-converto columns inline

Drops ROM_FILE_CONVERTO_COLUMNS and ROM_FILE_CONVERTO_KEPT_COLUMNS, so
_copy_scanned_columns keeps master's frozenset keep_when_unset.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-02 13:49:40 -04:00

388 lines
14 KiB
Python

from fastapi import HTTPException, Request, status
from pydantic import BaseModel, Field, field_validator
from adapters.services.rom_converto import (
LIBRARY_TARGETS_BY_PLATFORM,
normalize_platform_formats,
)
from config.config_manager import (
CONVERTO_INT_MINIMUMS,
DEFAULT_EXCLUDED_EXTENSIONS,
DEFAULT_EXCLUDED_FILES,
DEFAULT_EXCLUDED_MULTI_FILE_DIRS,
DEFAULT_EXCLUDED_PLATFORM_DIRS,
VALID_GAMELIST_IMAGE_TYPES,
VALID_GAMELIST_THUMBNAIL_TYPES,
VALID_SCAN_PRIORITY_SOURCES,
ConvertoConfig,
ExclusionType,
MetadataMediaType,
)
from config.config_manager import config_manager as cm
from decorators.auth import protected_route
from endpoints.responses.config import ConfigResponse
from exceptions.config_exceptions import ConfigNotWritableException
from handler.audit_handler import AuditTarget, record
from handler.auth.constants import Scope
from handler.database import db_rom_handler
from handler.filesystem import fs_platform_handler
from logger.logger import log
from models.audit_event import AuditAction, AuditTargetType
from utils.router import APIRouter
router = APIRouter(
prefix="/config",
tags=["config"],
)
class PlatformBindingPayload(BaseModel):
fs_slug: str
slug: str
class ExclusionPayload(BaseModel):
exclusion_value: str
# Left a string rather than the enum to keep the generated frontend type one.
exclusion_type: str
@field_validator("exclusion_type")
@classmethod
def validate_exclusion_type(cls, value: str) -> str:
if value not in ExclusionType:
raise ValueError(
f"Unknown exclusion type, expected one of {[t.value for t in ExclusionType]}"
)
return value
class ScanSettingsPayload(BaseModel):
"""Full replacement of the scan.* config section.
The three artwork override lists (cover/screenshot/manual) are optional:
a null value clears the override so that field falls back to
`artwork_priority`.
"""
metadata_priority: list[str]
artwork_priority: list[str]
cover_priority: list[str] | None = None
screenshot_priority: list[str] | None = None
manual_priority: list[str] | None = None
region_priority: list[str]
language_priority: list[str]
media: list[MetadataMediaType]
gamelist_export: bool
gamelist_thumbnail: MetadataMediaType
gamelist_image: MetadataMediaType
pegasus_export: bool
@field_validator(
"metadata_priority",
"artwork_priority",
"cover_priority",
"screenshot_priority",
"manual_priority",
)
@classmethod
def validate_sources(cls, value: list[str] | None) -> list[str] | None:
if value is None:
return value
invalid = [s for s in value if s not in VALID_SCAN_PRIORITY_SOURCES]
if invalid:
raise ValueError(f"Unknown metadata source(s): {sorted(set(invalid))}")
# Drop duplicates while preserving priority order.
return list(dict.fromkeys(value))
@field_validator("region_priority", "language_priority")
@classmethod
def validate_codes(cls, value: list[str]) -> list[str]:
# Region/language codes are open sets (provider-defined), so we only
# normalize to lowercase, trim blanks, and drop duplicates.
cleaned = [code.strip().lower() for code in value if code and code.strip()]
return list(dict.fromkeys(cleaned))
@field_validator("gamelist_thumbnail")
@classmethod
def validate_thumbnail(cls, value: MetadataMediaType) -> MetadataMediaType:
if value not in VALID_GAMELIST_THUMBNAIL_TYPES:
raise ValueError(
f"Invalid gamelist thumbnail; valid options: "
f"{sorted(o.value for o in VALID_GAMELIST_THUMBNAIL_TYPES)}"
)
return value
@field_validator("gamelist_image")
@classmethod
def validate_image(cls, value: MetadataMediaType) -> MetadataMediaType:
if value not in VALID_GAMELIST_IMAGE_TYPES:
raise ValueError(
f"Invalid gamelist image; valid options: "
f"{sorted(o.value for o in VALID_GAMELIST_IMAGE_TYPES)}"
)
return value
class ConvertoSettingsPayload(BaseModel):
"""Runtime-editable converto.* settings; `cache_ttl_hours` and `scan_metadata` stay in config.yml."""
download_conversion_enabled: bool
cache_max_size_gb: int = Field(ge=CONVERTO_INT_MINIMUMS["cache_max_size_gb"])
platform_formats: dict[str, str]
@field_validator("platform_formats")
@classmethod
def validate_platform_formats(cls, value: dict[str, str]) -> dict[str, str]:
return normalize_platform_formats(value)
@router.get("")
def get_config(request: Request) -> ConfigResponse:
"""Get config endpoint
Returns:
ConfigResponse: RomM's configuration
"""
cfg = cm.get_config()
return ConfigResponse(
CONFIG_FILE_MOUNTED=cfg.CONFIG_FILE_MOUNTED,
CONFIG_FILE_WRITABLE=cfg.CONFIG_FILE_WRITABLE,
# Raw parser error may leak the config file path, so only send when authenticated
CONFIG_FILE_PARSE_ERROR=(
cfg.CONFIG_FILE_PARSE_ERROR if request.user.is_authenticated else None
),
EXCLUDED_PLATFORMS=cfg.EXCLUDED_PLATFORMS,
EXCLUDED_SINGLE_EXT=cfg.EXCLUDED_SINGLE_EXT,
EXCLUDED_SINGLE_FILES=cfg.EXCLUDED_SINGLE_FILES,
EXCLUDED_MULTI_FILES=cfg.EXCLUDED_MULTI_FILES,
EXCLUDED_MULTI_PARTS_EXT=cfg.EXCLUDED_MULTI_PARTS_EXT,
EXCLUDED_MULTI_PARTS_FILES=cfg.EXCLUDED_MULTI_PARTS_FILES,
DEFAULT_EXCLUDED_PLATFORM_DIRS=list(DEFAULT_EXCLUDED_PLATFORM_DIRS),
DEFAULT_EXCLUDED_MULTI_FILE_DIRS=list(DEFAULT_EXCLUDED_MULTI_FILE_DIRS),
DEFAULT_EXCLUDED_FILES=list(DEFAULT_EXCLUDED_FILES),
DEFAULT_EXCLUDED_EXTENSIONS=list(DEFAULT_EXCLUDED_EXTENSIONS),
PLATFORMS_BINDING=cfg.PLATFORMS_BINDING,
PLATFORMS_VERSIONS=cfg.PLATFORMS_VERSIONS,
SKIP_HASH_CALCULATION=cfg.SKIP_HASH_CALCULATION,
EJS_DEBUG=cfg.EJS_DEBUG,
EJS_CACHE_LIMIT=cfg.EJS_CACHE_LIMIT,
EJS_DISABLE_AUTO_UNLOAD=cfg.EJS_DISABLE_AUTO_UNLOAD,
EJS_DISABLE_BATCH_BOOTUP=cfg.EJS_DISABLE_BATCH_BOOTUP,
EJS_ENABLE_AUTO_SAVE_SYNC=cfg.EJS_ENABLE_AUTO_SAVE_SYNC,
EJS_NETPLAY_ENABLED=cfg.EJS_NETPLAY_ENABLED,
# Contains credentials, so only send when authenticated
EJS_NETPLAY_ICE_SERVERS=(
cfg.EJS_NETPLAY_ICE_SERVERS if request.user.is_authenticated else []
),
EJS_CONTROLS=cfg.EJS_CONTROLS,
EJS_DEFAULT_CORES=cfg.EJS_DEFAULT_CORES,
EJS_SETTINGS=cfg.EJS_SETTINGS,
SCAN_METADATA_PRIORITY=cfg.SCAN_METADATA_PRIORITY,
SCAN_ARTWORK_PRIORITY=cfg.SCAN_ARTWORK_PRIORITY,
SCAN_ARTWORK_PRIORITY_OVERRIDES=cfg.SCAN_ARTWORK_PRIORITY_OVERRIDES,
SCAN_REGION_PRIORITY=cfg.SCAN_REGION_PRIORITY,
SCAN_LANGUAGE_PRIORITY=cfg.SCAN_LANGUAGE_PRIORITY,
SCAN_MEDIA=cfg.SCAN_MEDIA,
GAMELIST_AUTO_EXPORT_ON_SCAN=cfg.GAMELIST_AUTO_EXPORT_ON_SCAN,
GAMELIST_MEDIA_THUMBNAIL=cfg.GAMELIST_MEDIA_THUMBNAIL,
GAMELIST_MEDIA_IMAGE=cfg.GAMELIST_MEDIA_IMAGE,
PEGASUS_AUTO_EXPORT_ON_SCAN=cfg.PEGASUS_AUTO_EXPORT_ON_SCAN,
CONVERTO=cfg.CONVERTO,
CONVERTO_LIBRARY_TARGETS={
slug: sorted(targets)
for slug, targets in LIBRARY_TARGETS_BY_PLATFORM.items()
},
)
async def _reject_ambiguous_folder(fs_slug: str) -> None:
"""Refuse a mapping that several folders on disk would share."""
ambiguous = await fs_platform_handler.find_ambiguous_folders(fs_slug)
if ambiguous:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=(
f"Folders {', '.join(ambiguous)} differ only by case and share a "
"single mapping. Rename one to map them to different platforms."
),
)
def _record_config(request: Request, setting: str, op: str, **values: str) -> None:
record(
AuditAction.CONFIG_UPDATE,
request,
AuditTarget(AuditTargetType.CONFIG, setting, None),
{"setting": setting, "op": op, **values},
)
@protected_route(router.post, "/system/platforms", [Scope.PLATFORMS_WRITE])
async def add_platform_binding(
request: Request, payload: PlatformBindingPayload
) -> None:
"""Add platform binding to the configuration"""
fs_slug = payload.fs_slug
slug = payload.slug
await _reject_ambiguous_folder(fs_slug)
try:
cm.add_platform_binding(fs_slug, slug)
except ConfigNotWritableException as exc:
log.critical(exc.message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
) from exc
_record_config(request, "platform_binding", "add", fs_slug=fs_slug, slug=slug)
@protected_route(router.delete, "/system/platforms/{fs_slug}", [Scope.PLATFORMS_WRITE])
async def delete_platform_binding(request: Request, fs_slug: str) -> None:
"""Delete platform binding from the configuration"""
try:
cm.remove_platform_binding(fs_slug)
except ConfigNotWritableException as exc:
log.critical(exc.message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
) from exc
_record_config(request, "platform_binding", "remove", fs_slug=fs_slug)
@protected_route(router.post, "/system/versions", [Scope.PLATFORMS_WRITE])
async def add_platform_version(
request: Request, payload: PlatformBindingPayload
) -> None:
"""Add platform version to the configuration"""
fs_slug = payload.fs_slug
slug = payload.slug
await _reject_ambiguous_folder(fs_slug)
try:
cm.add_platform_version(fs_slug, slug)
except ConfigNotWritableException as exc:
log.critical(exc.message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
) from exc
_record_config(request, "platform_version", "add", fs_slug=fs_slug, slug=slug)
@protected_route(router.delete, "/system/versions/{fs_slug}", [Scope.PLATFORMS_WRITE])
async def delete_platform_version(request: Request, fs_slug: str) -> None:
"""Delete platform version from the configuration"""
try:
cm.remove_platform_version(fs_slug)
except ConfigNotWritableException as exc:
log.critical(exc.message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
) from exc
_record_config(request, "platform_version", "remove", fs_slug=fs_slug)
@protected_route(router.post, "/exclude", [Scope.PLATFORMS_WRITE])
async def add_exclusion(request: Request, payload: ExclusionPayload) -> None:
"""Add platform exclusion to the configuration"""
exclusion_value = payload.exclusion_value
exclusion_type = ExclusionType(payload.exclusion_type)
try:
cm.add_exclusion(exclusion_type, exclusion_value)
except ConfigNotWritableException as exc:
log.critical(exc.message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
) from exc
_record_config(
request, "exclusion", "add", type=exclusion_type, value=exclusion_value
)
@protected_route(
router.delete,
"/exclude/{exclusion_type}/{exclusion_value}",
[Scope.PLATFORMS_WRITE],
)
async def delete_exclusion(
request: Request, exclusion_type: ExclusionType, exclusion_value: str
) -> None:
"""Delete platform binding from the configuration"""
try:
cm.remove_exclusion(exclusion_type, exclusion_value)
except ConfigNotWritableException as exc:
log.critical(exc.message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
) from exc
_record_config(
request, "exclusion", "remove", type=exclusion_type, value=exclusion_value
)
@protected_route(router.put, "/scan", [Scope.PLATFORMS_WRITE])
async def update_scan_settings(request: Request, payload: ScanSettingsPayload) -> None:
"""Replace the scan.* section of the configuration"""
region_priority_changed = (
cm.get_config().SCAN_REGION_PRIORITY != payload.region_priority
)
try:
cm.update_scan_settings(
metadata_priority=payload.metadata_priority,
artwork_priority=payload.artwork_priority,
artwork_overrides={
"cover": payload.cover_priority,
"screenshot": payload.screenshot_priority,
"manual": payload.manual_priority,
},
region_priority=payload.region_priority,
language_priority=payload.language_priority,
media=[str(m) for m in payload.media],
gamelist_export=payload.gamelist_export,
gamelist_thumbnail=str(payload.gamelist_thumbnail),
gamelist_image=str(payload.gamelist_image),
pegasus_export=payload.pegasus_export,
)
except ConfigNotWritableException as exc:
log.critical(exc.message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
) from exc
_record_config(request, "scan_settings", "update")
# Region priority picks the primary rom of each sibling group, so every
# cached gallery sidecar is stale the moment the order changes.
if region_priority_changed:
db_rom_handler.invalidate_filter_values_cache()
@protected_route(router.put, "/converto_settings", [Scope.PLATFORMS_WRITE])
async def update_converto_settings(
request: Request, payload: ConvertoSettingsPayload
) -> None:
"""Update the runtime-editable converto.* settings"""
current = cm.get_config().CONVERTO
try:
cm.update_converto_settings(
ConvertoConfig(
**payload.model_dump(),
cache_ttl_hours=current.cache_ttl_hours,
scan_metadata=current.scan_metadata,
)
)
except ConfigNotWritableException as exc:
log.critical(exc.message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=exc.message
) from exc
_record_config(request, "converto_settings", "update")