fix(patcher): patch ROM members inside ZIP archives

This commit is contained in:
Kyle Benzo
2026-09-11 21:23:20 -07:00
parent 839605e679
commit 3511214fe7
8 changed files with 703 additions and 16 deletions

View File

@@ -4,15 +4,10 @@ from pathlib import Path
from typing import Annotated
from urllib.parse import quote
from fastapi import File, Form, HTTPException
from fastapi import Path as PathVar
from fastapi import Request, UploadFile, status
from pydantic import BaseModel
from starlette.background import BackgroundTask
from starlette.responses import FileResponse
from config import ROM_PATCHER_MAX_FILE_SIZE_BYTES
from decorators.auth import protected_route
from fastapi import File, Form, HTTPException, Request, UploadFile, status
from fastapi import Path as PathVar
from handler.auth.constants import Scope
from handler.auth.dependencies import ResolvedPermissions, get_permissions
from handler.database import db_rom_handler
@@ -20,7 +15,15 @@ from handler.filesystem import fs_rom_handler
from logger.formatter import BLUE
from logger.formatter import highlight as hl
from logger.logger import log
from utils.rom_patcher import SUPPORTED_PATCH_EXTENSIONS, PatcherError, apply_patch
from pydantic import BaseModel
from starlette.background import BackgroundTask
from starlette.responses import FileResponse
from utils.rom_patcher import (
SUPPORTED_PATCH_EXTENSIONS,
PatcherError,
PatcherInputError,
apply_patch,
)
from utils.router import APIRouter
router = APIRouter()
@@ -59,6 +62,10 @@ async def patch_rom(
description="Custom output file name. If omitted, derived from ROM + patch names.",
),
] = None,
archive_member_name: Annotated[
str | None,
Form(description="File inside a ZIP ROM archive to patch."),
] = None,
patch_file: Annotated[
UploadFile | None,
File(
@@ -150,10 +157,18 @@ async def patch_rom(
f"ROM file {hl(rom_file.file_name)} with patch {hl(patch_display_name)}"
)
validated = await apply_patch(rom_path, patch_path, output_path)
validated = await apply_patch(
rom_path, patch_path, output_path, archive_member_name
)
except HTTPException:
shutil.rmtree(tmp_dir, ignore_errors=True)
raise
except PatcherInputError as e:
shutil.rmtree(tmp_dir, ignore_errors=True)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e),
) from e
except PatcherError as e:
shutil.rmtree(tmp_dir, ignore_errors=True)
# Detail may contain server paths from node/RomPatcher.js; keep it server-side.

View File

