mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 10:33:22 +01:00
feat(converto): convert the library in place with a manual task
`converto.platform_formats` now names the format a platform's library is stored in, and the new "Convert library" task brings every matched rom to it. Each output is staged in a `.romm_tmp_` directory beside the original, moved into place, and only then are the originals (and a cue's tracks) deleted. Single-file roms take the new name, folder roms keep theirs and get their .m3u entries rewritten, and the file rows refresh, so a rom keeps its id, saves and collections. Only lossless conversions qualify, so xbox (xiso trims the dump) has no library format. Unmatched roms are skipped because a converted file no longer hash-matches a DAT. `/api/config` now carries the library targets and, per input extension, the formats a download can be converted to. Co-Authored-By: DevYukine <20647088+DevYukine@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017BuuZVVtVPNLRaCjTN9bgQ
This commit is contained in:
@@ -36,6 +36,10 @@ class RomConvertoOperationError(RomConvertoError):
|
||||
"""A conversion command exited nonzero."""
|
||||
|
||||
|
||||
# `xbox convert` keeps only a dump's game partition, so a library never stores its output.
|
||||
_LOSSY_ARGV: Final[frozenset[tuple[str, ...]]] = frozenset({("xbox", "convert")})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Operation:
|
||||
"""A subcommand bringing `input_exts` files to `target`; source and output are appended to `argv`."""
|
||||
@@ -46,6 +50,10 @@ class Operation:
|
||||
input_exts: frozenset[str]
|
||||
output_ext: str
|
||||
|
||||
@property
|
||||
def lossless(self) -> bool:
|
||||
return self.argv not in _LOSSY_ARGV
|
||||
|
||||
def output_name(self, src: Path, input_ext: str) -> str:
|
||||
"""`src` renamed from the matched lowercase `input_ext` to the output extension."""
|
||||
return f"{src.name[: len(src.name) - len(input_ext)]}{self.output_ext}"
|
||||
@@ -116,13 +124,31 @@ UNCOMPRESSED_TARGETS: Final[frozenset[str]] = frozenset(
|
||||
{"cci", "cia", "iso", "nsp", "wbfs", "xci", "xiso"}
|
||||
)
|
||||
|
||||
# Platform slug -> the targets it can be configured with.
|
||||
TARGETS_BY_PLATFORM: Final[dict[str, frozenset[str]]] = {
|
||||
slug: frozenset(op.target for op in OPERATIONS if slug in op.platforms)
|
||||
for slug in sorted({slug for op in OPERATIONS for slug in op.platforms})
|
||||
|
||||
# Platform slug -> the targets a library can be stored in.
|
||||
LIBRARY_TARGETS_BY_PLATFORM: Final[dict[str, frozenset[str]]] = {
|
||||
slug: frozenset(
|
||||
op.target for op in OPERATIONS if slug in op.platforms and op.lossless
|
||||
)
|
||||
for slug in sorted(
|
||||
{slug for op in OPERATIONS if op.lossless for slug in op.platforms}
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def download_formats() -> dict[str, dict[str, list[str]]]:
|
||||
"""Platform slug -> input extension -> the targets a download of it can be converted to."""
|
||||
table: dict[str, dict[str, set[str]]] = {}
|
||||
for op in OPERATIONS:
|
||||
for slug in op.platforms:
|
||||
for ext in op.input_exts:
|
||||
table.setdefault(slug, {}).setdefault(ext, set()).add(op.target)
|
||||
return {
|
||||
slug: {ext: sorted(targets) for ext, targets in sorted(exts.items())}
|
||||
for slug, exts in sorted(table.items())
|
||||
}
|
||||
|
||||
|
||||
# Extensions whose format goes by another name than the extension itself.
|
||||
_FORMAT_ALIASES: Final[dict[str, str]] = {
|
||||
".3ds": "cci",
|
||||
@@ -147,21 +173,21 @@ def file_format(file_name: str) -> str:
|
||||
|
||||
|
||||
def normalize_platform_formats(raw: dict[str, str]) -> dict[str, str]:
|
||||
"""`raw` with slugs and targets trimmed and lowercased.
|
||||
"""`raw` with slugs and library targets trimmed and lowercased.
|
||||
|
||||
Raises:
|
||||
ValueError: A platform has no conversions, or a target isn't one of them.
|
||||
ValueError: A platform has no library targets, or a target isn't one of them.
|
||||
"""
|
||||
cleaned = {
|
||||
str(slug).strip().lower(): str(target).strip().lower()
|
||||
for slug, target in raw.items()
|
||||
}
|
||||
for slug, target in cleaned.items():
|
||||
targets = TARGETS_BY_PLATFORM.get(slug)
|
||||
targets = LIBRARY_TARGETS_BY_PLATFORM.get(slug)
|
||||
if targets is None:
|
||||
raise ValueError(
|
||||
f"rom-converto has no conversions for {slug!r}. "
|
||||
f"Supported: {sorted(TARGETS_BY_PLATFORM)}."
|
||||
f"rom-converto has no library formats for {slug!r}. "
|
||||
f"Supported: {sorted(LIBRARY_TARGETS_BY_PLATFORM)}."
|
||||
)
|
||||
if target not in targets:
|
||||
raise ValueError(
|
||||
@@ -172,7 +198,7 @@ def normalize_platform_formats(raw: dict[str, str]) -> dict[str, str]:
|
||||
|
||||
|
||||
def resolve_operation(
|
||||
platform_slug: str, target: str, file_name: str
|
||||
platform_slug: str, target: str, file_name: str, *, lossless: bool = False
|
||||
) -> tuple[Operation, str] | None:
|
||||
"""The operation and matched extension bringing `file_name` to `target`, or None if none applies."""
|
||||
name = file_name.lower()
|
||||
@@ -180,6 +206,8 @@ def resolve_operation(
|
||||
for op in OPERATIONS:
|
||||
if op.target != target or platform_slug not in op.platforms:
|
||||
continue
|
||||
if lossless and not op.lossless:
|
||||
continue
|
||||
for ext in op.input_exts:
|
||||
# Prefer the longer extension so `.nkit.iso` is not read as `.iso`.
|
||||
if name.endswith(ext) and (best is None or len(ext) > len(best[1])):
|
||||
|
||||
@@ -2,7 +2,8 @@ from fastapi import HTTPException, Request, status
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from adapters.services.rom_converto import (
|
||||
TARGETS_BY_PLATFORM,
|
||||
LIBRARY_TARGETS_BY_PLATFORM,
|
||||
download_formats,
|
||||
normalize_platform_formats,
|
||||
)
|
||||
from config.config_manager import (
|
||||
@@ -189,9 +190,11 @@ def get_config(request: Request) -> ConfigResponse:
|
||||
GAMELIST_MEDIA_IMAGE=cfg.GAMELIST_MEDIA_IMAGE,
|
||||
PEGASUS_AUTO_EXPORT_ON_SCAN=cfg.PEGASUS_AUTO_EXPORT_ON_SCAN,
|
||||
CONVERTO=cfg.CONVERTO,
|
||||
CONVERTO_TARGETS={
|
||||
slug: sorted(targets) for slug, targets in TARGETS_BY_PLATFORM.items()
|
||||
CONVERTO_LIBRARY_TARGETS={
|
||||
slug: sorted(targets)
|
||||
for slug, targets in LIBRARY_TARGETS_BY_PLATFORM.items()
|
||||
},
|
||||
CONVERTO_DOWNLOAD_FORMATS=download_formats(),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -46,5 +46,7 @@ class ConfigResponse(TypedDict):
|
||||
GAMELIST_MEDIA_IMAGE: MetadataMediaType
|
||||
PEGASUS_AUTO_EXPORT_ON_SCAN: bool
|
||||
CONVERTO: ConvertoConfig
|
||||
# Platform slug -> the targets rom-converto can convert it to.
|
||||
CONVERTO_TARGETS: dict[str, list[str]]
|
||||
# Platform slug -> the formats its library can be stored in.
|
||||
CONVERTO_LIBRARY_TARGETS: dict[str, list[str]]
|
||||
# Platform slug -> input extension -> the formats a download can be converted to.
|
||||
CONVERTO_DOWNLOAD_FORMATS: dict[str, dict[str, list[str]]]
|
||||
|
||||
@@ -7,7 +7,8 @@ from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.rom import Rom
|
||||
|
||||
_STAGE_PREFIX = ".romm_tmp_"
|
||||
# Scans and the watcher skip dot-prefixed entries, so staged files stay unseen.
|
||||
STAGE_PREFIX = ".romm_tmp_"
|
||||
|
||||
# Parallel uploads each promote the ROM, maybe on different gunicorn workers.
|
||||
# Keyed by the target folder, since lone files sharing a stem promote into one.
|
||||
@@ -39,7 +40,7 @@ async def _promote(rom: Rom) -> Rom:
|
||||
origin = f"{fs_path}/{fs_name}"
|
||||
dest_dir = f"{fs_path}/{folder}"
|
||||
final = f"{dest_dir}/{fs_name}"
|
||||
staged = f"{fs_path}/{_STAGE_PREFIX}{fs_name}"
|
||||
staged = f"{fs_path}/{STAGE_PREFIX}{fs_name}"
|
||||
extensionless = folder == fs_name
|
||||
|
||||
# Extensionless dest_dir is the file's own path; only a directory collides.
|
||||
|
||||
254
backend/tasks/manual/convert_library.py
Normal file
254
backend/tasks/manual/convert_library.py
Normal file
@@ -0,0 +1,254 @@
|
||||
"""Convert each matched ROM to its platform's library format, in place."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
from adapters.services.rom_converto import (
|
||||
Operation,
|
||||
RomConvertoError,
|
||||
RomConvertoOperationError,
|
||||
file_format,
|
||||
resolve_operation,
|
||||
rom_converto_service,
|
||||
)
|
||||
from config import SCAN_TIMEOUT
|
||||
from config.config_manager import config_manager as cm
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.filesystem import fs_rom_handler
|
||||
from handler.rom_conversion import STAGE_PREFIX
|
||||
from handler.rom_files import refresh_rom_files
|
||||
from logger.formatter import highlight as hl
|
||||
from logger.logger import log
|
||||
from models.rom import Rom, RomFile, RomFileCategory
|
||||
from tasks.scheduled.convert_images_to_webp import ConversionStats
|
||||
from tasks.tasks import Task, TaskType
|
||||
from utils.context import initialize_context
|
||||
|
||||
_CUE_FILE_LINE: Final = re.compile(r'^\s*FILE\s+(?:"([^"]+)"|(\S+))', re.IGNORECASE)
|
||||
_PLAYLIST_EXT: Final = ".m3u"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConvertLibraryStats:
|
||||
converted: int = 0
|
||||
already_converted: int = 0
|
||||
# Converted files no longer hash-match a DAT, so only matched roms convert.
|
||||
unmatched: int = 0
|
||||
unsupported: int = 0
|
||||
failed: int = 0
|
||||
bytes_saved: int = 0
|
||||
|
||||
|
||||
def _cue_tracks(cue: Path) -> list[Path]:
|
||||
"""The track files a cue sheet references, all beside it."""
|
||||
tracks: list[Path] = []
|
||||
for line in cue.read_text(errors="replace").splitlines():
|
||||
match = _CUE_FILE_LINE.match(line)
|
||||
if match is None:
|
||||
continue
|
||||
name = match.group(1) or match.group(2)
|
||||
# A track outside the cue's folder isn't this rom's to delete.
|
||||
if Path(name).name != name:
|
||||
raise ValueError(f"{cue.name} references a track outside its folder")
|
||||
tracks.append(cue.with_name(name))
|
||||
return tracks
|
||||
|
||||
|
||||
def _rewrite_playlists(folder: Path, renames: dict[str, str]) -> None:
|
||||
"""Point each playlist entry for a converted file at its new name."""
|
||||
for playlist in folder.iterdir():
|
||||
if playlist.suffix.lower() != _PLAYLIST_EXT or not playlist.is_file():
|
||||
continue
|
||||
lines = playlist.read_text(errors="replace").splitlines()
|
||||
rewritten = [renames.get(line.strip(), line) for line in lines]
|
||||
if rewritten != lines:
|
||||
playlist.write_text("\n".join(rewritten) + "\n")
|
||||
|
||||
|
||||
def _sources(src: Path, final: Path, input_ext: str) -> list[Path]:
|
||||
"""The files a conversion of `src` replaces, refusing one that would overwrite."""
|
||||
if final.exists():
|
||||
raise FileExistsError(f"{final.name} already exists")
|
||||
return [src, *(_cue_tracks(src) if input_ext == ".cue" else [])]
|
||||
|
||||
|
||||
def _publish(stage_dir: Path, final: Path) -> None:
|
||||
if [p.name for p in stage_dir.iterdir()] != [final.name]:
|
||||
raise RomConvertoOperationError(
|
||||
f"rom-converto did not write exactly {final.name}"
|
||||
)
|
||||
os.replace(stage_dir / final.name, final)
|
||||
|
||||
|
||||
def _replace_sources(sources: list[Path], final: Path) -> int:
|
||||
"""Delete the converted files and return the bytes the conversion saved."""
|
||||
saved = sum(p.stat().st_size for p in sources if p.exists()) - final.stat().st_size
|
||||
for path in sources:
|
||||
try:
|
||||
path.unlink(missing_ok=True)
|
||||
except OSError as exc:
|
||||
log.warning(
|
||||
f"Converted to {hl(final.name)} but could not delete {path}: {exc}"
|
||||
)
|
||||
return saved
|
||||
|
||||
|
||||
async def _convert_in_place(
|
||||
src: Path, operation: Operation, input_ext: str
|
||||
) -> tuple[Path, int]:
|
||||
"""Convert `src` beside itself, then delete it and any tracks it references.
|
||||
|
||||
Raises only while the original is untouched.
|
||||
|
||||
Returns:
|
||||
The converted file and the bytes the conversion saved.
|
||||
"""
|
||||
final = src.with_name(operation.output_name(src, input_ext))
|
||||
sources = await asyncio.to_thread(_sources, src, final, input_ext)
|
||||
stage_dir = Path(
|
||||
await asyncio.to_thread(tempfile.mkdtemp, prefix=STAGE_PREFIX, dir=src.parent)
|
||||
)
|
||||
try:
|
||||
await rom_converto_service.convert(
|
||||
operation, src=src, out=stage_dir / final.name
|
||||
)
|
||||
await asyncio.to_thread(_publish, stage_dir, final)
|
||||
finally:
|
||||
await asyncio.to_thread(shutil.rmtree, stage_dir, True)
|
||||
return final, await asyncio.to_thread(_replace_sources, sources, final)
|
||||
|
||||
|
||||
def _game_files(rom: Rom) -> list[RomFile]:
|
||||
return [
|
||||
f
|
||||
for f in rom.files
|
||||
if f.is_top_level
|
||||
and not f.missing_from_fs
|
||||
and f.category in (None, RomFileCategory.GAME)
|
||||
]
|
||||
|
||||
|
||||
class ConvertLibraryTask(Task):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(
|
||||
title="Convert library",
|
||||
description=(
|
||||
"Convert each matched ROM to its platform's library format, "
|
||||
"replacing the original files"
|
||||
),
|
||||
task_type=TaskType.CONVERSION,
|
||||
enabled=True,
|
||||
manual_run=True,
|
||||
cron_string=None,
|
||||
# One conversion after another, each up to ROM_CONVERTO_TIMEOUT.
|
||||
timeout=SCAN_TIMEOUT,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _name_taken(rom: Rom, operation: Operation, input_ext: str) -> bool:
|
||||
"""Whether another rom row already holds the name this rom converts to."""
|
||||
name = operation.output_name(Path(rom.fs_name), input_ext)
|
||||
taken = f"{rom.fs_path}/{name}" in db_rom_handler.get_roms_by_fs_name(
|
||||
rom.platform_id, [name]
|
||||
)
|
||||
if taken:
|
||||
log.warning(f"Not converting {hl(rom.fs_name)}: a rom named {name} exists")
|
||||
return taken
|
||||
|
||||
async def _convert_rom(
|
||||
self, rom: Rom, target: str, stats: ConvertLibraryStats
|
||||
) -> None:
|
||||
planned: list[tuple[RomFile, Operation, str]] = []
|
||||
for rom_file in _game_files(rom):
|
||||
if file_format(rom_file.file_name) == target:
|
||||
stats.already_converted += 1
|
||||
continue
|
||||
resolved = resolve_operation(
|
||||
rom.platform_slug, target, rom_file.file_name, lossless=True
|
||||
)
|
||||
if resolved is None:
|
||||
stats.unsupported += 1
|
||||
continue
|
||||
if rom.has_simple_single_file and self._name_taken(rom, *resolved):
|
||||
stats.failed += 1
|
||||
continue
|
||||
planned.append((rom_file, *resolved))
|
||||
if not planned:
|
||||
return
|
||||
if not rom.is_identified:
|
||||
stats.unmatched += 1
|
||||
return
|
||||
|
||||
renames: dict[str, str] = {}
|
||||
for rom_file, operation, input_ext in planned:
|
||||
src = fs_rom_handler.validate_path(rom_file.full_path)
|
||||
try:
|
||||
final, saved = await _convert_in_place(src, operation, input_ext)
|
||||
except (RomConvertoError, OSError, ValueError) as exc:
|
||||
log.warning(f"Could not convert {hl(rom_file.file_name)}: {exc}")
|
||||
stats.failed += 1
|
||||
continue
|
||||
renames[src.name] = final.name
|
||||
stats.converted += 1
|
||||
stats.bytes_saved += saved
|
||||
log.info(f"Converted {hl(src.name)} to {hl(final.name)}")
|
||||
|
||||
if not renames:
|
||||
return
|
||||
if rom.has_simple_single_file:
|
||||
db_rom_handler.update_rom(rom.id, {"fs_name": renames[rom.fs_name]})
|
||||
else:
|
||||
await asyncio.to_thread(
|
||||
_rewrite_playlists,
|
||||
fs_rom_handler.validate_path(rom.full_path),
|
||||
renames,
|
||||
)
|
||||
refreshed = db_rom_handler.get_rom(rom.id)
|
||||
if refreshed is not None:
|
||||
await refresh_rom_files(refreshed)
|
||||
|
||||
@initialize_context()
|
||||
async def run(self, platform_id: int | None = None) -> dict[str, int]:
|
||||
"""Convert every matched ROM on platforms that have a library format."""
|
||||
log.info(f"Starting {self.title} task...")
|
||||
stats = ConvertLibraryStats()
|
||||
if not await rom_converto_service.is_enabled():
|
||||
log.warning(f"{self.title} needs rom-converto; set ROM_CONVERTO_ENABLED")
|
||||
return asdict(stats)
|
||||
|
||||
formats = cm.get_config().CONVERTO.platform_formats
|
||||
rom_ids: list[tuple[int, str]] = []
|
||||
for platform in db_platform_handler.get_platforms():
|
||||
if platform_id is not None and platform.id != platform_id:
|
||||
continue
|
||||
target = formats.get(platform.slug)
|
||||
if target:
|
||||
rom_ids.extend(
|
||||
(rom.id, target)
|
||||
for rom in db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform.id]
|
||||
)
|
||||
)
|
||||
|
||||
progress = ConversionStats()
|
||||
progress.update(total=len(rom_ids))
|
||||
for index, (rom_id, target) in enumerate(rom_ids):
|
||||
rom = db_rom_handler.get_rom(rom_id)
|
||||
if rom is not None:
|
||||
await self._convert_rom(rom, target, stats)
|
||||
progress.update(processed=index + 1, errors=stats.failed)
|
||||
|
||||
log.info(
|
||||
f"{self.title} completed: {stats.converted} converted, "
|
||||
f"{stats.failed} failed, {stats.bytes_saved} bytes saved"
|
||||
)
|
||||
return asdict(stats)
|
||||
|
||||
|
||||
convert_library_task = ConvertLibraryTask()
|
||||
@@ -9,6 +9,7 @@ from exceptions.task_exceptions import TaskNotFoundException
|
||||
from handler.redis_handler import low_prio_queue, scan_queue
|
||||
from tasks.manual.cleanup_missing_firmware import cleanup_missing_firmware_task
|
||||
from tasks.manual.cleanup_missing_roms import cleanup_missing_roms_task
|
||||
from tasks.manual.convert_library import convert_library_task
|
||||
from tasks.manual.recompute_save_content_hashes import (
|
||||
recompute_save_content_hashes_task,
|
||||
)
|
||||
@@ -59,6 +60,7 @@ MANUAL_TASKS: Final[dict[str, Task]] = {
|
||||
"cleanup_missing_firmware": cleanup_missing_firmware_task,
|
||||
"sync_folder_scan": sync_folder_scan_task,
|
||||
"recompute_save_content_hashes": recompute_save_content_hashes_task,
|
||||
"convert_library": convert_library_task,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -6,12 +6,13 @@ import pytest
|
||||
|
||||
from adapters.services import rom_converto
|
||||
from adapters.services.rom_converto import (
|
||||
TARGETS_BY_PLATFORM,
|
||||
LIBRARY_TARGETS_BY_PLATFORM,
|
||||
Operation,
|
||||
RomConvertoBinaryNotFoundError,
|
||||
RomConvertoOperationError,
|
||||
RomConvertoService,
|
||||
RomConvertoTimeoutError,
|
||||
download_formats,
|
||||
file_format,
|
||||
resolve_operation,
|
||||
)
|
||||
@@ -306,14 +307,32 @@ class TestResolveOperation:
|
||||
assert op.output_name(Path("Game.cue"), ext) == "Game.iso"
|
||||
|
||||
|
||||
class TestTargetsByPlatform:
|
||||
class TestLibraryTargetsByPlatform:
|
||||
def test_psp_targets(self):
|
||||
assert TARGETS_BY_PLATFORM["psp"] == {"chd", "cso", "iso", "zso"}
|
||||
assert LIBRARY_TARGETS_BY_PLATFORM["psp"] == {"chd", "cso", "iso", "zso"}
|
||||
|
||||
def test_platforms_without_format_conversions(self):
|
||||
for slug in ("wiiu", "psvita", "nds", "ps3"):
|
||||
assert slug not in TARGETS_BY_PLATFORM
|
||||
assert slug not in LIBRARY_TARGETS_BY_PLATFORM
|
||||
|
||||
def test_a_lossy_conversion_is_no_library_target(self):
|
||||
assert "xbox" not in LIBRARY_TARGETS_BY_PLATFORM
|
||||
assert resolve_operation("xbox", "xiso", "game.iso") is not None
|
||||
assert resolve_operation("xbox", "xiso", "game.iso", lossless=True) is None
|
||||
|
||||
|
||||
class TestDownloadFormats:
|
||||
def test_maps_each_input_extension_to_its_targets(self):
|
||||
formats = download_formats()
|
||||
|
||||
assert formats["psp"][".chd"] == ["cso", "iso", "zso"]
|
||||
assert formats["xbox"][".iso"] == ["xiso"]
|
||||
|
||||
def test_no_decrypt_or_encrypt_targets(self):
|
||||
targets = set().union(*TARGETS_BY_PLATFORM.values())
|
||||
targets = {
|
||||
target
|
||||
for exts in download_formats().values()
|
||||
for ext_targets in exts.values()
|
||||
for target in ext_targets
|
||||
}
|
||||
assert not targets & {"decrypted", "encrypted"}
|
||||
|
||||
@@ -731,6 +731,7 @@ def test_update_converto_settings_round_trip(tmp_path):
|
||||
[
|
||||
" platform_formats:\n psvita: iso\n",
|
||||
" platform_formats:\n psp: rvz\n",
|
||||
" platform_formats:\n xbox: xiso\n",
|
||||
" cache_ttl_hours: 0\n",
|
||||
" cache_max_size_gb: -1\n",
|
||||
" cache_max_size_gb: true\n",
|
||||
|
||||
@@ -311,6 +311,7 @@ def test_update_converto_settings_requires_auth(client):
|
||||
[
|
||||
{"platform_formats": {"psp": "rvz"}},
|
||||
{"platform_formats": {"psvita": "iso"}},
|
||||
{"platform_formats": {"xbox": "xiso"}},
|
||||
{"cache_max_size_gb": -1},
|
||||
],
|
||||
)
|
||||
|
||||
277
backend/tests/tasks/test_convert_library.py
Normal file
277
backend/tests/tasks/test_convert_library.py
Normal file
@@ -0,0 +1,277 @@
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
from tests.factories import make_rom
|
||||
|
||||
from adapters.services.rom_converto import (
|
||||
RomConvertoOperationError,
|
||||
rom_converto_service,
|
||||
)
|
||||
from config.config_manager import ConvertoConfig
|
||||
from config.config_manager import config_manager as cm
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.filesystem import fs_rom_handler
|
||||
from models.platform import Platform
|
||||
from models.rom import Rom, RomFile, RomFileCategory
|
||||
from models.user import User
|
||||
from tasks.manual.convert_library import ConvertLibraryTask
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def library(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
lib = tmp_path / "library"
|
||||
lib.mkdir()
|
||||
monkeypatch.setattr(fs_rom_handler, "base_path", lib.resolve())
|
||||
return lib
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def converto(mocker) -> ConvertoConfig:
|
||||
config = ConvertoConfig(platform_formats={"psp": "chd", "psx": "chd"})
|
||||
# The file refresh after a conversion reads the rest of the same config.
|
||||
real = cm.get_config()
|
||||
mocker.patch.object(real, "CONVERTO", config)
|
||||
mocker.patch.object(cm, "get_config", return_value=real)
|
||||
return config
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def converted(mocker) -> list[tuple[str, Path]]:
|
||||
"""Fake rom-converto: each conversion writes a small output and is recorded."""
|
||||
calls: list[tuple[str, Path]] = []
|
||||
|
||||
def convert(operation, src: Path, out: Path) -> None:
|
||||
calls.append((src.name, out))
|
||||
out.write_bytes(b"c")
|
||||
|
||||
mocker.patch.object(
|
||||
rom_converto_service, "is_enabled", AsyncMock(return_value=True)
|
||||
)
|
||||
mocker.patch.object(rom_converto_service, "convert", AsyncMock(side_effect=convert))
|
||||
return calls
|
||||
|
||||
|
||||
def _platform(slug: str) -> Platform:
|
||||
return db_platform_handler.add_platform(
|
||||
Platform(name=slug, slug=slug, fs_slug=slug)
|
||||
)
|
||||
|
||||
|
||||
def _rom(
|
||||
library: Path,
|
||||
admin_user: User,
|
||||
platform: Platform,
|
||||
files: dict[str, bytes],
|
||||
*,
|
||||
folder: bool = False,
|
||||
matched: bool = True,
|
||||
) -> Rom:
|
||||
"""A rom with `files` on disk: a single file, or a folder holding them all."""
|
||||
name = "game"
|
||||
rom = make_rom(
|
||||
platform,
|
||||
name,
|
||||
fs_extension="" if folder else Path(next(iter(files))).suffix.lstrip("."),
|
||||
igdb_id=1 if matched else None,
|
||||
)
|
||||
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id)
|
||||
file_path = f"{rom.fs_path}/{rom.fs_name}" if folder else rom.fs_path
|
||||
for file_name, data in files.items():
|
||||
disk = library / file_path / file_name
|
||||
disk.parent.mkdir(parents=True, exist_ok=True)
|
||||
disk.write_bytes(data)
|
||||
db_rom_handler.add_rom_file(
|
||||
RomFile(
|
||||
rom_id=rom.id,
|
||||
file_name=file_name,
|
||||
file_path=file_path,
|
||||
file_size_bytes=len(data),
|
||||
last_modified=disk.stat().st_mtime,
|
||||
category=RomFileCategory.GAME,
|
||||
)
|
||||
)
|
||||
refreshed = db_rom_handler.get_rom(rom.id)
|
||||
assert refreshed is not None
|
||||
return refreshed
|
||||
|
||||
|
||||
def _reload(rom: Rom) -> Rom:
|
||||
refreshed = db_rom_handler.get_rom(rom.id)
|
||||
assert refreshed is not None
|
||||
return refreshed
|
||||
|
||||
|
||||
async def _run(platform: Platform | None = None) -> dict[str, int]:
|
||||
return await ConvertLibraryTask().run(platform.id if platform else None)
|
||||
|
||||
|
||||
async def test_a_single_file_rom_is_replaced_and_keeps_its_id(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
psp = _platform("psp")
|
||||
rom = _rom(library, admin_user, psp, {"game.iso": b"x" * 100})
|
||||
folder = library / rom.fs_path
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["converted"] == 1
|
||||
assert stats["bytes_saved"] == 99
|
||||
assert sorted(p.name for p in folder.iterdir()) == ["game.chd"]
|
||||
after = _reload(rom)
|
||||
assert after.fs_name == "game.chd"
|
||||
assert after.fs_extension == "chd"
|
||||
assert [f.file_name for f in after.files] == ["game.chd"]
|
||||
|
||||
|
||||
async def test_a_cue_folder_becomes_one_chd_and_its_playlist_follows(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
psx = _platform("psx")
|
||||
cue = 'FILE "game (Track 1).bin" BINARY\nFILE "game (Track 2).bin" BINARY\n'
|
||||
rom = _rom(
|
||||
library,
|
||||
admin_user,
|
||||
psx,
|
||||
{
|
||||
"game.cue": cue.encode(),
|
||||
"game (Track 1).bin": b"x" * 50,
|
||||
"game (Track 2).bin": b"x" * 50,
|
||||
"game.m3u": b"game.cue\n",
|
||||
},
|
||||
folder=True,
|
||||
)
|
||||
folder = library / rom.full_path
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["converted"] == 1
|
||||
assert sorted(p.name for p in folder.iterdir()) == ["game.chd", "game.m3u"]
|
||||
assert (folder / "game.m3u").read_text() == "game.chd\n"
|
||||
after = _reload(rom)
|
||||
assert after.fs_name == rom.fs_name
|
||||
assert sorted(f.file_name for f in after.files) == ["game.chd", "game.m3u"]
|
||||
|
||||
|
||||
async def test_a_file_already_in_the_library_format_is_left_alone(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
_rom(library, admin_user, _platform("psp"), {"game.chd": b"x"})
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["already_converted"] == 1
|
||||
assert converted == []
|
||||
|
||||
|
||||
async def test_an_unmatched_rom_is_not_converted(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
rom = _rom(library, admin_user, _platform("psp"), {"game.iso": b"x"}, matched=False)
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["unmatched"] == 1
|
||||
assert converted == []
|
||||
assert (library / rom.full_path).exists()
|
||||
|
||||
|
||||
async def test_a_platform_without_a_library_format_is_skipped(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
converto.platform_formats = {}
|
||||
_rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["converted"] == 0
|
||||
assert converted == []
|
||||
|
||||
|
||||
async def test_only_the_requested_platform_is_converted(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
psp = _platform("psp")
|
||||
_rom(library, admin_user, psp, {"game.iso": b"x" * 10})
|
||||
_rom(library, admin_user, _platform("psx"), {"game.cue": b""}, folder=True)
|
||||
|
||||
await _run(psp)
|
||||
|
||||
assert [src for src, _ in converted] == ["game.iso"]
|
||||
|
||||
|
||||
async def test_a_failed_conversion_leaves_the_original_and_no_staged_output(
|
||||
library: Path, admin_user: User, converto, converted, mocker
|
||||
):
|
||||
rom = _rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
mocker.patch.object(
|
||||
rom_converto_service,
|
||||
"convert",
|
||||
AsyncMock(side_effect=RomConvertoOperationError("boom")),
|
||||
)
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert sorted(p.name for p in (library / rom.fs_path).iterdir()) == ["game.iso"]
|
||||
assert _reload(rom).fs_name == "game.iso"
|
||||
|
||||
|
||||
async def test_an_existing_output_is_never_overwritten(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
rom = _rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
(library / rom.fs_path / "game.chd").write_bytes(b"theirs")
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert converted == []
|
||||
assert (library / rom.fs_path / "game.chd").read_bytes() == b"theirs"
|
||||
assert (library / rom.full_path).exists()
|
||||
|
||||
|
||||
async def test_a_rom_row_already_holding_the_output_name_is_left_alone(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
psp = _platform("psp")
|
||||
rom = _rom(library, admin_user, psp, {"game.iso": b"x"})
|
||||
make_rom(psp, "other", fs_stem="game", fs_extension="chd")
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert converted == []
|
||||
assert (library / rom.full_path).exists()
|
||||
|
||||
|
||||
async def test_a_cue_pointing_outside_its_folder_is_refused(
|
||||
library: Path, admin_user: User, converto, converted
|
||||
):
|
||||
rom = _rom(
|
||||
library,
|
||||
admin_user,
|
||||
_platform("psx"),
|
||||
{"game.cue": b'FILE "../other.bin" BINARY\n'},
|
||||
folder=True,
|
||||
)
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["failed"] == 1
|
||||
assert converted == []
|
||||
assert (library / rom.full_path / "game.cue").exists()
|
||||
|
||||
|
||||
async def test_nothing_runs_without_rom_converto(
|
||||
library: Path, admin_user: User, converto, converted, mocker
|
||||
):
|
||||
mocker.patch.object(
|
||||
rom_converto_service, "is_enabled", AsyncMock(return_value=False)
|
||||
)
|
||||
_rom(library, admin_user, _platform("psp"), {"game.iso": b"x"})
|
||||
|
||||
stats = await _run()
|
||||
|
||||
assert stats["converted"] == 0
|
||||
assert converted == []
|
||||
@@ -321,6 +321,7 @@ backend/
|
||||
│ │ └── reap_streaming_sessions.py # Stop abandoned streaming sessions
|
||||
│ └── manual/ # On-demand tasks
|
||||
│ ├── cleanup_missing_roms.py # Drop DB entries for missing files
|
||||
│ ├── convert_library.py # Store matched ROMs in each platform's library format
|
||||
│ ├── cleanup_orphaned_resources.py # Remove unreferenced artwork
|
||||
│ └── sync_folder_scan.py # Scan sync folder for new saves
|
||||
│
|
||||
@@ -908,8 +909,11 @@ A reset link is emailed when SMTP is set up, the user has an address and `ROMM_B
|
||||
| DELETE | `/{id}` | ROMS_WRITE | Delete ROM |
|
||||
| POST | `/delete` | ROMS_WRITE | Bulk delete |
|
||||
| POST | `/download/{id}/{file_name}` | ROMS_READ | Download ROM |
|
||||
| GET | `/{id}/content/{file_name}` | ROMS_READ | Download ROM, in a listed `?format=` when asked |
|
||||
| POST | `/unidentified` | ROMS_READ | Get unidentified ROMs |
|
||||
|
||||
With rom-converto enabled (`ROM_CONVERTO_ENABLED`, `converto.download_conversion_enabled`), `?format=zso,iso` lists the formats a client can read. A single-file download whose stored format is listed is served as-is. Otherwise the first listed format with a copy cached under `/romm/cache/converts` is served, then the first one rom-converto can produce: answered by the same request if it converts within a few seconds, else `202` with `Retry-After` while it finishes. `406` means no listed format can be served, and `HEAD` reports the same without starting a conversion. Only signed-in, non-kiosk users start conversions. `CONVERTO_DOWNLOAD_FORMATS` in `/api/config` lists the formats each input extension converts to.
|
||||
|
||||
#### ROM Upload (Chunked)
|
||||
|
||||
| Method | Path | Scope | Description |
|
||||
@@ -1675,29 +1679,33 @@ failure callback and a scan needs one to report a worker that died mid-scan.
|
||||
|
||||
Toggled via environment variables:
|
||||
|
||||
| Task | Env Toggle | Default Cron | Description |
|
||||
| --------------------------------- | ----------------------------------------------------- | ------------------ | ---------------------- |
|
||||
| `scan_library` | `ENABLE_SCHEDULED_RESCAN` | `0 3 * * *` (3 AM) | Full library rescan |
|
||||
| `update_switch_titledb` | `ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB` | `0 4 * * *` | Update Switch game DB |
|
||||
| `update_launchbox_metadata` | `ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA` | `0 4 * * *` | Refresh LaunchBox data |
|
||||
| `convert_images_to_webp` | `ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP` | `0 4 * * *` | Image optimization |
|
||||
| `sync_retroachievements_progress` | `ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC` | `0 4 * * *` | Sync RA user progress |
|
||||
| `cleanup_orphaned_resources` | `ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES` | `0 5 * * *` | Remove unused artwork |
|
||||
| `cleanup_netplay` | `ENABLE_SCHEDULED_CLEANUP_NETPLAY` (default on) | `*/30 * * * *` | Clean empty rooms |
|
||||
| `cleanup_upload_tmp` | `ENABLE_SCHEDULED_CLEANUP_UPLOAD_TMP` (default on) | `0 * * * *` | Drop stale uploads |
|
||||
| `cleanup_zip_cache` | `ENABLE_SCHEDULED_CLEANUP_ZIP_CACHE` (default on) | `0 4 * * *` | Drop stale cached ZIPs |
|
||||
| `cleanup_sync_sessions` | `ENABLE_SCHEDULED_CLEANUP_SYNC_SESSIONS` (default on) | `23 * * * *` | Fail abandoned syncs |
|
||||
| `reap_streaming_sessions` | `streaming.enabled` in config, read at startup | `* * * * *` | Stop abandoned streams |
|
||||
| `cleanup_audit_log` | `AUDIT_LOG_RETENTION_DAYS` above 0 (default 90) | `30 4 * * *` | Prune old audit events |
|
||||
| Task | Env Toggle | Default Cron | Description |
|
||||
| --------------------------------- | ----------------------------------------------------- | ------------------ | ------------------------------ |
|
||||
| `scan_library` | `ENABLE_SCHEDULED_RESCAN` | `0 3 * * *` (3 AM) | Full library rescan |
|
||||
| `update_switch_titledb` | `ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB` | `0 4 * * *` | Update Switch game DB |
|
||||
| `update_launchbox_metadata` | `ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA` | `0 4 * * *` | Refresh LaunchBox data |
|
||||
| `convert_images_to_webp` | `ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP` | `0 4 * * *` | Image optimization |
|
||||
| `sync_retroachievements_progress` | `ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC` | `0 4 * * *` | Sync RA user progress |
|
||||
| `cleanup_orphaned_resources` | `ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES` | `0 5 * * *` | Remove unused artwork |
|
||||
| `cleanup_netplay` | `ENABLE_SCHEDULED_CLEANUP_NETPLAY` (default on) | `*/30 * * * *` | Clean empty rooms |
|
||||
| `cleanup_upload_tmp` | `ENABLE_SCHEDULED_CLEANUP_UPLOAD_TMP` (default on) | `0 * * * *` | Drop stale uploads |
|
||||
| `cleanup_zip_cache` | `ENABLE_SCHEDULED_CLEANUP_ZIP_CACHE` (default on) | `0 4 * * *` | Drop stale cached ZIPs |
|
||||
| `cleanup_conversion_cache` | Always on | `0 4 * * *` | Drop stale converted downloads |
|
||||
| `cleanup_sync_sessions` | `ENABLE_SCHEDULED_CLEANUP_SYNC_SESSIONS` (default on) | `23 * * * *` | Fail abandoned syncs |
|
||||
| `reap_streaming_sessions` | `streaming.enabled` in config, read at startup | `* * * * *` | Stop abandoned streams |
|
||||
| `cleanup_audit_log` | `AUDIT_LOG_RETENTION_DAYS` above 0 (default 90) | `30 4 * * *` | Prune old audit events |
|
||||
|
||||
### Manual Tasks
|
||||
|
||||
Triggered via `POST /api/tasks/run/{task_name}`, which enqueues on `low_prio_queue` and answers 503 when no live worker is listening on it:
|
||||
|
||||
| Task | Description |
|
||||
| ---------------------- | --------------------------------------------- |
|
||||
| `cleanup_missing_roms` | Remove DB entries for files no longer on disk |
|
||||
| `sync_folder_scan` | Scan sync folder for new device saves |
|
||||
| Task | Description |
|
||||
| ---------------------- | ------------------------------------------------------------------------------------- |
|
||||
| `cleanup_missing_roms` | Remove DB entries for files no longer on disk |
|
||||
| `sync_folder_scan` | Scan sync folder for new device saves |
|
||||
| `convert_library` | Convert matched ROMs to `converto.platform_formats` in place, replacing the originals |
|
||||
|
||||
`convert_library` only converts losslessly (no xiso) and only identified ROMs, since a converted file no longer hash-matches a DAT. It stages each output under a `.romm_tmp_` directory beside the original, deletes the originals (and a cue's tracks) once the output is in place, rewrites `.m3u` entries in folder ROMs, and refreshes the ROM's files, so the ROM keeps its id, saves and collections.
|
||||
|
||||
`cleanup_orphaned_resources` is also runnable this way; it is listed under
|
||||
Scheduled Tasks because it additionally supports an opt-in cron schedule. It
|
||||
|
||||
@@ -262,15 +262,15 @@
|
||||
# cache_ttl_hours: 24
|
||||
# # Cache size before the least recently downloaded copies are evicted (0: unbounded)
|
||||
# cache_max_size_gb: 20
|
||||
# # Platform slug -> target format. Targets per platform:
|
||||
# # Platform slug -> the format the "Convert library" task stores its matched
|
||||
# # roms in, replacing the original files. Formats per platform:
|
||||
# # 3ds: cci, cia, z3ds
|
||||
# # psp, ps2: chd, cso, iso, zso
|
||||
# # psx, saturn, segacd, dc: chd, iso
|
||||
# # ngc: iso, rvz
|
||||
# # wii: iso, rvz, wbfs
|
||||
# # switch, switch-2: nsp, nsz, xci, xcz
|
||||
# # xbox: xiso
|
||||
# # xbox360: zar
|
||||
# platform_formats:
|
||||
# psp: cso
|
||||
# psx: chd
|
||||
# ngc: rvz
|
||||
|
||||
@@ -44,6 +44,7 @@ export type ConfigResponse = {
|
||||
GAMELIST_MEDIA_IMAGE: MetadataMediaType;
|
||||
PEGASUS_AUTO_EXPORT_ON_SCAN: boolean;
|
||||
CONVERTO: ConvertoConfig;
|
||||
CONVERTO_TARGETS: Record<string, Array<string>>;
|
||||
CONVERTO_LIBRARY_TARGETS: Record<string, Array<string>>;
|
||||
CONVERTO_DOWNLOAD_FORMATS: Record<string, Record<string, Array<string>>>;
|
||||
};
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ export type ConvertoConfig = {
|
||||
download_conversion_enabled?: boolean;
|
||||
cache_ttl_hours?: number;
|
||||
cache_max_size_gb?: number;
|
||||
max_sync_size_mb?: number;
|
||||
platform_formats?: Record<string, string>;
|
||||
};
|
||||
|
||||
|
||||
@@ -3,13 +3,11 @@
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* Full replacement of the converto.* config section.
|
||||
* The converto.* settings editable at runtime; `cache_ttl_hours` stays config.yml-only.
|
||||
*/
|
||||
export type ConvertoSettingsPayload = {
|
||||
download_conversion_enabled: boolean;
|
||||
cache_ttl_hours: number;
|
||||
cache_max_size_gb: number;
|
||||
max_sync_size_mb: number;
|
||||
platform_formats: Record<string, string>;
|
||||
};
|
||||
|
||||
|
||||
@@ -57,7 +57,8 @@ const defaultConfig = {
|
||||
cache_max_size_gb: 20,
|
||||
platform_formats: {},
|
||||
},
|
||||
CONVERTO_TARGETS: {},
|
||||
CONVERTO_LIBRARY_TARGETS: {},
|
||||
CONVERTO_DOWNLOAD_FORMATS: {},
|
||||
} as ConfigResponse;
|
||||
|
||||
export default defineStore("config", {
|
||||
|
||||
Reference in New Issue
Block a user