mirror of
https://github.com/rommapp/romm.git
synced 2026-12-06 15:54:45 +01:00
fix(export): encode filenames in ROM content URLs (#5596)
* fix(export): encode filenames in ROM content URLs
* refactor(export): share one ROM content URL builder (pr-ready: code-review)
Move the quoted get_rom_content URL into utils.urls.rom_content_url and use it
from both exporters and the feeds. Match the test route to the real
{file_name} converter and drop an unused fixture.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(export): share the ROM file URL builder too (pr-ready: simplify)
Move feeds' romfile download URL into utils.urls next to rom_content_url,
with the same encoding. Resolve the test's URLs against the real app router
and drop the branching that re-checked local paths.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(urls): cover the ROM and ROM file content URL builders (pr-ready: review-polish)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(export): match URL re-exports by ROM id and decode URL paths on import
A URL-mode gamelist or Pegasus export never matched its own earlier entries,
so each re-export appended every game again. Entries whose path is a RomM
content URL are now matched by the ROM id it carries, which also covers
unencoded URLs and other hostnames from older exports. The gamelist importer
decodes a URL path's last segment before matching it to a file name. Both
exports pass visibility=UNRESTRICTED explicitly, since they write the
library's shared metadata file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style: format romfile_content_url
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.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:
8 files changed
+296
-61
No files matched your search
+14
-35
@@ -5,7 +5,6 @@ from collections import Counter
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Any
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import HTTPException
|
||||
from fastapi import Path as PathVar
|
||||
@@ -59,27 +58,7 @@ from utils.archives import is_compressed_file
|
||||
from utils.datetime import format_utc
|
||||
from utils.platform_slugs import UniversalPlatformSlug as UPS
|
||||
from utils.router import APIRouter
|
||||
|
||||
|
||||
def generate_rom_download_url(request: Request, rom: Rom) -> str:
|
||||
return str(
|
||||
request.url_for(
|
||||
"get_rom_content",
|
||||
id=rom.id,
|
||||
file_name=quote(rom.fs_name, safe="/"),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def generate_romfile_download_url(request: Request, file: RomFile) -> str:
|
||||
return str(
|
||||
request.url_for(
|
||||
"get_romfile_content",
|
||||
file_id=file.id,
|
||||
file_name=quote(file.file_name, safe="/"),
|
||||
)
|
||||
)
|
||||
|
||||
from utils.urls import rom_content_url, romfile_content_url
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/feeds",
|
||||
@@ -138,7 +117,7 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema:
|
||||
**HAS_FILE_ON_DISK_FILTERS,
|
||||
)
|
||||
for rom in roms:
|
||||
download_url = generate_rom_download_url(request, rom)
|
||||
download_url = rom_content_url(request, rom)
|
||||
category_item = WebrcadeFeedItemSchema(
|
||||
title=rom.name or rom.fs_name_no_tags,
|
||||
description=rom.summary or "",
|
||||
@@ -254,7 +233,7 @@ async def tinfoil_index_feed(
|
||||
return TinfoilFeedSchema(
|
||||
files=[
|
||||
TinfoilFeedFileSchema(
|
||||
url=generate_romfile_download_url(request, rom_file),
|
||||
url=romfile_content_url(request, rom_file),
|
||||
size=rom_file.file_size_bytes,
|
||||
)
|
||||
for rom in roms
|
||||
@@ -311,7 +290,7 @@ def get_rap_data(request: Request, rom: Rom) -> tuple[str, str]:
|
||||
for file in rom.files:
|
||||
if file.file_extension.lower() == "rap":
|
||||
rap_hash = file.sha1_hash or ""
|
||||
rap_download_url = generate_romfile_download_url(request, file)
|
||||
rap_download_url = romfile_content_url(request, file)
|
||||
return rap_hash, rap_download_url
|
||||
|
||||
return "", ""
|
||||
@@ -375,7 +354,7 @@ def pkgi_ps3_feed(
|
||||
continue
|
||||
|
||||
content_id = generate_content_id(file)
|
||||
download_url = generate_romfile_download_url(request, file)
|
||||
download_url = romfile_content_url(request, file)
|
||||
|
||||
# Validate the item schema
|
||||
pkgi_item = PKGiFeedPS3ItemSchema(
|
||||
@@ -450,7 +429,7 @@ def pkgi_psvita_feed(
|
||||
continue
|
||||
|
||||
content_id = generate_content_id(file)
|
||||
download_url = generate_romfile_download_url(request, file)
|
||||
download_url = romfile_content_url(request, file)
|
||||
|
||||
pkgi_item = PKGiFeedPSVitaItemSchema(
|
||||
contentid=content_id,
|
||||
@@ -526,7 +505,7 @@ def pkgi_psp_feed(
|
||||
continue
|
||||
|
||||
content_id = generate_content_id(file)
|
||||
download_url = generate_romfile_download_url(request, file)
|
||||
download_url = romfile_content_url(request, file)
|
||||
|
||||
# Validate the item schema
|
||||
pkgi_item = PKGiFeedPSPItemSchema(
|
||||
@@ -696,7 +675,7 @@ def fpkgi_feed(
|
||||
if category_filter and category != category_filter:
|
||||
continue
|
||||
|
||||
download_url = generate_romfile_download_url(request, file)
|
||||
download_url = romfile_content_url(request, file)
|
||||
response_data[download_url] = FPKGiFeedItemSchema(
|
||||
name=item_names[file.id],
|
||||
size=file.file_size_bytes,
|
||||
@@ -744,7 +723,7 @@ def kekatsu_ds_feed(request: Request, platform_slug: str) -> Response:
|
||||
txt_lines.append("\t")
|
||||
|
||||
for rom in roms:
|
||||
download_url = generate_rom_download_url(request, rom)
|
||||
download_url = rom_content_url(request, rom)
|
||||
|
||||
# Generate box art URL if cover exists
|
||||
box_art_url = ""
|
||||
@@ -811,7 +790,7 @@ def pkgj_psp_games_feed(request: Request) -> Response:
|
||||
if not validate_pkgi_file(file, RomFileCategory.GAME):
|
||||
continue
|
||||
|
||||
download_url = generate_romfile_download_url(request, file)
|
||||
download_url = romfile_content_url(request, file)
|
||||
content_id = generate_content_id(file)
|
||||
last_modified = format_pkgj_datetime(file.updated_at)
|
||||
|
||||
@@ -875,7 +854,7 @@ def pkgj_psp_dlcs_feed(request: Request) -> Response:
|
||||
if not validate_pkgi_file(file, RomFileCategory.DLC):
|
||||
continue
|
||||
|
||||
download_url = generate_romfile_download_url(request, file)
|
||||
download_url = romfile_content_url(request, file)
|
||||
content_id = generate_content_id(file)
|
||||
last_modified = format_pkgj_datetime(file.updated_at)
|
||||
|
||||
@@ -936,7 +915,7 @@ def pkgj_psv_games_feed(request: Request) -> Response:
|
||||
if not validate_pkgi_file(file, RomFileCategory.GAME):
|
||||
continue
|
||||
|
||||
download_url = generate_romfile_download_url(request, file)
|
||||
download_url = romfile_content_url(request, file)
|
||||
content_id = generate_content_id(file)
|
||||
last_modified = format_pkgj_datetime(file.updated_at)
|
||||
|
||||
@@ -1001,7 +980,7 @@ def pkgj_psv_dlcs_feed(request: Request) -> Response:
|
||||
if not validate_pkgi_file(file, RomFileCategory.DLC):
|
||||
continue
|
||||
|
||||
download_url = generate_romfile_download_url(request, file)
|
||||
download_url = romfile_content_url(request, file)
|
||||
content_id = generate_content_id(file)
|
||||
last_modified = format_pkgj_datetime(file.updated_at)
|
||||
|
||||
@@ -1058,7 +1037,7 @@ def pkgj_psx_games_feed(request: Request) -> Response:
|
||||
if not validate_pkgi_file(file, RomFileCategory.GAME):
|
||||
continue
|
||||
|
||||
download_url = generate_romfile_download_url(request, file)
|
||||
download_url = romfile_content_url(request, file)
|
||||
content_id = generate_content_id(file)
|
||||
last_modified = format_pkgj_datetime(file.updated_at)
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import uuid
|
||||
from collections.abc import Callable, Collection, Iterator
|
||||
from pathlib import Path
|
||||
from typing import Final, Literal, NotRequired, TypedDict
|
||||
from urllib.parse import unquote, urlsplit
|
||||
from xml.etree.ElementTree import Element # trunk-ignore(bandit/B405)
|
||||
|
||||
import pydash
|
||||
@@ -153,8 +154,19 @@ XML_TAG_MAP: Final[dict[MediaUrlKey, str]] = {
|
||||
}
|
||||
|
||||
|
||||
def _url_file_name(raw_path: str) -> str | None:
|
||||
"""The decoded last segment of an http(s) <path>, as a URL export writes it."""
|
||||
parts = urlsplit(raw_path)
|
||||
if parts.scheme not in ("http", "https"):
|
||||
return None
|
||||
return unquote(parts.path.rsplit("/", 1)[-1])
|
||||
|
||||
|
||||
def gamelist_path_to_filename(raw_path: str) -> str:
|
||||
"""Return the filename a gamelist <path> refers to, without the `./` prefix."""
|
||||
url_name = _url_file_name(raw_path)
|
||||
if url_name is not None:
|
||||
return url_name
|
||||
return os.path.basename(raw_path.removeprefix("./"))
|
||||
|
||||
|
||||
@@ -162,8 +174,12 @@ def gamelist_path_to_rel_path(raw_path: str) -> str:
|
||||
"""Return a gamelist <path> as a path relative to the gamelist file itself.
|
||||
|
||||
Unlike the filename alone, this tells two identically named roms in different
|
||||
folders apart, which a custom library structure allows.
|
||||
folders apart, which a custom library structure allows. A URL only carries
|
||||
the filename.
|
||||
"""
|
||||
url_name = _url_file_name(raw_path)
|
||||
if url_name is not None:
|
||||
return url_name
|
||||
return raw_path.removeprefix("./").strip("/")
|
||||
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ from handler.metadata.gamelist_handler import (
|
||||
build_media_file_index,
|
||||
extract_media_from_gamelist_rom,
|
||||
extract_metadata_from_gamelist_rom,
|
||||
gamelist_path_to_filename,
|
||||
gamelist_path_to_rel_path,
|
||||
populate_rom_specific_paths,
|
||||
)
|
||||
from models.platform import Platform
|
||||
@@ -894,3 +896,21 @@ def test_parse_gamelist_xml_keeps_a_sort_names_leading_article(
|
||||
roms_data = GamelistHandler()._parse_gamelist_xml(gamelist_path, platform)
|
||||
|
||||
assert roms_data["test-rom.zip"].get("name_sort_key") == "the simpsons"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("raw_path", "rel_path", "filename"),
|
||||
[
|
||||
("./Hacks/Game (USA).sfc", "Hacks/Game (USA).sfc", "Game (USA).sfc"),
|
||||
(
|
||||
"https://example.test/api/roms/7/content/Game%20%28USA%29%20%231.sfc",
|
||||
"Game (USA) #1.sfc",
|
||||
"Game (USA) #1.sfc",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_gamelist_path_helpers_decode_content_urls(
|
||||
raw_path: str, rel_path: str, filename: str
|
||||
) -> None:
|
||||
assert gamelist_path_to_rel_path(raw_path) == rel_path
|
||||
assert gamelist_path_to_filename(raw_path) == filename
|
||||
@@ -0,0 +1,109 @@
|
||||
from collections.abc import Callable
|
||||
from xml.etree.ElementTree import fromstring
|
||||
|
||||
import pytest
|
||||
from fastapi import Request
|
||||
from main import app
|
||||
from tests.factories import make_platform, make_rom
|
||||
|
||||
from utils.gamelist_exporter import GamelistExporter, parse_existing_gamelist
|
||||
from utils.pegasus_exporter import PegasusExporter, parse_existing_pegasus
|
||||
|
||||
REQUEST = Request(
|
||||
{
|
||||
"type": "http",
|
||||
"scheme": "https",
|
||||
"server": ("example.test", 443),
|
||||
"headers": [],
|
||||
"root_path": "/romm",
|
||||
"router": app.router,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def pegasus_path(platform_id: int, request: Request) -> str:
|
||||
content = PegasusExporter(local_export=False).export_platform_to_pegasus(
|
||||
platform_id, request=request
|
||||
)
|
||||
return next(
|
||||
line.removeprefix("file: ")
|
||||
for line in content.splitlines()
|
||||
if line.startswith("file: ")
|
||||
)
|
||||
|
||||
|
||||
def gamelist_path(platform_id: int, request: Request) -> str:
|
||||
content = GamelistExporter(local_export=False).export_platform_to_xml(
|
||||
platform_id, request=request
|
||||
)
|
||||
return fromstring(content).findtext("game/path", default="")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"export_path",
|
||||
[
|
||||
pytest.param(pegasus_path, id="pegasus"),
|
||||
pytest.param(gamelist_path, id="gamelist"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
("fs_stem", "encoded_name"),
|
||||
[
|
||||
("Game #1?", "Game%20%231%3F.zip"),
|
||||
("100% + game", "100%25%20%2B%20game.zip"),
|
||||
("Game%20", "Game%2520.zip"),
|
||||
("Café", "Caf%C3%A9.zip"),
|
||||
("game", "game.zip"),
|
||||
],
|
||||
)
|
||||
def test_export_content_url_encodes_filename(
|
||||
export_path: Callable[[int, Request], str], fs_stem: str, encoded_name: str
|
||||
) -> None:
|
||||
platform = make_platform("nes")
|
||||
rom = make_rom(platform, "URL test", fs_stem=fs_stem)
|
||||
|
||||
assert (
|
||||
export_path(platform.id, REQUEST)
|
||||
== f"https://example.test/romm/api/roms/{rom.id}/content/{encoded_name}"
|
||||
)
|
||||
|
||||
|
||||
def test_gamelist_url_reexport_matches_entry_by_rom_id() -> None:
|
||||
platform = make_platform("nes")
|
||||
rom = make_rom(platform, "URL test", fs_stem="Game #1?")
|
||||
existing = parse_existing_gamelist(f"""<gameList>
|
||||
<game>
|
||||
<path>http://old.host/api/roms/{rom.id}/content/Game #1?.zip</path>
|
||||
<favorite>true</favorite>
|
||||
</game>
|
||||
</gameList>""")
|
||||
|
||||
xml, _ = GamelistExporter(local_export=False)._build_gamelist_xml(
|
||||
platform.id, request=REQUEST, platform_dir=None, existing=existing
|
||||
)
|
||||
|
||||
games = fromstring(xml).findall("game")
|
||||
assert len(games) == 1
|
||||
assert games[0].findtext("path") == (
|
||||
f"https://example.test/romm/api/roms/{rom.id}/content/Game%20%231%3F.zip"
|
||||
)
|
||||
assert games[0].findtext("favorite") == "true"
|
||||
|
||||
|
||||
def test_pegasus_url_reexport_matches_entry_by_rom_id() -> None:
|
||||
platform = make_platform("nes")
|
||||
rom = make_rom(platform, "URL test", fs_stem="Game #1?")
|
||||
existing = parse_existing_pegasus(f"""game: URL test
|
||||
file: http://old.host/api/roms/{rom.id}/content/Game #1?.zip
|
||||
x-favorite: yes
|
||||
""")
|
||||
|
||||
content, _ = PegasusExporter(local_export=False)._build_pegasus(
|
||||
platform.id, request=REQUEST, platform_dir=None, existing=existing
|
||||
)
|
||||
|
||||
file_lines = [line for line in content.splitlines() if line.startswith("file:")]
|
||||
assert file_lines == [
|
||||
f"file: https://example.test/romm/api/roms/{rom.id}/content/Game%20%231%3F.zip"
|
||||
]
|
||||
assert "x-favorite: yes" in content.splitlines()
|
||||
@@ -0,0 +1,48 @@
|
||||
import pytest
|
||||
from fastapi import Request
|
||||
from main import app
|
||||
|
||||
from models.rom import Rom, RomFile
|
||||
from utils.urls import rom_content_url, rom_id_from_content_url, romfile_content_url
|
||||
|
||||
REQUEST = Request(
|
||||
{
|
||||
"type": "http",
|
||||
"scheme": "https",
|
||||
"server": ("example.test", 443),
|
||||
"headers": [],
|
||||
"root_path": "",
|
||||
"router": app.router,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_rom_content_url_encodes_fs_name() -> None:
|
||||
rom = Rom(id=7, fs_name="Game #1?.zip")
|
||||
|
||||
assert (
|
||||
rom_content_url(REQUEST, rom)
|
||||
== "https://example.test/api/roms/7/content/Game%20%231%3F.zip"
|
||||
)
|
||||
|
||||
|
||||
def test_romfile_content_url_encodes_file_name() -> None:
|
||||
file = RomFile(id=9, file_name="Disc 1/100%.bin")
|
||||
|
||||
assert (
|
||||
romfile_content_url(REQUEST, file)
|
||||
== "https://example.test/api/roms/9/files/content/Disc%201%2F100%25.bin"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "rom_id"),
|
||||
[
|
||||
("https://example.test/romm/api/roms/12/content/Game%20%231.zip", 12),
|
||||
("http://old.host/api/roms/3/content/Game #1?.zip", 3),
|
||||
("https://example.test/api/roms/3/files/content/Game.zip", None),
|
||||
("./Game.zip", None),
|
||||
],
|
||||
)
|
||||
def test_rom_id_from_content_url(value: str, rom_id: int | None) -> None:
|
||||
assert rom_id_from_content_url(value) == rom_id
|
||||
@@ -19,6 +19,7 @@ from starlette.datastructures import URLPath
|
||||
from config import FRONTEND_RESOURCES_PATH, YOUTUBE_BASE_URL
|
||||
from config.config_manager import PLATFORM_MEDIA_DIRS
|
||||
from config.config_manager import config_manager as cm
|
||||
from handler.auth.rom_visibility import UNRESTRICTED
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.filesystem import fs_platform_handler, fs_resource_handler
|
||||
from handler.metadata.gamelist_handler import gamelist_path_to_rel_path
|
||||
@@ -26,6 +27,7 @@ from logger.logger import log
|
||||
from models.rom import HAS_FILE_ON_DISK_FILTERS, Rom
|
||||
from utils.datetime import format_utc
|
||||
from utils.filesystem import join_rel_path, place_export_asset, rel_platform_folder
|
||||
from utils.urls import rom_content_url, rom_id_from_content_url
|
||||
|
||||
# Each tag maps to the assets it can take, best first. RetroBat reads some of the
|
||||
# same media under its own names (cartridge, titleshot, mix), hence the repeats.
|
||||
@@ -60,12 +62,13 @@ class ExistingGamelist:
|
||||
"""What an on-disk gamelist.xml holds that RomM did not generate."""
|
||||
|
||||
games: dict[str, Element] = field(default_factory=dict)
|
||||
games_by_rom_id: dict[int, Element] = field(default_factory=dict)
|
||||
others: list[Element] = field(default_factory=list)
|
||||
root_siblings: list[Element] = field(default_factory=list)
|
||||
|
||||
|
||||
def parse_existing_gamelist(content: str) -> ExistingGamelist:
|
||||
"""Index a gamelist.xml by ROM path, keeping every element RomM does not own.
|
||||
"""Index a gamelist.xml by ROM path or content URL, keeping every other element.
|
||||
|
||||
ES-DE writes <alternativeEmulator> beside <gameList>, so the document is
|
||||
parsed under a wrapper root to accept those siblings.
|
||||
@@ -92,13 +95,13 @@ def parse_existing_gamelist(content: str) -> ExistingGamelist:
|
||||
|
||||
for elem in gamelist:
|
||||
path_elem = elem.find("path") if elem.tag == "game" else None
|
||||
rel_path = (
|
||||
gamelist_path_to_rel_path(path_elem.text)
|
||||
if path_elem is not None and path_elem.text
|
||||
else None
|
||||
)
|
||||
# A second entry with the same path is carried over, not dropped.
|
||||
if rel_path and rel_path not in existing.games:
|
||||
raw_path = path_elem.text if path_elem is not None else None
|
||||
rom_id = rom_id_from_content_url(raw_path) if raw_path else None
|
||||
rel_path = gamelist_path_to_rel_path(raw_path) if raw_path else None
|
||||
# A second entry with the same key is carried over, not dropped.
|
||||
if rom_id is not None and rom_id not in existing.games_by_rom_id:
|
||||
existing.games_by_rom_id[rom_id] = elem
|
||||
elif rom_id is None and rel_path and rel_path not in existing.games:
|
||||
existing.games[rel_path] = elem
|
||||
else:
|
||||
existing.others.append(elem)
|
||||
@@ -255,13 +258,7 @@ class GamelistExporter:
|
||||
raise ValueError(
|
||||
"Request object must be provided for non-local exports"
|
||||
)
|
||||
SubElement(game, "path").text = str(
|
||||
request.url_for(
|
||||
"get_rom_content",
|
||||
id=rom.id,
|
||||
file_name=rom.fs_name,
|
||||
)
|
||||
)
|
||||
SubElement(game, "path").text = rom_content_url(request, rom)
|
||||
|
||||
SubElement(game, "name").text = rom.name or rom.fs_name
|
||||
|
||||
@@ -358,11 +355,14 @@ class GamelistExporter:
|
||||
raise ValueError(f"Platform with ID {platform_id} not found")
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform_id], **HAS_FILE_ON_DISK_FILTERS
|
||||
platform_ids=[platform_id],
|
||||
visibility=UNRESTRICTED,
|
||||
**HAS_FILE_ON_DISK_FILTERS,
|
||||
)
|
||||
|
||||
existing = existing or ExistingGamelist()
|
||||
unmatched_games = dict(existing.games)
|
||||
unmatched_by_rom_id = dict(existing.games_by_rom_id)
|
||||
|
||||
root = Element("gameList")
|
||||
root.extend(existing.others)
|
||||
@@ -394,15 +394,18 @@ class GamelistExporter:
|
||||
media_thumbnail=media_thumbnail,
|
||||
rel_folder=rel_folder,
|
||||
)
|
||||
existing_game = unmatched_games.pop(
|
||||
join_rel_path(rel_folder, rom.fs_name), None
|
||||
)
|
||||
existing_game = unmatched_by_rom_id.pop(rom.id, None)
|
||||
if existing_game is None:
|
||||
existing_game = unmatched_games.pop(
|
||||
join_rel_path(rel_folder, rom.fs_name), None
|
||||
)
|
||||
if existing_game is not None:
|
||||
merge_existing_game(game_element, existing_game)
|
||||
root.append(game_element)
|
||||
count += 1
|
||||
|
||||
root.extend(unmatched_games.values())
|
||||
root.extend(unmatched_by_rom_id.values())
|
||||
|
||||
indent(root, space=" ", level=0)
|
||||
xml_str = tostring(root, encoding="unicode", xml_declaration=True)
|
||||
|
||||
@@ -5,6 +5,7 @@ from typing import Final
|
||||
from fastapi import Request
|
||||
|
||||
from config.config_manager import PLATFORM_MEDIA_DIRS
|
||||
from handler.auth.rom_visibility import UNRESTRICTED
|
||||
from handler.database import db_platform_handler, db_rom_handler
|
||||
from handler.filesystem import fs_platform_handler, fs_resource_handler
|
||||
from logger.logger import log
|
||||
@@ -13,6 +14,7 @@ from models.rom import HAS_FILE_ON_DISK_FILTERS, Rom
|
||||
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
|
||||
from utils.urls import rom_content_url, rom_id_from_content_url
|
||||
|
||||
# Map RomM platform slugs to canonical Pegasus (collection name, shortname) pairs.
|
||||
# Source: https://www.pegasus-frontend.org/docs/user-guide/meta-files/
|
||||
@@ -209,6 +211,13 @@ class PegasusBlock:
|
||||
def lines(self, skip: frozenset[str] | set[str] = frozenset()) -> list[str]:
|
||||
return [line for key, lines in self.fields if key not in skip for line in lines]
|
||||
|
||||
def content_url_rom_id(self) -> int | None:
|
||||
"""The ROM id in the block's `file:` when that is a RomM content URL."""
|
||||
for key, lines in self.fields:
|
||||
if key == "file":
|
||||
return rom_id_from_content_url(lines[0].partition(":")[2].strip())
|
||||
return None
|
||||
|
||||
def file_paths(self) -> set[str]:
|
||||
"""Each listed path, plus the folders holding it.
|
||||
|
||||
@@ -395,9 +404,7 @@ class PegasusExporter:
|
||||
raise ValueError(
|
||||
"Request object must be provided for non-local exports"
|
||||
)
|
||||
lines.append(
|
||||
f"file: {request.url_for('get_rom_content', id=rom.id, file_name=rom.fs_name)}"
|
||||
)
|
||||
lines.append(f"file: {rom_content_url(request, rom)}")
|
||||
|
||||
# Sort title (use fs_name_no_tags if different from name)
|
||||
if rom.name and rom.fs_name_no_tags and rom.name != rom.fs_name_no_tags:
|
||||
@@ -472,7 +479,9 @@ class PegasusExporter:
|
||||
raise ValueError(f"Platform with ID {platform_id} not found")
|
||||
|
||||
roms = db_rom_handler.get_roms_scalar(
|
||||
platform_ids=[platform_id], **HAS_FILE_ON_DISK_FILTERS
|
||||
platform_ids=[platform_id],
|
||||
visibility=UNRESTRICTED,
|
||||
**HAS_FILE_ON_DISK_FILTERS,
|
||||
)
|
||||
|
||||
existing = existing or ExistingPegasus()
|
||||
@@ -482,6 +491,11 @@ class PegasusExporter:
|
||||
for index, game in enumerate(existing.games)
|
||||
for path in game.file_paths()
|
||||
}
|
||||
game_index_by_rom_id: dict[int, int] = {}
|
||||
for index, game in enumerate(existing.games):
|
||||
rom_id = game.content_url_rom_id()
|
||||
if rom_id is not None:
|
||||
game_index_by_rom_id.setdefault(rom_id, index)
|
||||
platform_fs_path = fs_platform_handler.get_platform_fs_structure(
|
||||
platform.fs_slug
|
||||
)
|
||||
@@ -530,9 +544,13 @@ class PegasusExporter:
|
||||
entry_lines = entry.splitlines()
|
||||
|
||||
existing_game = unmatched_games.pop(
|
||||
game_index_by_path.get(join_rel_path(rel_folder, rom.fs_name), -1),
|
||||
None,
|
||||
game_index_by_rom_id.get(rom.id, -1), None
|
||||
)
|
||||
if existing_game is None:
|
||||
existing_game = unmatched_games.pop(
|
||||
game_index_by_path.get(join_rel_path(rel_folder, rom.fs_name), -1),
|
||||
None,
|
||||
)
|
||||
if existing_game is not None:
|
||||
emitted_keys = parse_pegasus(entry)[-1].keys()
|
||||
entry_lines.extend(existing_game.lines(skip=emitted_keys))
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Final
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
import yarl
|
||||
from fastapi import Request
|
||||
|
||||
import config
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from models.rom import Rom, RomFile
|
||||
|
||||
# The tail of the get_rom_content route, matched whatever host or root path served it.
|
||||
ROM_CONTENT_PATH_RE: Final = re.compile(r"/api/roms/(\d+)/content/[^/]*$")
|
||||
|
||||
|
||||
def is_shareable_host(host: str) -> bool:
|
||||
"""Whether a host resolves to something other than the instance itself."""
|
||||
@@ -24,3 +36,33 @@ def get_public_base_url() -> str | None:
|
||||
if not is_shareable_host(url.host):
|
||||
return None
|
||||
return str(url).rstrip("/")
|
||||
|
||||
|
||||
# url_for inserts path params verbatim, so a `#`, `?` or `%` would break the URL.
|
||||
def rom_content_url(request: Request, rom: Rom) -> str:
|
||||
"""Absolute download URL for `rom`, its file name percent-encoded."""
|
||||
return str(
|
||||
request.url_for(
|
||||
"get_rom_content", id=rom.id, file_name=quote(rom.fs_name, safe="")
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def romfile_content_url(request: Request, file: RomFile) -> str:
|
||||
"""Absolute download URL for one file of a ROM, its name percent-encoded."""
|
||||
return str(
|
||||
request.url_for(
|
||||
"get_romfile_content",
|
||||
file_id=file.id,
|
||||
file_name=quote(file.file_name, safe=""),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def rom_id_from_content_url(value: str) -> int | None:
|
||||
"""The ROM id in a URL `rom_content_url` built, or None for anything else."""
|
||||
parts = urlsplit(value)
|
||||
if parts.scheme not in ("http", "https"):
|
||||
return None
|
||||
match = ROM_CONTENT_PATH_RE.search(parts.path)
|
||||
return int(match.group(1)) if match else None
|
||||
Reference in new issue
Block a user