@@ -0,0 +1,95 @@
from pathlib import Path
import pytest
from endpoints.roms import patch as patch_endpoint
from fastapi import status
from fastapi.testclient import TestClient
from handler.database import db_rom_handler
from models.rom import Rom, RomFile, RomFileCategory
from utils.rom_patcher import PatcherInputError
def _auth(token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
def _patch_file(rom: Rom) -> RomFile:
return db_rom_handler.add_rom_file(
RomFile(
rom_id=rom.id,
file_name="translation.bps",
file_path=rom.fs_path,
file_size_bytes=100,
category=RomFileCategory.PATCH,
)
)
def test_patch_rom_passes_archive_member_and_validation_header(
client: TestClient,
access_token: str,
rom: Rom,
rom_file: RomFile,
monkeypatch: pytest.MonkeyPatch,
):
patch_file = _patch_file(rom)
received_member: str | None = None
async def patch(
_rom_path: Path,
_patch_path: Path,
output_path: Path,
archive_member_name: str | None,
) -> bool:
nonlocal received_member
received_member = archive_member_name
output_path.write_bytes(b"patched zip")
return False
monkeypatch.setattr(
patch_endpoint.fs_rom_handler, "validate_path", lambda path: Path(path)
)
monkeypatch.setattr(patch_endpoint, "apply_patch", patch)
response = client.post(
f"/api/roms/{rom_file.id}/patch",
headers=_auth(access_token),
data={
"patch_file_id": patch_file.id,
"archive_member_name": "roms/game.sfc",
},
)
assert response.status_code == status.HTTP_200_OK
assert response.content == b"patched zip"
assert response.headers["x-patch-validated"] == "false"
assert received_member == "roms/game.sfc"
def test_patch_rom_returns_bad_request_for_invalid_archive(
client: TestClient,
access_token: str,
rom: Rom,
rom_file: RomFile,
monkeypatch: pytest.MonkeyPatch,
):
patch_file = _patch_file(rom)
async def reject_patch(*_args, **_kwargs) -> bool:
raise PatcherInputError("Select which file inside the ROM archive to patch")
monkeypatch.setattr(
patch_endpoint.fs_rom_handler, "validate_path", lambda path: Path(path)
)
monkeypatch.setattr(patch_endpoint, "apply_patch", reject_patch)
response = client.post(
f"/api/roms/{rom_file.id}/patch",
headers=_auth(access_token),
data={"patch_file_id": patch_file.id},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json() == {
"detail": "Select which file inside the ROM archive to patch"
}

View File

@@ -1,5 +1,232 @@
from utils.rom_patcher import SUPPORTED_PATCH_EXTENSIONS
import zipfile
from collections.abc import Awaitable, Callable
from pathlib import Path
import pytest
from utils.rom_patcher import (
SUPPORTED_PATCH_EXTENSIONS,
PatcherInputError,
apply_patch,
)
from utils.rom_patcher import patcher as rom_patcher
def _write_zip(
path: Path,
members: dict[str, bytes],
*,
comment: bytes = b"",
) -> None:
with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
archive.comment = comment
for name, content in members.items():
archive.writestr(name, content)
def _fake_patcher(
expected_source: bytes,
patched_content: bytes,
*,
validated: bool = True,
) -> Callable[[Path, Path, Path], Awaitable[bool]]:
async def patch(rom_path: Path, _patch_path: Path, output_path: Path) -> bool:
assert rom_path.read_bytes() == expected_source
output_path.write_bytes(patched_content)
return validated
return patch
def test_supported_patch_extensions_include_xdelta():
assert ".xdelta" in SUPPORTED_PATCH_EXTENSIONS
@pytest.mark.asyncio
async def test_apply_patch_keeps_raw_rom_behavior(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source = tmp_path / "game.sfc"
patch = tmp_path / "translation.bps"
output = tmp_path / "patched.sfc"
source.write_bytes(b"source")
patch.write_bytes(b"patch")
monkeypatch.setattr(
rom_patcher,
"_apply_binary_patch",
_fake_patcher(b"source", b"patched", validated=False),
)
validated = await apply_patch(source, patch, output)
assert validated is False
assert output.read_bytes() == b"patched"
@pytest.mark.asyncio
async def test_apply_patch_rebuilds_single_member_snes_zip(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source = tmp_path / "game.zip"
patch = tmp_path / "translation.bps"
output = tmp_path / "patched.zip"
_write_zip(source, {"Super Metroid.sfc": b"source"}, comment=b"archive comment")
patch.write_bytes(b"patch")
monkeypatch.setattr(
rom_patcher,
"_apply_binary_patch",
_fake_patcher(b"source", b"patched"),
)
validated = await apply_patch(source, patch, output)
assert validated is True
assert source.read_bytes() != output.read_bytes()
with zipfile.ZipFile(source) as archive:
assert archive.read("Super Metroid.sfc") == b"source"
with zipfile.ZipFile(output) as archive:
assert archive.comment == b"archive comment"
assert archive.namelist() == ["Super Metroid.sfc"]
assert archive.read("Super Metroid.sfc") == b"patched"
assert (
archive.getinfo("Super Metroid.sfc").compress_type == zipfile.ZIP_DEFLATED
)
assert archive.testzip() is None
@pytest.mark.asyncio
async def test_apply_patch_replaces_selected_member_and_preserves_others(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source = tmp_path / "game.zip"
patch = tmp_path / "translation.ips"
output = tmp_path / "patched.zip"
_write_zip(
source,
{
"docs/readme.txt": b"instructions",
"roms/game.smc": b"source",
},
)
patch.write_bytes(b"patch")
monkeypatch.setattr(
rom_patcher,
"_apply_binary_patch",
_fake_patcher(b"source", b"patched"),
)
await apply_patch(source, patch, output, "roms/game.smc")
with zipfile.ZipFile(output) as archive:
assert archive.namelist() == ["docs/readme.txt", "roms/game.smc"]
assert archive.read("docs/readme.txt") == b"instructions"
assert archive.read("roms/game.smc") == b"patched"
@pytest.mark.asyncio
async def test_apply_patch_requires_member_for_multi_file_zip(tmp_path: Path):
source = tmp_path / "game.zip"
_write_zip(source, {"game.sfc": b"source", "readme.txt": b"readme"})
with pytest.raises(PatcherInputError, match="Select which file"):
await apply_patch(source, tmp_path / "patch.bps", tmp_path / "patched.zip")
@pytest.mark.asyncio
async def test_apply_patch_rejects_missing_archive_member(tmp_path: Path):
source = tmp_path / "game.zip"
_write_zip(source, {"game.sfc": b"source", "readme.txt": b"readme"})
with pytest.raises(PatcherInputError, match="not found uniquely"):
await apply_patch(
source,
tmp_path / "patch.bps",
tmp_path / "patched.zip",
"missing.sfc",
)
@pytest.mark.asyncio
async def test_apply_patch_does_not_extract_member_paths(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source = tmp_path / "game.zip"
output = tmp_path / "patched.zip"
_write_zip(source, {"../../game.sfc": b"source", "readme.txt": b"readme"})
monkeypatch.setattr(
rom_patcher,
"_apply_binary_patch",
_fake_patcher(b"source", b"patched"),
)
await apply_patch(source, tmp_path / "patch.bps", output, "../../game.sfc")
assert not (tmp_path.parent / "game.sfc").exists()
with zipfile.ZipFile(output) as archive:
assert archive.read("../../game.sfc") == b"patched"
@pytest.mark.asyncio
async def test_apply_patch_rejects_corrupt_zip(tmp_path: Path):
source = tmp_path / "game.zip"
source.write_bytes(b"not a zip")
with pytest.raises(PatcherInputError, match="could not be read"):
await apply_patch(source, tmp_path / "patch.bps", tmp_path / "patched.zip")
@pytest.mark.asyncio
async def test_apply_patch_rejects_oversized_uncompressed_member(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source = tmp_path / "game.zip"
_write_zip(source, {"game.sfc": b"large"})
monkeypatch.setattr(rom_patcher, "ROM_PATCHER_MAX_FILE_SIZE_BYTES", 4)
with pytest.raises(PatcherInputError, match="uncompressed ROM is too large"):
await apply_patch(source, tmp_path / "patch.bps", tmp_path / "patched.zip")
@pytest.mark.asyncio
async def test_apply_patch_rejects_oversized_patched_member(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
source = tmp_path / "game.zip"
_write_zip(source, {"game.sfc": b"rom"})
monkeypatch.setattr(rom_patcher, "ROM_PATCHER_MAX_FILE_SIZE_BYTES", 4)
monkeypatch.setattr(
rom_patcher,
"_apply_binary_patch",
_fake_patcher(b"rom", b"large"),
)
with pytest.raises(PatcherInputError, match="patched ROM is too large"):
await apply_patch(source, tmp_path / "patch.bps", tmp_path / "patched.zip")
@pytest.mark.asyncio
async def test_apply_patch_rejects_encrypted_zip(tmp_path: Path):
source = tmp_path / "game.zip"
_write_zip(source, {"game.sfc": b"rom"})
data = bytearray(source.read_bytes())
for signature, flag_offset in ((b"PK\x03\x04", 6), (b"PK\x01\x02", 8)):
index = data.index(signature)
flags = int.from_bytes(
data[index + flag_offset : index + flag_offset + 2], "little"
)
data[index + flag_offset : index + flag_offset + 2] = (flags | 1).to_bytes(
2, "little"
)
source.write_bytes(data)
with pytest.raises(PatcherInputError, match="Encrypted"):
await apply_patch(source, tmp_path / "patch.bps", tmp_path / "patched.zip")
@pytest.mark.asyncio
async def test_apply_patch_rejects_unsupported_archive_format(tmp_path: Path):
with pytest.raises(PatcherInputError, match="not supported"):
await apply_patch(
tmp_path / "game.7z",
tmp_path / "patch.bps",
tmp_path / "patched.7z",
)

View File

@@ -2,6 +2,7 @@ from .patcher import (
PATCHER_SCRIPT,
SUPPORTED_PATCH_EXTENSIONS,
PatcherError,
PatcherInputError,
apply_patch,
)
@@ -9,5 +10,6 @@ __all__ = [
"PATCHER_SCRIPT",
"SUPPORTED_PATCH_EXTENSIONS",
"PatcherError",
"PatcherInputError",
"apply_patch",
]

View File

@@ -5,12 +5,22 @@ a patch file to a ROM file.
"""
import asyncio
import copy
import json
import shutil
import zipfile
import zlib
from pathlib import Path
from anyio import Path as AnyioPath
from config import (
ROM_PATCHER_MAX_CONCURRENCY,
ROM_PATCHER_MAX_FILE_SIZE_BYTES,
ROM_PATCHER_TIMEOUT,
)
from config import ROM_PATCHER_MAX_CONCURRENCY, ROM_PATCHER_TIMEOUT
from utils.filesystem import COMPRESSED_FILE_EXTENSIONS
from utils.zip_cache import ensure_zipfile_writable
PATCHER_SCRIPT = Path(__file__).parent / "patcher.js"
@@ -37,7 +47,120 @@ class PatcherError(Exception):
"""Raised when the Node.js patcher script fails or produces no output."""
async def apply_patch(rom_path: Path, patch_path: Path, output_path: Path) -> bool:
class PatcherInputError(PatcherError):
"""Raised when a ROM cannot be safely prepared for patching."""
def _extract_zip_member(
archive_path: Path, output_path: Path, member_name: str | None
) -> str:
try:
with zipfile.ZipFile(archive_path, "r") as archive:
members = [entry for entry in archive.infolist() if not entry.is_dir()]
if not members:
raise PatcherInputError("The ROM archive contains no files")
if member_name is None:
if len(members) != 1:
raise PatcherInputError(
"Select which file inside the ROM archive to patch"
)
selected = members[0]
else:
matches = [entry for entry in members if entry.filename == member_name]
if len(matches) != 1:
raise PatcherInputError(
"The selected file was not found uniquely in the ROM archive"
)
selected = matches[0]
if any(entry.flag_bits & 0x1 for entry in members):
raise PatcherInputError("Encrypted ROM archives are not supported")
if selected.file_size > ROM_PATCHER_MAX_FILE_SIZE_BYTES:
raise PatcherInputError(
"The uncompressed ROM is too large to patch "
f"({selected.file_size} bytes, max {ROM_PATCHER_MAX_FILE_SIZE_BYTES})"
)
if (
sum(entry.file_size for entry in members)
> ROM_PATCHER_MAX_FILE_SIZE_BYTES
):
raise PatcherInputError("The uncompressed ROM archive is too large")
with (
archive.open(selected, "r") as source,
output_path.open("wb") as output,
):
shutil.copyfileobj(source, output)
if output_path.stat().st_size > ROM_PATCHER_MAX_FILE_SIZE_BYTES:
output_path.unlink(missing_ok=True)
raise PatcherInputError("The uncompressed ROM is too large to patch")
return selected.filename
except PatcherInputError:
raise
except (
EOFError,
OSError,
RuntimeError,
NotImplementedError,
zipfile.BadZipFile,
zlib.error,
) as e:
raise PatcherInputError("The ROM archive could not be read") from e
def _rebuild_zip(
archive_path: Path,
output_path: Path,
patched_path: Path,
patched_member_name: str,
) -> None:
writable_compression = {
zipfile.ZIP_STORED,
zipfile.ZIP_DEFLATED,
zipfile.ZIP_BZIP2,
zipfile.ZIP_LZMA,
}
try:
ensure_zipfile_writable()
with (
zipfile.ZipFile(archive_path, "r") as source_archive,
zipfile.ZipFile(output_path, "w", allowZip64=True) as output_archive,
):
output_archive.comment = source_archive.comment
for source_entry in source_archive.infolist():
output_entry = copy.copy(source_entry)
if output_entry.compress_type not in writable_compression:
output_entry.compress_type = zipfile.ZIP_DEFLATED
if source_entry.is_dir():
output_archive.writestr(output_entry, b"")
continue
with output_archive.open(
output_entry, "w", force_zip64=True
) as output_file:
if source_entry.filename == patched_member_name:
with patched_path.open("rb") as patched_file:
shutil.copyfileobj(patched_file, output_file)
else:
with source_archive.open(source_entry, "r") as source_file:
shutil.copyfileobj(source_file, output_file)
except (
EOFError,
OSError,
RuntimeError,
NotImplementedError,
zipfile.BadZipFile,
zlib.error,
) as e:
output_path.unlink(missing_ok=True)
raise PatcherInputError("The patched ROM archive could not be created") from e
async def _apply_binary_patch(
rom_path: Path, patch_path: Path, output_path: Path
) -> bool:
"""Apply ``patch_path`` to ``rom_path`` and write the result to ``output_path``.
Returns whether the patch's embedded source checksum matched the ROM (always
@@ -61,7 +184,7 @@ async def apply_patch(rom_path: Path, patch_path: Path, output_path: Path) -> bo
stdout, stderr = await asyncio.wait_for(
proc.communicate(), timeout=ROM_PATCHER_TIMEOUT
)
except (asyncio.TimeoutError, TimeoutError) as e:
except TimeoutError as e:
proc.kill()
await proc.wait()
raise PatcherError(
@@ -73,7 +196,7 @@ async def apply_patch(rom_path: Path, patch_path: Path, output_path: Path) -> bo
try:
err_data = json.loads(stderr.decode())
message = err_data.get("error", message)
except (json.JSONDecodeError, UnicodeDecodeError):
except json.JSONDecodeError, UnicodeDecodeError:
if stderr:
message = stderr.decode(errors="replace").strip()
raise PatcherError(message)
@@ -85,5 +208,40 @@ async def apply_patch(rom_path: Path, patch_path: Path, output_path: Path) -> bo
try:
result = json.loads(stdout.decode())
return bool(result.get("validated", True))
except (json.JSONDecodeError, UnicodeDecodeError):
except json.JSONDecodeError, UnicodeDecodeError:
return True
async def apply_patch(
rom_path: Path,
patch_path: Path,
output_path: Path,
archive_member_name: str | None = None,
) -> bool:
"""Apply a patch to a raw ROM or to one member of a ZIP archive."""
extension = rom_path.suffix.lower()
if extension != ".zip":
if archive_member_name is not None:
raise PatcherInputError("Archive member selection requires a ZIP ROM")
if extension in COMPRESSED_FILE_EXTENSIONS:
raise PatcherInputError(
f"ROM archives in '{extension}' format are not supported for patching"
)
return await _apply_binary_patch(rom_path, patch_path, output_path)
extracted_path = output_path.parent / "source_rom"
member_name = await asyncio.to_thread(
_extract_zip_member, rom_path, extracted_path, archive_member_name
)
patched_path = output_path.parent / "patched_rom"
validated = await _apply_binary_patch(extracted_path, patch_path, patched_path)
patched_size = (await AnyioPath(patched_path).stat()).st_size
if patched_size > ROM_PATCHER_MAX_FILE_SIZE_BYTES:
raise PatcherInputError(
"The patched ROM is too large "
f"({patched_size} bytes, max {ROM_PATCHER_MAX_FILE_SIZE_BYTES})"
)
await asyncio.to_thread(
_rebuild_zip, rom_path, output_path, patched_path, member_name
)
return validated

View File

@@ -11,9 +11,12 @@ export type Body_patch_rom_api_roms__id__patch_post = {
* Custom output file name. If omitted, derived from ROM + patch names.
*/
output_file_name?: (string | null);
/**
* File inside a ZIP ROM archive to patch.
*/
archive_member_name?: (string | null);
/**
* A patch file uploaded from the client, applied without being stored in the library.
*/
patch_file?: (string | null);
};

View File

@@ -0,0 +1,144 @@
import { flushPromises, mount } from "@vue/test-utils";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DetailedRomSchema } from "@/__generated__";
import PatcherTab from "./PatcherTab.vue";
const { post } = vi.hoisted(() => ({ post: vi.fn() }));
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
}));
vi.mock("pinia", async (importOriginal) => ({
...(await importOriginal<typeof import("pinia")>()),
storeToRefs: (store: object) => store,
}));
vi.mock("@/services/api", () => ({ default: { post } }));
vi.mock("@/services/api/rom", () => ({
default: { uploadRoms: vi.fn() },
}));
vi.mock("@/services/socket", () => ({
default: { connected: true, connect: vi.fn(), emit: vi.fn() },
}));
vi.mock("@/stores/heartbeat", () => ({
default: () => ({ getEnabledMetadataOptions: () => [] }),
}));
vi.mock("@/stores/platforms", () => ({
default: () => ({ filteredPlatforms: { value: [] } }),
}));
vi.mock("@/stores/scanning", () => ({
default: () => ({ setScanning: vi.fn() }),
}));
vi.mock("@/stores/upload", () => ({
default: () => ({ reset: vi.fn() }),
}));
vi.mock("@/v2/composables/useCan", async () => {
const { ref } = await import("vue");
return { useCan: () => ref(false) };
});
vi.mock("@/v2/composables/useSnackbar", () => ({
useSnackbar: () => ({ success: vi.fn(), warning: vi.fn() }),
}));
const RSelect = {
props: {
modelValue: { type: String, default: "" },
items: { type: Array, default: () => [] },
},
emits: ["update:modelValue"],
template: `<select :value="modelValue" @change="$emit('update:modelValue', $event.target.value)"><option v-for="item in items" :key="item.name" :value="item.name">{{ item.name }}</option></select>`,
};
const RBtn = {
props: { disabled: { type: Boolean, default: false } },
emits: ["click"],
template: `<button :disabled="disabled" @click="$emit('click')"><slot /></button>`,
};
function rom(): DetailedRomSchema {
return {
id: 1,
name: "Super Metroid",
fs_name: "Super Metroid.zip",
platform_id: 2,
platform_slug: "snes",
platform_fs_slug: "snes",
platform_display_name: "Super Nintendo Entertainment System",
missing_from_fs: false,
files: [
{
id: 10,
category: "game",
file_name: "Super Metroid.zip",
file_size_bytes: 100,
archive_members: [
{
name: "docs/readme.txt",
size: 10,
crc_hash: "",
md5_hash: "",
sha1_hash: "",
},
{
name: "roms/Super Metroid.sfc",
size: 90,
crc_hash: "",
md5_hash: "",
sha1_hash: "",
},
],
},
{
id: 11,
category: "patch",
file_name: "translation.bps",
file_size_bytes: 10,
archive_members: null,
},
],
} as DetailedRomSchema;
}
describe("PatcherTab", () => {
beforeEach(() => {
vi.clearAllMocks();
post.mockResolvedValue({ data: new Blob(["patched"]), headers: {} });
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
});
it("sends the selected ZIP member when applying a patch", async () => {
const wrapper = mount(PatcherTab, {
props: { rom: rom() },
global: {
stubs: {
RAlert: true,
RBtn,
RCheckbox: true,
RDropzone: true,
RExpandTransition: { template: "<div><slot /></div>" },
RIcon: true,
RPlatformIcon: true,
RSelect,
RSliderBtnGroup: true,
RTextField: true,
RTooltip: true,
MissingFSBadge: true,
PlatformSelect: true,
},
},
});
const applyButton = wrapper.get("button");
expect(applyButton.attributes("disabled")).toBeDefined();
await wrapper.get("select").setValue("roms/Super Metroid.sfc");
expect(applyButton.attributes("disabled")).toBeUndefined();
await applyButton.trigger("click");
await flushPromises();
const request = post.mock.calls[0];
expect(request[0]).toBe("/roms/10/patch");
expect((request[1] as FormData).get("patch_file_id")).toBe("11");
expect((request[1] as FormData).get("archive_member_name")).toBe(
"roms/Super Metroid.sfc",
);
});
});

View File

@@ -68,8 +68,15 @@ function isPatchFile(file: RomFileSchema) {
);
}
function getZipMembers(file: RomFileSchema | null) {
return file && getExt(file.file_name) === ".zip"
? (file.archive_members ?? [])
: [];
}
const selectedRomFile = ref<RomFileSchema | null>(null);
const selectedPatchFile = ref<RomFileSchema | null>(null);
const selectedArchiveMemberName = ref<string | null>(null);
// The patch can come from the ROM's bundled files ("library") or be uploaded
// from disk ("upload") so users don't have to store patches until needed.
@@ -108,6 +115,7 @@ const baseFiles = computed(() =>
);
const patchFiles = computed(() => props.rom.files.filter(isPatchFile));
const hasLibraryPatches = computed(() => patchFiles.value.length > 0);
const archiveMembers = computed(() => getZipMembers(selectedRomFile.value));
const patchSourceItems = computed(() => [
{ id: "library" as const, label: t("common.library") },
@@ -159,6 +167,16 @@ watch(
{ immediate: true },
);
watch(
selectedRomFile,
(file) => {
const members = getZipMembers(file);
selectedArchiveMemberName.value =
members.length === 1 ? members[0].name : null;
},
{ immediate: true },
);
function onPatchFiles(files: File[]) {
uploadedPatch.value = files[0] ?? null;
}
@@ -226,6 +244,9 @@ async function patchRom() {
if (customFileName.value) {
form.append("output_file_name", customFileName.value);
}
if (selectedArchiveMemberName.value) {
form.append("archive_member_name", selectedArchiveMemberName.value);
}
const response = await api.post(
`/roms/${selectedRomFile.value.id}/patch`,
@@ -325,6 +346,7 @@ async function uploadPatchedFile(file: File, platformId: number) {
const canApply = computed(
() =>
!!selectedRomFile.value &&
(archiveMembers.value.length <= 1 || !!selectedArchiveMemberName.value) &&
hasPatch.value &&
!applying.value &&
(downloadLocally.value || saveIntoRomM.value) &&
@@ -427,6 +449,27 @@ const applyLabel = computed(() => {
</span>
</div>
<RSelect
v-if="archiveMembers.length > 1"
v-model="selectedArchiveMemberName"
:items="archiveMembers"
item-title="name"
item-value="name"
:label="t('patcher.select-file')"
variant="outlined"
density="comfortable"
hide-details
>
<template #item="{ props: itemProps, item }">
<li v-bind="itemProps" class="r-v2-patch__file-row">
<span class="r-select__item-title">{{ item.raw.name }}</span>
<span class="r-v2-patch__file-size">
{{ formatBytes(item.raw.size) }}
</span>
</li>
</template>
</RSelect>
<p v-if="baseFiles.length === 0" class="r-v2-patch__warn">
{{ t("patcher.no-files") }}
</p>