mirror of
https://github.com/rommapp/romm.git
synced 2026-12-04 12:52:19 +01:00
fix: Export HLTB and RetroAchievements extras in Pegasus metadata (#5825)
* Export HLTB and RetroAchievements extras in Pegasus metadata * fix(pegasus): address Greptile review on HLTB/RA export Skip malformed hltb_metadata and achievement values instead of failing the export, emit x-ra-id whenever the ROM has one, shorten the comment, and rename the loop variable that shadowed dataclasses.field (ruff F402). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: code-review Drop stale x-hltb-*/x-ra-* keys when merging into an existing metadata file, count only well-formed achievements, and skip boolean HLTB values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: prose Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: prose (code-review additions) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(roms): drop the old RA metadata when a manual rematch misses Changing ra_id to a game RetroAchievements cannot resolve kept the new id but the previous game's achievements, genres and companies, so exports paired the new id with the old totals. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: rwendell <rwendell@users.noreply.github.com> Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2026,11 +2026,9 @@ async def _refetch_ss(rom: Rom, ss_id: Any) -> Mapping[str, object]:
|
||||
return exc.fallback
|
||||
|
||||
|
||||
def _ra_miss(rom: Rom) -> dict[str, Any]:
|
||||
# The kept blob's hash match was earned against the previous game.
|
||||
if rom.ra_metadata and rom.ra_metadata.get("hash_match"):
|
||||
return {"ra_metadata": {**rom.ra_metadata, "hash_match": False}}
|
||||
return {}
|
||||
def _ra_miss(_rom: Rom) -> dict[str, Any]:
|
||||
# The typed id is kept, so the previous game's achievements must not ride along.
|
||||
return {"ra_metadata": {}}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -2770,17 +2770,24 @@ class TestUpdateMetadataIDs:
|
||||
assert get_rom_by_id_mock.called
|
||||
|
||||
@patch.object(RAHandler, "get_rom_by_id", return_value=RAGameRom(ra_id=None))
|
||||
def test_update_rom_ra_id_drops_the_previous_games_hash_match(
|
||||
def test_update_rom_ra_id_drops_the_previous_games_metadata(
|
||||
self,
|
||||
get_rom_by_id_mock: AsyncMock,
|
||||
client: TestClient,
|
||||
access_token: str,
|
||||
rom: Rom,
|
||||
):
|
||||
"""A relink RA can't resolve keeps the old blob, but not its verification."""
|
||||
"""A relink RA can't resolve keeps the new id but none of the old game's data."""
|
||||
db_rom_handler.update_rom(
|
||||
rom.id,
|
||||
{"ra_id": 1, "ra_metadata": {"achievements": [], "hash_match": True}},
|
||||
{
|
||||
"ra_id": 1,
|
||||
"ra_metadata": {
|
||||
"achievements": [{"ra_id": 7, "points": 10}],
|
||||
"genres": ["Platform"],
|
||||
"hash_match": True,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
response = client.put(
|
||||
@@ -2792,7 +2799,7 @@ class TestUpdateMetadataIDs:
|
||||
|
||||
body = response.json()
|
||||
assert body["ra_id"] == MOCK_RA_ID
|
||||
assert body["merged_ra_metadata"]["hash_match"] is False
|
||||
assert not body["merged_ra_metadata"]
|
||||
|
||||
@patch.object(
|
||||
LaunchboxHandler,
|
||||
|
||||
@@ -47,6 +47,9 @@ def _mock_rom(**overrides) -> Rom:
|
||||
"path_screenshots": None,
|
||||
"path_video": None,
|
||||
"metadatum": None,
|
||||
"hltb_metadata": None,
|
||||
"ra_id": None,
|
||||
"ra_metadata": None,
|
||||
}
|
||||
defaults.update(overrides)
|
||||
mock = MagicMock(spec=Rom)
|
||||
@@ -472,6 +475,62 @@ class TestGameEntry:
|
||||
for key, path in exported_assets.items():
|
||||
assert f"assets.{key}: {path}" in entry
|
||||
|
||||
def test_game_entry_with_hltb_and_retroachievements(self):
|
||||
rom = _mock_rom(
|
||||
id=42,
|
||||
hltb_metadata={
|
||||
"main_story": 3600,
|
||||
"main_plus_extra": 7200,
|
||||
"completionist": 18000,
|
||||
},
|
||||
ra_id=123,
|
||||
ra_metadata={
|
||||
"achievements": [
|
||||
{"points": 10},
|
||||
{"points": 5},
|
||||
{"points": 0},
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
entry = PegasusExporter(local_export=True)._create_game_entry(rom, request=None)
|
||||
|
||||
assert "x-hltb-main: 3600" in entry
|
||||
assert "x-hltb-extra: 7200" in entry
|
||||
assert "x-hltb-100: 18000" in entry
|
||||
assert "x-ra-id: 123" in entry
|
||||
assert "x-ra-count: 3" in entry
|
||||
assert "x-ra-points: 15" in entry
|
||||
|
||||
def test_game_entry_skips_malformed_hltb_and_ra_values(self):
|
||||
rom = _mock_rom(
|
||||
id=42,
|
||||
hltb_metadata={
|
||||
"main_story": "abc",
|
||||
"main_plus_extra": True,
|
||||
"completionist": 18000,
|
||||
},
|
||||
ra_id=123,
|
||||
ra_metadata={"achievements": ["bad", {"points": "x"}, {"points": 7}]},
|
||||
)
|
||||
|
||||
entry = PegasusExporter(local_export=True)._create_game_entry(rom, request=None)
|
||||
|
||||
assert "x-hltb-main" not in entry
|
||||
assert "x-hltb-extra" not in entry
|
||||
assert "x-hltb-100: 18000" in entry
|
||||
assert "x-ra-count: 2" in entry
|
||||
assert "x-ra-points: 7" in entry
|
||||
|
||||
def test_game_entry_ra_id_without_achievements(self):
|
||||
rom = _mock_rom(id=42, ra_id=123, ra_metadata={"achievements": []})
|
||||
|
||||
entry = PegasusExporter(local_export=True)._create_game_entry(rom, request=None)
|
||||
|
||||
assert "x-ra-id: 123" in entry
|
||||
assert "x-ra-count" not in entry
|
||||
assert "x-ra-points" not in entry
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def snes_platform(admin_user: User) -> Platform:
|
||||
@@ -626,6 +685,29 @@ file: hack.sfc
|
||||
assert mario["file"] == "Super Mario World (USA).sfc"
|
||||
assert mario["x-note"] == "multi"
|
||||
|
||||
async def test_drops_stale_hltb_and_retroachievements_keys(
|
||||
self, snes_platform: Platform, metadata_file: Path
|
||||
):
|
||||
"""A ROM with no HLTB or RA match loses the values an earlier export wrote."""
|
||||
_write_metadata(
|
||||
metadata_file,
|
||||
"collection: SNES\nshortname: snes\n\n"
|
||||
"game: Old\nfile: Super Mario World (USA).sfc\n"
|
||||
"x-hltb-main: 3600\nx-hltb-extra: 7200\nx-hltb-100: 18000\n"
|
||||
"x-ra-id: 123\nx-ra-count: 3\nx-ra-points: 15\nx-favorite: yes\n",
|
||||
)
|
||||
|
||||
exporter = PegasusExporter(local_export=True)
|
||||
assert (
|
||||
await exporter.export_platform_to_file(snes_platform.id, request=None)
|
||||
is True
|
||||
)
|
||||
|
||||
content = _read_metadata(metadata_file)
|
||||
assert "x-hltb-" not in content
|
||||
assert "x-ra-" not in content
|
||||
assert _parse_pegasus(content)["games"][0]["x-favorite"] == "yes"
|
||||
|
||||
async def test_refuses_to_overwrite_undecodable_file(
|
||||
self, snes_platform: Platform, metadata_file: Path
|
||||
):
|
||||
|
||||
@@ -11,6 +11,7 @@ from handler.filesystem import fs_platform_handler, fs_resource_handler
|
||||
from logger.logger import log
|
||||
from models.platform import Platform
|
||||
from models.rom import HAS_FILE_ON_DISK_FILTERS, Rom
|
||||
from utils import safe_int
|
||||
from utils.datetime import format_utc
|
||||
from utils.filesystem import join_rel_path, place_export_asset, rel_platform_folder
|
||||
from utils.platform_slugs import UniversalPlatformSlug as UPS
|
||||
@@ -185,6 +186,23 @@ PEGASUS_ASSET_ALIASES: Final[dict[str, str]] = {
|
||||
|
||||
COLLECTION_HEADER_KEYS: Final = frozenset({"collection", "shortname"})
|
||||
|
||||
# Maps each `x-hltb-*` suffix to the HLTB duration field it exports.
|
||||
HLTB_PEGASUS_FIELDS: Final[dict[str, str]] = {
|
||||
"main": "main_story",
|
||||
"extra": "main_plus_extra",
|
||||
"100": "completionist",
|
||||
}
|
||||
|
||||
# Only RomM writes these, so an existing value is dropped once RomM stops emitting it.
|
||||
ROMM_OWNED_GAME_KEYS: Final = frozenset(
|
||||
{
|
||||
*(f"x-hltb-{key}" for key in HLTB_PEGASUS_FIELDS),
|
||||
"x-ra-id",
|
||||
"x-ra-count",
|
||||
"x-ra-points",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def canonical_pegasus_key(key: str) -> str:
|
||||
"""Fold every spelling Pegasus accepts for a lowercased key into one name."""
|
||||
@@ -465,6 +483,29 @@ class PegasusExporter:
|
||||
|
||||
lines.append(f"x-romm-id: {rom.id}")
|
||||
|
||||
# Metadata edited as raw JSON is not validated, so malformed values are skipped.
|
||||
hltb = rom.hltb_metadata if isinstance(rom.hltb_metadata, dict) else {}
|
||||
for key, hltb_field in HLTB_PEGASUS_FIELDS.items():
|
||||
value = hltb.get(hltb_field)
|
||||
seconds = 0 if isinstance(value, bool) else safe_int(value)
|
||||
if seconds > 0:
|
||||
lines.append(f"x-hltb-{key}: {seconds}")
|
||||
|
||||
if rom.ra_id:
|
||||
lines.append(f"x-ra-id: {rom.ra_id}")
|
||||
|
||||
ra = rom.ra_metadata if isinstance(rom.ra_metadata, dict) else {}
|
||||
achievements = ra.get("achievements")
|
||||
entries = (
|
||||
[item for item in achievements if isinstance(item, dict)]
|
||||
if isinstance(achievements, list)
|
||||
else []
|
||||
)
|
||||
if entries:
|
||||
points = sum(safe_int(item.get("points")) for item in entries)
|
||||
lines.append(f"x-ra-count: {len(entries)}")
|
||||
lines.append(f"x-ra-points: {points}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
def _build_pegasus(
|
||||
@@ -558,7 +599,9 @@ class PegasusExporter:
|
||||
)
|
||||
if existing_game is not None:
|
||||
emitted_keys = parse_pegasus(entry)[-1].keys()
|
||||
entry_lines.extend(existing_game.lines(skip=emitted_keys))
|
||||
entry_lines.extend(
|
||||
existing_game.lines(skip=emitted_keys | ROMM_OWNED_GAME_KEYS)
|
||||
)
|
||||
|
||||
if game_count > 0:
|
||||
lines.append("")
|
||||
|
||||
Reference in New Issue
Block a user