diff --git a/.claude/skills/pr-ready/SKILL.md b/.claude/skills/pr-ready/SKILL.md index 8c97d1fb6..94ee44d49 100644 --- a/.claude/skills/pr-ready/SKILL.md +++ b/.claude/skills/pr-ready/SKILL.md @@ -86,5 +86,9 @@ Finish with one consolidated summary rather than four transcripts: the security verdict, what steps 2 and 3 changed by area, which checks ran and their results, and anything still needing a human decision. +The summary also carries what the PR description needs and the transcripts hold: the +screenshots step 4 captured, as paths the user can drag into the `Screenshots` section, +and the `mermaid` block for a change that moved a boundary. + Four passes in one session is a lot of context. For a very large diff, run the steps in separate sessions against the same `$RANGE`. diff --git a/.claude/skills/review-polish/SKILL.md b/.claude/skills/review-polish/SKILL.md index 18da72963..e47e434a2 100644 --- a/.claude/skills/review-polish/SKILL.md +++ b/.claude/skills/review-polish/SKILL.md @@ -1,6 +1,6 @@ --- name: review-polish -description: The before-review and before-handoff pass for RomM, covering both stacks. First shapes the code the checks can't see — comment and docstring discipline (the single most-corrected thing in this repo), duplicated constants/types/getters, imprecise names, loose typing in tests. Then runs the verification gate that keeps CI green — frontend (typecheck/lint/test/build/i18n/tokens), backend (pytest/alembic/trunk), the OpenAPI regen step, and (for UI) manual browser/theme/input/Storybook checks. Use after the code works, right before committing, opening a PR, or telling the user a change is done. +description: The before-review and before-handoff pass for RomM, covering both stacks. First shapes the code the checks can't see — comment and docstring discipline (the single most-corrected thing in this repo), duplicated constants/types/getters, imprecise names, loose typing in tests. Then runs the verification gate that keeps CI green — frontend (typecheck/lint/test/build/i18n/tokens), backend (pytest/alembic/trunk), the OpenAPI regen step, and (for UI) manual browser/theme/input/Storybook checks. Ends with what the PR description owes a reviewer: screenshots of a UI change, a mermaid diagram of an architectural one. Use after the code works, right before committing, opening a PR, or telling the user a change is done. --- # RomM: Review Polish & Verification @@ -163,6 +163,10 @@ With `uiVersion = "v2"`: - **Responsive sweep:** 320px → 4K across the `useBreakpoint` tiers; overlays full-bleed on `xs`. - **Accessibility:** contrast, keyboard reachability with no traps, aria-labels on icon-only controls. - **Performance:** lists/grids of 1000+ items stay smooth; every `v-for` has a stable `:key`. +- **Screenshots:** capture the change while you're in there, at least one and enough to + convey what's different. Shoot the component or view in its real surroundings, not a + full-page dump, and save to a temp dir outside the repo. + See [F. The PR description](#f-the-pr-description). #### Storybook (for `/lib`) @@ -186,11 +190,67 @@ Run from `backend/`: ### Don't - Open a PR without manually testing the UI when UI was touched. +- Open a PR on a UI change with an empty `Screenshots` section. +- Describe a boundary change in prose alone when a diagram would land it in one read. - `--no-verify` on commits. - Leave a locale key English-only, a token un-generated, or a migration one-directional. --- +## F. The PR description + +Base it on `.github/PULL_REQUEST_TEMPLATE.md`, and carry the two things a reviewer cannot +reconstruct from the diff. + +### Screenshots, for a UI change + +The template's `Screenshots (if applicable)` heading is not optional for a UI change; a reviewer +who can't see the change reviews the diff instead of the result. Shoot enough to give that +reviewer the gist, and stop there: one shot carries most changes. + +- **Before/after** when the change alters something that already existed and the after alone + wouldn't read as different, labelled as such. +- **A second theme** only when the change is theme-dependent; a state or breakpoint only when it's + the point of the change. +- Name the files for what they show (`missing-games-actions.png`), so the handoff list reads on + its own. + +Attachments on github.com live under `user-attachments`, and nothing uploads there from the CLI. +So unless you have a URL the PR body can point at, open the PR with the heading and a one-line +placeholder naming each shot, then give the user the file paths in your summary to drag into the +description. Never commit the images or push them to a branch to get a URL. + +### Mermaid diagram, for an architectural change + +GitHub renders a fenced `mermaid` block in a PR body, so a change that moves a boundary gets one: +a new service, handler, or task in a request or job path; a model or relationship change; a new +external provider or integration; a different call path across layers; an auth, session, or socket +flow. Code that changes inside an existing boundary does not. + +- **Draw what changed**, with the new pieces distinguishable from what was already there. A + diagram that redraws the whole backend teaches nothing. +- **Pick the type for the question:** `flowchart` for a call or data path, `sequenceDiagram` for an + exchange whose order over time is the point (auth handshake, scan lifecycle), `erDiagram` for + models and their relationships. +- **Label the edges** with what crosses them, the call, the payload, the event name, not "uses". +- **No custom colors or styling.** The default theme is the one that reads in both of GitHub's. +- **Make sure it parses.** An unparseable block renders as raw text in the description. When the + syntax isn't one you're sure of, render it first: + `npx -y @mermaid-js/mermaid-cli -i d.mmd -o d.svg -p pc.json`, where `pc.json` is + `{"executablePath": "", "args": ["--no-sandbox"]}` (puppeteer downloads no + browser of its own here). + +```mermaid +flowchart LR + client[Web client] -->|POST /api/roms/scan| api[roms endpoint] + api -->|enqueue| queue[(RQ queue)] + queue --> worker[scan task] + worker -->|emit scan:done| socket[Socket.IO] + socket --> client +``` + +--- + ## Checklist - [ ] No comment or docstring over two lines of prose; no change history, no @@ -202,4 +262,7 @@ Run from `backend/`: pytest, migrations both directions, OpenAPI regen) - [ ] UI changes tested in the browser: both themes, all four input modalities, responsive sweep +- [ ] UI changes screenshotted (enough to convey the change), and the shots + attached to the PR or handed to the user +- [ ] Architectural changes carry a `mermaid` diagram in the PR description - [ ] `trunk fmt && trunk check` clean, with whatever fmt rewrote committed diff --git a/CLAUDE.md b/CLAUDE.md index faceaf031..f058e8820 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -72,6 +72,8 @@ These live in `.claude/skills/` and carry the detailed rules. Invoke the one tha **Python tools live in `backend/tools/`.** Standalone dev/test utilities and scripts (not part of the app runtime) go in `backend/tools/`, not scattered across `backend/`. **Link PRs to issues.** In the PR description, use `Fixes #XXXX` for issue/bug fixes and `Closes #XXXX` for feature implementations. **Use the PR template.** Base every PR description on `.github/PULL_REQUEST_TEMPLATE.md`. +**Show UI changes in the PR.** A PR that touches anything visible ships with at least one screenshot under the template's `Screenshots` heading, captured from the running app during the `review-polish` browser pass. Enough shots to convey what changed, not a catalogue of every state. Save the files outside the repo and never commit them. If you can't attach them to the PR yourself, open the PR with the section in place and hand the user the file paths to drop in. +**Diagram architectural changes in the PR.** When a change moves a boundary (a new service, task, or provider in a path, a model relationship, a different call path across layers, an auth or socket flow), the PR description carries a `mermaid` block showing it. GitHub renders them. Draw what changed, not the whole system. See `review-polish`. --- diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index fcc3d916f..0712adc68 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -126,6 +126,27 @@ cd backend uv run python3 main.py ``` +#### - Run the task workers + +A manual task run is refused, and a scheduled job stays queued, until an RQ worker listens on its queue; scans have a worker of their own. Each command is a foreground process, so run them in separate terminals. `-c config` reads the Redis connection from the same `REDIS_*` settings in `.env` the backend uses. + +```sh +cd backend +uv run rq worker -c config --worker-class handler.rq_worker.RomMWorker --with-scheduler high default low +``` + +```sh +cd backend +uv run rq worker -c config --worker-class handler.rq_worker.RomMWorker --with-scheduler scans +``` + +`--with-scheduler` releases delayed jobs, such as the rescans the filesystem watcher waits out, so each worker needs it. The recurring schedule is registered by the RQ cron process, which the workers then execute: + +```sh +cd backend +uv run rq cron -c config tasks.cron_config +``` + ### Setting up the frontend #### - Install node.js dependencies diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index ce6714425..c29fecfb4 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -756,7 +756,7 @@ class ConfigManager: self._raw_config, "emulatorjs.disable_batch_bootup", False ), EJS_ENABLE_AUTO_SAVE_SYNC=pydash.get( - self._raw_config, "emulatorjs.auto_save_sync", False + self._raw_config, "emulatorjs.auto_save_sync", True ), EJS_NETPLAY_ENABLED=pydash.get( self._raw_config, "emulatorjs.netplay.enabled", False diff --git a/backend/endpoints/responses/__init__.py b/backend/endpoints/responses/__init__.py index b225d6f89..6f1fa89c2 100644 --- a/backend/endpoints/responses/__init__.py +++ b/backend/endpoints/responses/__init__.py @@ -53,13 +53,24 @@ class OrphanedResourcesCleanupStats(TypedDict): class MissingRomsCleanupStats(TypedDict): - platform_id: int | None + platform_ids: list[int] | None roms_found: int roms_deleted: int errors: int -CleanupStats = Union[OrphanedResourcesCleanupStats, MissingRomsCleanupStats] +class MissingFirmwareCleanupStats(TypedDict): + platform_ids: list[int] | None + firmware_found: int + firmware_deleted: int + errors: int + + +CleanupStats = Union[ + OrphanedResourcesCleanupStats, + MissingRomsCleanupStats, + MissingFirmwareCleanupStats, +] class CleanupTaskMeta(TypedDict): diff --git a/backend/endpoints/roms/manual.py b/backend/endpoints/roms/manual.py index 62d5b071b..916cbb45d 100644 --- a/backend/endpoints/roms/manual.py +++ b/backend/endpoints/roms/manual.py @@ -10,24 +10,22 @@ from streaming_form_data import StreamingFormDataParser from streaming_form_data.targets import FileTarget, NullTarget from decorators.auth import protected_route +from endpoints.roms.upload import receive_rom_file from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException -from exceptions.fs_exceptions import RomAlreadyExistsException from handler.auth.constants import Scope from handler.auth.dependencies import assert_rom_visible from handler.database import db_rom_handler from handler.filesystem import fs_resource_handler, fs_rom_handler from handler.filesystem.resources_handler import ALLOWED_MANUAL_EXTENSIONS -from handler.rom_conversion import promote_single_file_to_folder +from handler.rom_upload import CATEGORY_UPLOAD_FOLDERS from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log -from models.rom import RomFile, RomFileCategory +from models.rom import RomFileCategory from utils.router import APIRouter router = APIRouter() -MANUAL_FOLDER = "manual" - def _is_allowed_manual_file(file_name: str) -> bool: _, ext = os.path.splitext(file_name) @@ -209,7 +207,7 @@ async def add_rom_manual_file( ), ], ) -> Response: - """Upload a manual PDF into the ROM's own manual/ subfolder.""" + """Upload a manual document into the ROM's own manual/ subfolder.""" rom = db_rom_handler.get_rom(id) if not rom: @@ -217,92 +215,9 @@ async def add_rom_manual_file( assert_rom_visible(request, rom) - if rom.has_simple_single_file: - try: - rom = await promote_single_file_to_folder(rom) - except RomAlreadyExistsException as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, detail=str(exc) - ) from exc - - try: - safe_filename = fs_rom_handler._sanitize_filename(filename) - except ValueError as exc: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload filename: {exc}", - ) from exc - - if safe_filename != filename: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload filename must be a plain file name, not a path", - ) - - if not _is_allowed_manual_file(safe_filename): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=( - f"Unsupported manual file type. Allowed: " - f"{', '.join(sorted(ALLOWED_MANUAL_EXTENSIONS))}" - ), - ) - - manual_dir_rel = f"{rom.full_path}/{MANUAL_FOLDER}" - file_rel_path = f"{manual_dir_rel}/{safe_filename}" - file_location = fs_rom_handler.validate_path(file_rel_path) - log.info(f"Uploading manual file to {hl(str(file_location))}") - - await fs_rom_handler.make_directory(manual_dir_rel) - - parser = StreamingFormDataParser(headers=request.headers) - parser.register("x-upload-platform", NullTarget()) - parser.register(safe_filename, FileTarget(str(file_location))) - - def cleanup_partial_file(): - if file_location.exists(): - file_location.unlink() - - try: - async for chunk in request.stream(): - parser.data_received(chunk) - except ClientDisconnect: - log.error("Client disconnected during upload") - cleanup_partial_file() - raise - except Exception as exc: - log.error("Error uploading manual file", exc_info=exc) - cleanup_partial_file() - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="There was an error uploading the manual file", - ) from exc - - stat = os.stat(file_location) - existing = db_rom_handler.get_rom_file_by_path( - rom_id=rom.id, file_path=manual_dir_rel, file_name=safe_filename + await receive_rom_file( + request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.MANUAL], filename ) - if existing: - db_rom_handler.update_rom_file( - existing.id, - { - "file_size_bytes": stat.st_size, - "last_modified": stat.st_mtime, - "category": RomFileCategory.MANUAL, - "missing_from_fs": False, - }, - ) - else: - db_rom_handler.add_rom_file( - RomFile( - rom_id=rom.id, - file_name=safe_filename, - file_path=manual_dir_rel, - file_size_bytes=stat.st_size, - last_modified=stat.st_mtime, - category=RomFileCategory.MANUAL, - ) - ) return Response(status_code=status.HTTP_201_CREATED) diff --git a/backend/endpoints/roms/screenshot.py b/backend/endpoints/roms/screenshot.py index 6228446ac..996f3c125 100644 --- a/backend/endpoints/roms/screenshot.py +++ b/backend/endpoints/roms/screenshot.py @@ -1,36 +1,26 @@ -import os from typing import Annotated from fastapi import Header, HTTPException from fastapi import Path as PathVar from fastapi import Request, status from fastapi.responses import Response -from starlette.requests import ClientDisconnect -from streaming_form_data import StreamingFormDataParser -from streaming_form_data.targets import FileTarget, NullTarget from decorators.auth import protected_route +from endpoints.roms.upload import receive_rom_file from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException -from exceptions.fs_exceptions import RomAlreadyExistsException from handler.auth.constants import Scope from handler.auth.dependencies import assert_rom_visible from handler.database import db_rom_handler from handler.filesystem import fs_rom_handler -from handler.rom_conversion import promote_single_file_to_folder +from handler.rom_upload import CATEGORY_UPLOAD_FOLDERS from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log -from models.rom import RomFile, RomFileCategory -from utils.media_types import ( - ALLOWED_IMAGE_EXTENSIONS, - is_allowed_image_file, -) +from models.rom import RomFileCategory from utils.router import APIRouter router = APIRouter() -SCREENSHOT_FOLDER = "screenshots" - @protected_route( router.post, @@ -50,7 +40,7 @@ async def add_rom_screenshots( ), ], ) -> Response: - """Upload a screenshot image for a multi-file ROM.""" + """Upload a screenshot image into the ROM's screenshots/ subfolder.""" rom = db_rom_handler.get_rom(id) if not rom: @@ -58,94 +48,9 @@ async def add_rom_screenshots( assert_rom_visible(request, rom) - if rom.has_simple_single_file: - try: - rom = await promote_single_file_to_folder(rom) - except RomAlreadyExistsException as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, detail=str(exc) - ) from exc - - try: - safe_filename = fs_rom_handler._sanitize_filename(filename) - except ValueError as exc: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload filename: {exc}", - ) from exc - - # Reject rather than silently strip — otherwise the client's form-field - # name won't match what we register with the parser below. - if safe_filename != filename: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload filename must be a plain file name, not a path", - ) - - if not is_allowed_image_file(safe_filename): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=( - f"Unsupported image file type. Allowed: " - f"{', '.join(sorted(ALLOWED_IMAGE_EXTENSIONS))}" - ), - ) - - screenshot_dir_rel = f"{rom.full_path}/{SCREENSHOT_FOLDER}" - file_rel_path = f"{screenshot_dir_rel}/{safe_filename}" - file_location = fs_rom_handler.validate_path(file_rel_path) - log.info(f"Uploading screenshot to {hl(str(file_location))}") - - await fs_rom_handler.make_directory(screenshot_dir_rel) - - parser = StreamingFormDataParser(headers=request.headers) - parser.register("x-upload-platform", NullTarget()) - parser.register(safe_filename, FileTarget(str(file_location))) - - def cleanup_partial_file(): - if file_location.exists(): - file_location.unlink() - - try: - async for chunk in request.stream(): - parser.data_received(chunk) - except ClientDisconnect: - log.error("Client disconnected during upload") - cleanup_partial_file() - raise - except Exception as exc: - log.error("Error uploading screenshot", exc_info=exc) - cleanup_partial_file() - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="There was an error uploading the screenshot", - ) from exc - - stat = os.stat(file_location) - existing = db_rom_handler.get_rom_file_by_path( - rom_id=rom.id, file_path=screenshot_dir_rel, file_name=safe_filename + await receive_rom_file( + request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.SCREENSHOT], filename ) - if existing: - db_rom_handler.update_rom_file( - existing.id, - { - "file_size_bytes": stat.st_size, - "last_modified": stat.st_mtime, - "category": RomFileCategory.SCREENSHOT, - "missing_from_fs": False, - }, - ) - else: - db_rom_handler.add_rom_file( - RomFile( - rom_id=rom.id, - file_name=safe_filename, - file_path=screenshot_dir_rel, - file_size_bytes=stat.st_size, - last_modified=stat.st_mtime, - category=RomFileCategory.SCREENSHOT, - ) - ) return Response(status_code=status.HTTP_201_CREATED) diff --git a/backend/endpoints/roms/soundtrack.py b/backend/endpoints/roms/soundtrack.py index 6976ec254..69ae52757 100644 --- a/backend/endpoints/roms/soundtrack.py +++ b/backend/endpoints/roms/soundtrack.py @@ -1,41 +1,28 @@ -import os from typing import Annotated from fastapi import Header, HTTPException from fastapi import Path as PathVar from fastapi import Request, status from fastapi.responses import Response -from starlette.requests import ClientDisconnect -from streaming_form_data import StreamingFormDataParser -from streaming_form_data.targets import FileTarget, NullTarget from decorators.auth import protected_route from endpoints.responses.rom import SoundtrackTrackMetaSchema, TrackMetaSchema +from endpoints.roms.upload import receive_rom_file from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException -from exceptions.fs_exceptions import RomAlreadyExistsException from handler.auth.constants import Scope from handler.auth.dependencies import assert_rom_visible from handler.database import db_rom_handler from handler.filesystem import fs_rom_handler -from handler.rom_conversion import promote_single_file_to_folder +from handler.rom_upload import CATEGORY_UPLOAD_FOLDERS from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log -from models.rom import RomFile, RomFileCategory, TrackMeta -from utils.audio_tags import ( - ALLOWED_AUDIO_EXTENSIONS, - extract_audio_meta, - is_allowed_audio_file, - persist_embedded_cover, - remove_persisted_cover, - track_meta_columns, -) +from models.rom import RomFileCategory +from utils.audio_tags import remove_persisted_cover from utils.router import APIRouter router = APIRouter() -SOUNDTRACK_FOLDER = "soundtrack" - @protected_route( router.get, @@ -90,7 +77,7 @@ async def add_rom_soundtracks( ), ], ) -> Response: - """Upload a soundtrack audio file for a multi-file ROM.""" + """Upload a soundtrack audio file into the ROM's soundtrack/ subfolder.""" rom = db_rom_handler.get_rom(id) if not rom: @@ -98,121 +85,9 @@ async def add_rom_soundtracks( assert_rom_visible(request, rom) - if rom.has_simple_single_file: - try: - rom = await promote_single_file_to_folder(rom) - except RomAlreadyExistsException as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, detail=str(exc) - ) from exc - - try: - safe_filename = fs_rom_handler._sanitize_filename(filename) - except ValueError as exc: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload filename: {exc}", - ) from exc - - # Reject rather than silently strip — otherwise the client's form-field - # name won't match what we register with the parser below. - if safe_filename != filename: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload filename must be a plain file name, not a path", - ) - - if not is_allowed_audio_file(safe_filename): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=( - f"Unsupported audio file type. Allowed: " - f"{', '.join(sorted(ALLOWED_AUDIO_EXTENSIONS))}" - ), - ) - - soundtrack_dir_rel = f"{rom.full_path}/{SOUNDTRACK_FOLDER}" - file_rel_path = f"{soundtrack_dir_rel}/{safe_filename}" - file_location = fs_rom_handler.validate_path(file_rel_path) - log.info(f"Uploading soundtrack to {hl(str(file_location))}") - - await fs_rom_handler.make_directory(soundtrack_dir_rel) - - parser = StreamingFormDataParser(headers=request.headers) - parser.register("x-upload-platform", NullTarget()) - parser.register(safe_filename, FileTarget(str(file_location))) - - def cleanup_partial_file(): - if file_location.exists(): - file_location.unlink() - - try: - async for chunk in request.stream(): - parser.data_received(chunk) - except ClientDisconnect: - log.error("Client disconnected during upload") - cleanup_partial_file() - raise - except Exception as exc: - log.error("Error uploading soundtrack", exc_info=exc) - cleanup_partial_file() - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="There was an error uploading the soundtrack", - ) from exc - - stat = os.stat(file_location) - audio_meta = extract_audio_meta(str(file_location)) - cols = track_meta_columns(audio_meta) if audio_meta else None - existing = db_rom_handler.get_rom_file_by_path( - rom_id=rom.id, file_path=soundtrack_dir_rel, file_name=safe_filename + await receive_rom_file( + request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.SOUNDTRACK], filename ) - if existing: - # Reuploading: drop stale cover first so a new id-based path can replace it. - if existing.track_meta and existing.track_meta.cover_path: - remove_persisted_cover(existing.track_meta.cover_path) - saved = db_rom_handler.update_rom_file( - existing.id, - { - "file_size_bytes": stat.st_size, - "last_modified": stat.st_mtime, - "category": RomFileCategory.SOUNDTRACK, - "missing_from_fs": False, - }, - ) - if cols: - db_rom_handler.upsert_track_meta(existing.id, rom.id, cols) - else: - db_rom_handler.delete_track_meta(existing.id) - else: - saved = db_rom_handler.add_rom_file( - RomFile( - rom_id=rom.id, - file_name=safe_filename, - file_path=soundtrack_dir_rel, - file_size_bytes=stat.st_size, - last_modified=stat.st_mtime, - category=RomFileCategory.SOUNDTRACK, - track_meta=(TrackMeta(rom_id=rom.id, **cols) if cols else None), - ) - ) - - if saved and audio_meta and audio_meta.get("has_embedded_cover"): - cover_path = persist_embedded_cover( - audio_full_path=str(file_location), - platform_id=rom.platform_id, - rom_id=rom.id, - file_id=saved.id, - ) - if cover_path: - db_rom_handler.upsert_track_meta( - saved.id, rom.id, {"cover_path": cover_path} - ) - else: - log.error(f"[audio_tags] cover persist failed for {file_location}") - db_rom_handler.upsert_track_meta( - saved.id, rom.id, {"has_embedded_cover": False} - ) return Response(status_code=status.HTTP_201_CREATED) diff --git a/backend/endpoints/roms/upload.py b/backend/endpoints/roms/upload.py index 8228e6a27..58c09c83c 100644 --- a/backend/endpoints/roms/upload.py +++ b/backend/endpoints/roms/upload.py @@ -1,20 +1,19 @@ import json -import os import shutil from pathlib import Path from typing import Annotated from uuid import UUID, uuid4 +from anyio import Path as AsyncPath from anyio import open_file from fastapi import Header, HTTPException, Request, status from pydantic import BaseModel, Field +from starlette.requests import ClientDisconnect from starlette.responses import Response +from streaming_form_data import StreamingFormDataParser +from streaming_form_data.targets import FileTarget, NullTarget -from config import ( - ROM_UPLOAD_ASSEMBLING_EXT, - ROM_UPLOAD_TMP_BASE, - ROM_UPLOAD_TTL, -) +from config import ROM_UPLOAD_TMP_BASE, ROM_UPLOAD_TTL from decorators.auth import protected_route from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException from exceptions.fs_exceptions import RomAlreadyExistsException @@ -23,10 +22,20 @@ from handler.auth.dependencies import assert_rom_visible from handler.database import db_platform_handler, db_rom_handler from handler.filesystem import fs_rom_handler from handler.redis_handler import async_cache -from handler.rom_conversion import promote_single_file_to_folder -from handler.rom_files import refresh_rom_files +from handler.rom_upload import ( + UploadConflictException, + UploadDestination, + UploadNotRegisteredException, + UploadRejectedException, + commit_upload, + parse_upload_folder, + prepare_upload_destination, + resolve_upload_destination, + sanitize_upload_filename, + staging_path, +) from logger.logger import log -from models.rom import Rom +from models.rom import Rom, RomFile from utils.router import APIRouter router = APIRouter( @@ -101,46 +110,11 @@ async def _cleanup_upload_state(upload_id: str) -> None: def _sanitized_filename(filename: str) -> str: try: - safe_filename = fs_rom_handler._sanitize_filename(filename) - except ValueError as exc: + return sanitize_upload_filename(filename) + except UploadRejectedException as exc: raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload filename: {exc}", + status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc) ) from exc - if safe_filename != filename: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload filename must be a plain file name, not a path", - ) - return safe_filename - - -def _parse_upload_folder(folder: str) -> str: - """Normalize the target subfolder to a relative path made of plain names.""" - raw = folder.strip() - if raw.startswith("/") or "\\" in raw: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload folder must be a relative, forward-slashed path", - ) - raw = raw.rstrip("/") - if not raw: - return "" - segments = raw.split("/") - for segment in segments: - try: - safe_segment = fs_rom_handler._sanitize_filename(segment) - except ValueError as exc: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload folder: {exc}", - ) from exc - if safe_segment != segment: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload folder must be a relative path inside the game folder", - ) - return "/".join(segments) def _get_upload_rom(request: Request, rom_id: int, platform_id: int) -> Rom: @@ -156,94 +130,125 @@ def _get_upload_rom(request: Request, rom_id: int, platform_id: int) -> Rom: return rom -def _free_rom_destination(rom: Rom, folder: str, filename: str) -> tuple[str, Path]: - """The library-relative directory and absolute file path of an upload into a - ROM, kept inside the folder a lone file gets promoted into and refused when - a file of that name is already there (or will be, once promoted).""" - root = ( - f"{rom.fs_path}/{rom.fs_name_no_ext}" - if rom.has_simple_single_file - else rom.full_path - ) - rel_dir = f"{root}/{folder}" if folder else root +async def _prepare_rom_destination( + rom: Rom, folder: str, filename: str, *, overwrite: bool +) -> UploadDestination: try: - root_location = fs_rom_handler.validate_path(root) - location = fs_rom_handler.validate_path(f"{rel_dir}/{filename}") - except ValueError as exc: + return await prepare_upload_destination( + rom, folder, filename, overwrite=overwrite + ) + except UploadRejectedException as exc: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc) ) from exc - if not location.is_relative_to(root_location): + except (UploadConflictException, RomAlreadyExistsException) as exc: raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload destination must be inside the game folder", - ) - - promoted_over_itself = ( - rom.has_simple_single_file and not folder and filename == rom.fs_name - ) - if location.exists() or promoted_over_itself: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"File {filename} already exists in the game folder", - ) - return rel_dir, location - - -def _claim_destination(location: Path) -> None: - """Create the final path exclusively, so two completions racing for the - same name cannot overwrite each other's bytes.""" - try: - os.close(os.open(location, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)) - except FileExistsError as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"File {location.name} already exists", + status_code=status.HTTP_409_CONFLICT, detail=str(exc) ) from exc -async def _resolve_destination( - request: Request, session: dict -) -> tuple[str, Path, Rom | None]: - """Where a completed upload lands: the directory to create, the file path, - and the ROM it belongs to when it targets one.""" +async def _commit( + destination: UploadDestination, staged: Path, *, overwrite: bool +) -> RomFile | None: + try: + return await commit_upload(destination, staged, overwrite=overwrite) + except UploadConflictException as exc: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, detail=str(exc) + ) from exc + except UploadNotRegisteredException as exc: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc) + ) from exc + + +async def receive_rom_file( + request: Request, rom: Rom, folder: str, filename: str +) -> RomFile | None: + """Stream a single-file multipart body into a subfolder of the ROM and + register it the way a chunked upload is, replacing a file of the same name. + + Returns: + The registered file row, or None when the scanner did not list it. + """ + safe_filename = _sanitized_filename(filename) + destination = await _prepare_rom_destination( + rom, folder, safe_filename, overwrite=True + ) + staged = staging_path(destination.location) + log.info(f"Uploading {safe_filename} to {destination.location}") + + parser = StreamingFormDataParser(headers=request.headers) + parser.register("x-upload-platform", NullTarget()) + parser.register(safe_filename, FileTarget(str(staged))) + try: + async for chunk in request.stream(): + parser.data_received(chunk) + except ClientDisconnect: + log.error("Client disconnected during upload") + await AsyncPath(staged).unlink(missing_ok=True) + raise + except Exception as exc: + log.error(f"Error uploading {safe_filename}", exc_info=exc) + await AsyncPath(staged).unlink(missing_ok=True) + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="There was an error uploading the file", + ) from exc + + # The parser only writes the part whose field name matches the header, so + # a body naming the file differently leaves nothing behind. + if not await AsyncPath(staged).exists(): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"The upload body has no file part named {safe_filename}", + ) + + return await _commit(destination, staged, overwrite=True) + + +async def _resolve_destination(request: Request, session: dict) -> UploadDestination: + """Where a completed upload lands, with its directory created.""" filename = session["filename"] rom_id = session.get("rom_id") if rom_id is None: try: roms_path = fs_rom_handler.get_roms_upload_path(session["platform_fs_slug"]) - return ( - roms_path, - fs_rom_handler.validate_path(f"{roms_path}/{filename}"), - None, - ) + location = fs_rom_handler.validate_path(f"{roms_path}/{filename}") except ValueError as exc: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc) ) from exc + await fs_rom_handler.make_directory(roms_path) + return UploadDestination(rom=None, rel_dir=roms_path, location=location) rom = _get_upload_rom(request, rom_id, session["platform_id"]) - folder = session["folder"] - rel_dir, location = _free_rom_destination(rom, folder, filename) - if rom.has_simple_single_file: - try: - rom = await promote_single_file_to_folder(rom) - except RomAlreadyExistsException as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, detail=str(exc) - ) from exc - return rel_dir, location, rom + return await _prepare_rom_destination( + rom, session["folder"], filename, overwrite=session["overwrite"] + ) class UploadTargetPayload(BaseModel): """Optional body of `/start`: upload into a ROM's folder instead of the - platform folder.""" + platform folder, and name the file where the header cannot.""" - rom_id: int = Field(ge=1) + rom_id: int | None = Field( + default=None, + ge=1, + description="Upload into this ROM's folder instead of the platform folder.", + ) folder: str = Field( default="", description="Subfolder inside the ROM's folder, relative and forward-slashed. Empty for the root.", ) + filename: str | None = Field( + default=None, + description="The file name. Takes precedence over the header, which cannot carry characters outside Latin-1.", + ) + overwrite: bool = Field( + default=False, + description="Replace a file of the same name in the ROM's folder instead of refusing the upload.", + ) @protected_route( @@ -282,10 +287,14 @@ async def start_chunked_upload( ) platform_fs_slug = db_platform.fs_slug + if target and target.filename is not None: + filename = target.filename safe_filename = _sanitized_filename(filename) + rom_id = target.rom_id if target else None + overwrite = bool(target and target.overwrite and rom_id is not None) rel_folder = "" - if target is None: + if rom_id is None: try: roms_path = fs_rom_handler.get_roms_upload_path(platform_fs_slug) except ValueError as exc: @@ -298,14 +307,20 @@ async def start_chunked_upload( detail=f"File {filename} already exists", ) else: - rom = _get_upload_rom(request, target.rom_id, platform_id) - rel_folder = _parse_upload_folder(target.folder) - if fs_rom_handler.is_excluded_multi_part(safe_filename): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"File {filename} would be ignored by the scanner", + rom = _get_upload_rom(request, rom_id, platform_id) + try: + rel_folder = parse_upload_folder(target.folder if target else "") + resolve_upload_destination( + rom, rel_folder, safe_filename, overwrite=overwrite ) - _free_rom_destination(rom, rel_folder, safe_filename) + except UploadRejectedException as exc: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc) + ) from exc + except UploadConflictException as exc: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, detail=str(exc) + ) from exc upload_id = str(uuid4()) tmp_dir = ROM_UPLOAD_TMP_BASE / upload_id @@ -319,13 +334,14 @@ async def start_chunked_upload( "total_chunks": total_chunks, "total_size": total_size, "user_id": request.user.id, - "rom_id": target.rom_id if target else None, + "rom_id": rom_id, "folder": rel_folder, + "overwrite": overwrite, } await _save_session(upload_id, session) log.info( - f"Started chunked upload session {upload_id} for {filename} " + f"Started chunked upload session {upload_id} for {safe_filename} " f"({total_chunks} chunks, {total_size} bytes)" ) @@ -419,6 +435,42 @@ async def upload_chunk( return {"received": received_count, "total": session["total_chunks"]} +async def _assemble_chunks(upload_id: str, session: dict, staged: Path) -> None: + """Concatenate the received chunks into the staged file, dropping it on + any failure.""" + total_chunks = session["total_chunks"] + log.info(f"Assembling {total_chunks} chunks into {staged}") + assembled_bytes = 0 + try: + async with await open_file(staged, "wb") as dest: + for i in range(total_chunks): + chunk_path = ROM_UPLOAD_TMP_BASE / upload_id / f"{i:05d}" + async with await open_file(chunk_path, "rb") as src: + while True: + buf = await src.read(ROM_ASSEMBLY_CHUNK_SIZE) + if not buf: + break + assembled_bytes += len(buf) + await dest.write(buf) + if assembled_bytes != session["total_size"]: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=( + "Assembled file size mismatch: " + f"expected {session['total_size']}, got {assembled_bytes}" + ), + ) + except Exception as exc: + await AsyncPath(staged).unlink(missing_ok=True) + if isinstance(exc, HTTPException): + raise + log.error(f"Error assembling upload {upload_id}", exc_info=exc) + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Error assembling file chunks", + ) from exc + + @protected_route( router.post, "/{upload_id}/complete", @@ -459,75 +511,12 @@ async def complete_chunked_upload( ) try: - target_dir, file_location, rom = await _resolve_destination(request, session) - except Exception: + destination = await _resolve_destination(request, session) + staged = staging_path(destination.location) + await _assemble_chunks(upload_id, session, staged) + await _commit(destination, staged, overwrite=session["overwrite"]) + finally: await _cleanup_upload_state(upload_id) - raise - - await fs_rom_handler.make_directory(target_dir) - - log.info(f"Assembling {total_chunks} chunks into {file_location}") - - # Assemble chunks in order into final file with a temporary filename - # then atomically rename to final location - temp_location = file_location.with_name( - f".{file_location.name}.{uuid4().hex}.{ROM_UPLOAD_ASSEMBLING_EXT}" - ) - assembled_bytes = 0 - claimed = False - - try: - async with await open_file(temp_location, "wb") as dest: - for i in range(total_chunks): - chunk_path = ROM_UPLOAD_TMP_BASE / upload_id / f"{i:05d}" - async with await open_file(chunk_path, "rb") as src: - while True: - buf = await src.read(ROM_ASSEMBLY_CHUNK_SIZE) - if not buf: - break - assembled_bytes += len(buf) - await dest.write(buf) - if assembled_bytes != session["total_size"]: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=( - "Assembled file size mismatch: " - f"expected {session['total_size']}, got {assembled_bytes}" - ), - ) - - _claim_destination(file_location) - claimed = True - temp_location.replace(file_location) - except Exception as exc: - if temp_location.exists(): - temp_location.unlink() - if claimed: - # The claim is an empty placeholder the rename never replaced; - # left behind, a scan would ingest it as a zero-byte ROM. - file_location.unlink(missing_ok=True) - await _cleanup_upload_state(upload_id) - if isinstance(exc, HTTPException): - raise - log.error(f"Error assembling upload {upload_id}", exc_info=exc) - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="Error assembling file chunks", - ) from exc - - await _cleanup_upload_state(upload_id) - - log.info(f"Chunked upload complete: {file_location}") - - if rom is not None: - try: - await refresh_rom_files(rom) - except Exception as exc: - log.error(f"Error registering uploaded file for ROM {rom.id}", exc_info=exc) - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="File uploaded but not registered yet, run a quick scan", - ) from exc return Response(status_code=status.HTTP_201_CREATED) diff --git a/backend/endpoints/roms/walkthrough.py b/backend/endpoints/roms/walkthrough.py index 0c7adc0c0..9207c35d3 100644 --- a/backend/endpoints/roms/walkthrough.py +++ b/backend/endpoints/roms/walkthrough.py @@ -8,11 +8,9 @@ from fastapi import Body, Header, HTTPException from fastapi import Path as PathVar from fastapi import Request, status from fastapi.responses import Response -from starlette.requests import ClientDisconnect -from streaming_form_data import StreamingFormDataParser -from streaming_form_data.targets import FileTarget, NullTarget from decorators.auth import protected_route +from endpoints.roms.upload import receive_rom_file from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException from exceptions.fs_exceptions import RomAlreadyExistsException from handler.auth.constants import Scope @@ -20,27 +18,20 @@ from handler.auth.dependencies import assert_rom_visible from handler.database import db_rom_handler from handler.filesystem import fs_rom_handler from handler.rom_conversion import promote_single_file_to_folder +from handler.rom_upload import CATEGORY_UPLOAD_FOLDERS from handler.walkthrough import fetch_gamefaqs_guide, validate_gamefaqs_url from handler.walkthrough.gamefaqs import GameFAQsFetchError from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log from models.rom import DocSource, RomFile, RomFileCategory -from utils.media_types import ALLOWED_DOCUMENT_EXTENSIONS from utils.router import APIRouter router = APIRouter() -WALKTHROUGH_FOLDER = "walkthrough" - _SLUG_RE = re.compile(r"[^a-z0-9]+") -def _is_allowed_walkthrough_file(file_name: str) -> bool: - _, ext = os.path.splitext(file_name) - return ext.lower() in ALLOWED_DOCUMENT_EXTENSIONS - - def _slugify(value: str, fallback: str = "walkthrough") -> str: slug = _SLUG_RE.sub("-", value.lower()).strip("-") return (slug[:80] or fallback).strip("-") or fallback @@ -91,104 +82,18 @@ async def add_rom_walkthrough_file( assert_rom_visible(request, rom) - if rom.has_simple_single_file: - try: - rom = await promote_single_file_to_folder(rom) - except RomAlreadyExistsException as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, detail=str(exc) - ) from exc - - try: - safe_filename = fs_rom_handler._sanitize_filename(filename) - except ValueError as exc: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload filename: {exc}", - ) from exc - - if safe_filename != filename: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload filename must be a plain file name, not a path", - ) - - if not _is_allowed_walkthrough_file(safe_filename): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=( - f"Unsupported walkthrough file type. Allowed: " - f"{', '.join(sorted(ALLOWED_DOCUMENT_EXTENSIONS))}" - ), - ) - - walkthrough_dir_rel = f"{rom.full_path}/{WALKTHROUGH_FOLDER}" - file_rel_path = f"{walkthrough_dir_rel}/{safe_filename}" - file_location = fs_rom_handler.validate_path(file_rel_path) - log.info(f"Uploading walkthrough file to {hl(str(file_location))}") - - await fs_rom_handler.make_directory(walkthrough_dir_rel) - - parser = StreamingFormDataParser(headers=request.headers) - parser.register("x-upload-platform", NullTarget()) - parser.register(safe_filename, FileTarget(str(file_location))) - - def cleanup_partial_file(): - if file_location.exists(): - file_location.unlink() - - try: - async for chunk in request.stream(): - parser.data_received(chunk) - except ClientDisconnect: - log.error("Client disconnected during upload") - cleanup_partial_file() - raise - except Exception as exc: - log.error("Error uploading walkthrough file", exc_info=exc) - cleanup_partial_file() - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="There was an error uploading the walkthrough file", - ) from exc - - stat = os.stat(file_location) - existing = db_rom_handler.get_rom_file_by_path( - rom_id=rom.id, file_path=walkthrough_dir_rel, file_name=safe_filename + rom_file = await receive_rom_file( + request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.WALKTHROUGH], filename ) - if existing: - db_rom_handler.update_rom_file( - existing.id, - { - "file_size_bytes": stat.st_size, - "last_modified": stat.st_mtime, - "category": RomFileCategory.WALKTHROUGH, - "missing_from_fs": False, + if rom_file: + db_rom_handler.upsert_doc_meta( + rom_file_id=rom_file.id, + rom_id=rom.id, + values={ + "author": _decode_header(author), + "title": _decode_header(title), }, ) - rom_file_id = existing.id - else: - created = db_rom_handler.add_rom_file( - RomFile( - rom_id=rom.id, - file_name=safe_filename, - file_path=walkthrough_dir_rel, - file_size_bytes=stat.st_size, - last_modified=stat.st_mtime, - category=RomFileCategory.WALKTHROUGH, - ) - ) - rom_file_id = created.id - - db_rom_handler.upsert_doc_meta( - rom_file_id=rom_file_id, - rom_id=rom.id, - values={ - "source": DocSource.UPLOAD, - "author": _decode_header(author), - "title": _decode_header(title), - }, - ) return Response(status_code=status.HTTP_201_CREATED) @@ -243,7 +148,9 @@ async def add_rom_gamefaqs_walkthrough( status_code=status.HTTP_409_CONFLICT, detail=str(exc) ) from exc - walkthrough_dir_rel = f"{rom.full_path}/{WALKTHROUGH_FOLDER}" + walkthrough_dir_rel = ( + f"{rom.full_path}/{CATEGORY_UPLOAD_FOLDERS[RomFileCategory.WALKTHROUGH]}" + ) base_name = _slugify(guide["title"] or f"gamefaqs-{rom.id}") file_name = f"{base_name}.txt" diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index 781be1b6e..898a944bb 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -1,7 +1,7 @@ from datetime import datetime, timezone from typing import Any, Final, Mapping, cast -from fastapi import Body, HTTPException, Request +from fastapi import Body, HTTPException, Request, status from rq import Worker from rq.exceptions import NoSuchJobError from rq.job import Job, JobStatus @@ -10,6 +10,7 @@ from rq.registry import FailedJobRegistry, FinishedJobRegistry from config import ENABLE_RESCAN_ON_FILESYSTEM_CHANGE, RESCAN_ON_FILESYSTEM_CHANGE_DELAY from decorators.auth import protected_route from endpoints.responses import ( + CleanupStats, CleanupTaskStatusResponse, ConversionTaskStatusResponse, GenericTaskStatusResponse, @@ -27,6 +28,8 @@ from handler.redis_handler import ( ALL_QUEUES, get_job_func_name, get_worker_current_job, + has_live_worker, + low_prio_queue, redis_client, ) from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS, enqueue_task @@ -86,6 +89,19 @@ def _fill_scan_stats(stats: Mapping[str, Any] | None) -> ScanStats | None: return cast(ScanStats, {**_EMPTY_SCAN_STATS, **stats}) +def _fill_cleanup_stats(stats: Mapping[str, Any] | None) -> CleanupStats | None: + """Widen the single platform a 5.2.0 job's stored stats named.""" + # Job meta lives for TASK_RESULT_TTL, so this only ever meets jobs that + # finished just before an upgrade. + if stats is None or "platform_id" not in stats: + return cast(CleanupStats | None, stats) + + legacy = {**stats} + platform_id = legacy.pop("platform_id") + legacy["platform_ids"] = [platform_id] if platform_id is not None else None + return cast(CleanupStats, legacy) + + def _build_task_status_response( job: Job, ) -> TaskStatusResponse: @@ -140,7 +156,9 @@ def _build_task_status_response( case TaskType.CLEANUP: return CleanupTaskStatusResponse( task_type=TaskType.CLEANUP, - meta={"cleanup_stats": job_meta.get("cleanup_stats")}, + meta={ + "cleanup_stats": _fill_cleanup_stats(job_meta.get("cleanup_stats")) + }, **common_data, # trunk-ignore(mypy/typeddict-item) ) case TaskType.SYNC: @@ -301,9 +319,16 @@ async def run_single_task( detail=f"Task '{task_name}' cannot be run", ) + # Without a worker the job would sit queued while the UI waits on it. + if not has_live_worker(low_prio_queue): + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="No task worker is listening, so the task cannot be queued", + ) + # The caller's arguments are nested rather than spread, so a body cannot # name a different task than the one this route just authorized. - job = enqueue_task(task_name, task_kwargs=task_kwargs or {}) + job = enqueue_task(task_name, queue=low_prio_queue, task_kwargs=task_kwargs or {}) return { "task_key": task_name, diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 55cba7b99..966074a16 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -147,6 +147,18 @@ def category_matches(category: str, path_parts: list[str]) -> bool: ) +def category_for_path_parts(path_parts_lower: list[str]) -> RomFileCategory | None: + """The file category a folder path implies, from its lowercased parts.""" + return next( + ( + category + for category in RomFileCategory + if category_matches(category.value, path_parts_lower) + ), + None, + ) + + DEFAULT_CRC_C = 0 DEFAULT_MD5_H_DIGEST = hashlib.md5(usedforsecurity=False).digest() DEFAULT_SHA1_H_DIGEST = hashlib.sha1(usedforsecurity=False).digest() @@ -482,14 +494,8 @@ class FSRomsHandler(FSHandler): ) -> RomFile: abs_file_path = Path(self.base_path, rom_path, file_name) - path_parts_lower = list(map(str.lower, rom_path.parts)) - matching_category = next( - ( - category - for category in RomFileCategory - if category_matches(category.value, path_parts_lower) - ), - None, + matching_category = category_for_path_parts( + list(map(str.lower, rom_path.parts)) ) track_meta = None diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index 7ae82a13c..ec2ca9f16 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -8,6 +8,7 @@ from redis.asyncio import Redis as AsyncRedis from rq import Queue, Worker from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobError from rq.job import Job, JobStatus +from rq.worker import WorkerStatus from config import IS_PYTEST_RUN, REDIS_URL from logger.logger import log @@ -161,3 +162,13 @@ def get_worker_current_job(worker: Worker) -> Job | None: return worker.get_current_job() except NoSuchJobError: return None + + +def has_live_worker(queue: Queue) -> bool: + """Whether a job enqueued on ``queue`` would be picked up.""" + # A worker that crashed without announcing it stays registered until its + # key TTL lapses, so this can still say yes for a few minutes after a kill. + return any( + worker.death_date is None and worker.get_state() != WorkerStatus.SUSPENDED + for worker in Worker.all(queue=queue) + ) diff --git a/backend/handler/rom_files.py b/backend/handler/rom_files.py index 6925b24e2..ea1011901 100644 --- a/backend/handler/rom_files.py +++ b/backend/handler/rom_files.py @@ -1,7 +1,9 @@ import asyncio -import weakref +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager from dataclasses import dataclass from typing import Any +from uuid import uuid4 from sqlalchemy import inspect as sa_inspect @@ -9,6 +11,7 @@ from config.config_manager import config_manager as cm from handler.database import db_rom_handler from handler.filesystem import fs_rom_handler from handler.filesystem.roms_handler import RomFileKey, rom_file_key +from handler.redis_handler import async_cache from handler.scan_handler import persist_soundtrack_cover from logger.formatter import highlight as hl from logger.logger import log @@ -19,17 +22,30 @@ ROM_LEVEL_HASH_COLUMNS = ("crc_hash", "md5_hash", "sha1_hash", "ra_hash") # A refresh lists the folder and then deletes every row the listing missed, so # two of them running for the same rom (parallel uploads into one folder) would -# let the slower listing drop what the faster one just registered. -_refresh_locks: weakref.WeakValueDictionary[int, asyncio.Lock] = ( - weakref.WeakValueDictionary() -) +# let the slower listing drop what the faster one just registered. The lock +# lives in Redis because the uploads may land on different gunicorn workers, +# and is a plain SET NX so it also works without Lua scripting. +REFRESH_LOCK_TIMEOUT_SECONDS = 600 +REFRESH_LOCK_POLL_SECONDS = 0.1 -def _refresh_lock(rom_id: int) -> asyncio.Lock: - lock = _refresh_locks.get(rom_id) - if lock is None: - lock = _refresh_locks[rom_id] = asyncio.Lock() - return lock +@asynccontextmanager +async def _refresh_lock(rom_id: int) -> AsyncIterator[None]: + key = f"rom_files_refresh:{rom_id}" + token = uuid4().hex + for _ in range(int(REFRESH_LOCK_TIMEOUT_SECONDS / REFRESH_LOCK_POLL_SECONDS)): + if await async_cache.set(key, token, nx=True, ex=REFRESH_LOCK_TIMEOUT_SECONDS): + break + await asyncio.sleep(REFRESH_LOCK_POLL_SECONDS) + else: + raise TimeoutError(f"Timed out waiting to refresh the files of ROM {rom_id}") + try: + yield + finally: + # Only the owner releases; an expired lock may belong to someone else. + held = await async_cache.get(key) + if held in (token, token.encode()): + await async_cache.delete(key) @dataclass(frozen=True) diff --git a/backend/handler/rom_upload.py b/backend/handler/rom_upload.py new file mode 100644 index 000000000..cd03f636e --- /dev/null +++ b/backend/handler/rom_upload.py @@ -0,0 +1,249 @@ +"""One ingestion path for every file uploaded into a ROM's folder, whether the +bytes arrive in chunks or as a single multipart request.""" + +import os +from dataclasses import dataclass +from pathlib import Path +from uuid import uuid4 + +from config import ROM_UPLOAD_ASSEMBLING_EXT +from handler.database import db_rom_handler +from handler.filesystem import fs_rom_handler +from handler.filesystem.resources_handler import ALLOWED_MANUAL_EXTENSIONS +from handler.filesystem.roms_handler import category_for_path_parts +from handler.rom_conversion import promote_single_file_to_folder +from handler.rom_files import refresh_rom_files +from logger.logger import log +from models.rom import DocSource, Rom, RomFile, RomFileCategory +from utils.audio_tags import ALLOWED_AUDIO_EXTENSIONS +from utils.media_types import ALLOWED_DOCUMENT_EXTENSIONS, ALLOWED_IMAGE_EXTENSIONS + +# The folder each media route uploads into. The scanner maps these names back to +# the category, so a file landing here is registered the same way a scan would. +CATEGORY_UPLOAD_FOLDERS: dict[RomFileCategory, str] = { + RomFileCategory.MANUAL: "manual", + RomFileCategory.WALKTHROUGH: "walkthrough", + RomFileCategory.SCREENSHOT: "screenshots", + RomFileCategory.SOUNDTRACK: "soundtrack", +} + + +# What a folder the scanner maps to a media category may receive, so a file the +# tab could never show is refused before it lands. +CATEGORY_FILE_TYPES: dict[RomFileCategory, tuple[str, frozenset[str]]] = { + RomFileCategory.MANUAL: ("manual", ALLOWED_MANUAL_EXTENSIONS), + RomFileCategory.WALKTHROUGH: ("walkthrough", ALLOWED_DOCUMENT_EXTENSIONS), + RomFileCategory.SCREENSHOT: ("image", ALLOWED_IMAGE_EXTENSIONS), + RomFileCategory.SOUNDTRACK: ("audio", ALLOWED_AUDIO_EXTENSIONS), +} + + +class UploadRejectedException(ValueError): + """The upload names a file or folder the ROM's folder cannot take.""" + + +class UploadConflictException(FileExistsError): + """A file of that name is already in the ROM's folder.""" + + +class UploadNotRegisteredException(Exception): + """The file is on disk but the ROM's file rows could not be refreshed.""" + + +@dataclass(frozen=True) +class UploadDestination: + """Where an upload lands: the ROM it belongs to (none for a platform folder + upload), the library-relative directory and the absolute file path.""" + + rom: Rom | None + rel_dir: str + location: Path + + +def sanitize_upload_filename(filename: str) -> str: + """A plain file name, or UploadRejectedException when it carries a path.""" + try: + safe_filename = fs_rom_handler._sanitize_filename(filename) + except ValueError as exc: + raise UploadRejectedException(f"Invalid upload filename: {exc}") from exc + if safe_filename != filename: + raise UploadRejectedException( + "Upload filename must be a plain file name, not a path" + ) + return safe_filename + + +def parse_upload_folder(folder: str) -> str: + """Normalize the target subfolder to a relative path made of plain names.""" + raw = folder.strip() + if raw.startswith("/") or "\\" in raw: + raise UploadRejectedException( + "Upload folder must be a relative, forward-slashed path" + ) + raw = raw.rstrip("/") + if not raw: + return "" + segments = raw.split("/") + for segment in segments: + try: + safe_segment = fs_rom_handler._sanitize_filename(segment) + except ValueError as exc: + raise UploadRejectedException(f"Invalid upload folder: {exc}") from exc + if safe_segment != segment: + raise UploadRejectedException( + "Upload folder must be a relative path inside the game folder" + ) + return "/".join(segments) + + +def assert_allowed_in_folder(folder: str, filename: str) -> None: + """Refuse a file the category the folder maps to cannot hold.""" + category = category_for_path_parts(folder.lower().split("/")) + if category is None or category not in CATEGORY_FILE_TYPES: + return + label, extensions = CATEGORY_FILE_TYPES[category] + if os.path.splitext(filename)[1].lower() not in extensions: + raise UploadRejectedException( + f"Unsupported {label} file type. Allowed: {', '.join(sorted(extensions))}" + ) + + +def resolve_upload_destination( + rom: Rom, folder: str, filename: str, *, overwrite: bool = False +) -> tuple[str, Path]: + """The library-relative directory and absolute file path of an upload into a + ROM, kept inside the folder a lone file gets promoted into. + + Raises: + UploadRejectedException: The destination is unusable, the folder's + category cannot hold the file, or the scanner would never register it. + UploadConflictException: A file of that name is already there (or will + be, once promoted), unless `overwrite` allows replacing it. + """ + assert_allowed_in_folder(folder, filename) + if fs_rom_handler.is_excluded_multi_part(filename): + raise UploadRejectedException( + f"File {filename} would be ignored by the scanner" + ) + + root = ( + f"{rom.fs_path}/{rom.fs_name_no_ext}" + if rom.has_simple_single_file + else rom.full_path + ) + rel_dir = f"{root}/{folder}" if folder else root + try: + root_location = fs_rom_handler.validate_path(root) + location = fs_rom_handler.validate_path(f"{rel_dir}/{filename}") + except ValueError as exc: + raise UploadRejectedException(str(exc)) from exc + if not location.is_relative_to(root_location): + raise UploadRejectedException( + "Upload destination must be inside the game folder" + ) + + promoted_over_itself = ( + rom.has_simple_single_file and not folder and filename == rom.fs_name + ) + replaceable = overwrite and location.is_file() + if promoted_over_itself or (location.exists() and not replaceable): + raise UploadConflictException( + f"File {filename} already exists in the game folder" + ) + return rel_dir, location + + +async def prepare_upload_destination( + rom: Rom, folder: str, filename: str, *, overwrite: bool = False +) -> UploadDestination: + """Resolve where the file lands, promote a lone file into its folder and + create the target directory. + + Raises the same as `resolve_upload_destination`, plus + RomAlreadyExistsException when the promotion collides with a folder. + """ + rel_dir, location = resolve_upload_destination( + rom, folder, filename, overwrite=overwrite + ) + if rom.has_simple_single_file: + rom = await promote_single_file_to_folder(rom) + await fs_rom_handler.make_directory(rel_dir) + return UploadDestination(rom=rom, rel_dir=rel_dir, location=location) + + +def staging_path(location: Path) -> Path: + """A private sibling of the destination, so the final move is a rename on + the same filesystem.""" + return location.with_name( + f".{location.name}.{uuid4().hex}.{ROM_UPLOAD_ASSEMBLING_EXT}" + ) + + +def claim_destination(location: Path) -> None: + """Create the final path exclusively, so two uploads racing for the same + name cannot overwrite each other's bytes.""" + try: + os.close(os.open(location, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)) + except FileExistsError as exc: + raise UploadConflictException(f"File {location.name} already exists") from exc + + +def _move_into_place(location: Path, staged: Path, *, overwrite: bool) -> None: + claimed = False + try: + if not overwrite: + claim_destination(location) + claimed = True + staged.replace(location) + except BaseException: + staged.unlink(missing_ok=True) + if claimed: + # The claim is an empty placeholder the rename never replaced; + # left behind, a scan would ingest it as a zero-byte ROM. + location.unlink(missing_ok=True) + raise + + +async def commit_upload( + destination: UploadDestination, staged: Path, *, overwrite: bool = False +) -> RomFile | None: + """Move the staged bytes into place and register the file on its ROM. + + The staged file is removed whatever the outcome. + + Returns: + The registered file row, or None for a platform folder upload. + Raises: + UploadConflictException: The name got taken while the bytes arrived. + UploadNotRegisteredException: The file is in place but the ROM's rows + could not be refreshed. + """ + _move_into_place(destination.location, staged, overwrite=overwrite) + log.info(f"Upload complete: {destination.location}") + + rom = destination.rom + if rom is None: + return None + try: + await refresh_rom_files(rom) + except Exception as exc: + log.error(f"Error registering uploaded file for ROM {rom.id}", exc_info=exc) + raise UploadNotRegisteredException( + "File uploaded but not registered yet, run a quick scan" + ) from exc + + rom_file = db_rom_handler.get_rom_file_by_path( + rom_id=rom.id, + file_path=destination.rel_dir, + file_name=destination.location.name, + ) + # A scan records no provenance; an upload is one, whichever route took it. + if ( + rom_file + and rom_file.category == RomFileCategory.WALKTHROUGH + and rom_file.doc_meta is None + ): + db_rom_handler.upsert_doc_meta( + rom_file_id=rom_file.id, rom_id=rom.id, values={"source": DocSource.UPLOAD} + ) + return rom_file diff --git a/backend/tasks/manual/cleanup_missing_firmware.py b/backend/tasks/manual/cleanup_missing_firmware.py index afa7a3a76..7d3aaa677 100644 --- a/backend/tasks/manual/cleanup_missing_firmware.py +++ b/backend/tasks/manual/cleanup_missing_firmware.py @@ -1,5 +1,7 @@ -from dataclasses import dataclass +from dataclasses import asdict, dataclass +from typing import cast +from endpoints.responses import MissingFirmwareCleanupStats from handler.database import db_firmware_handler from logger.logger import log from tasks.tasks import Task, TaskType, update_job_meta @@ -22,13 +24,8 @@ class CleanupMissingFirmwareStats: update_job_meta({"cleanup_stats": self.to_dict()}) - def to_dict(self) -> dict: - return { - "platform_ids": self.platform_ids, - "firmware_found": self.firmware_found, - "firmware_deleted": self.firmware_deleted, - "errors": self.errors, - } + def to_dict(self) -> MissingFirmwareCleanupStats: + return cast(MissingFirmwareCleanupStats, asdict(self)) class CleanupMissingFirmwareTask(Task): @@ -43,7 +40,9 @@ class CleanupMissingFirmwareTask(Task): ) @initialize_context() - async def run(self, platform_ids: list[int] | None = None) -> dict: + async def run( + self, platform_ids: list[int] | None = None + ) -> MissingFirmwareCleanupStats: """Clean up firmware that is flagged as missing from the filesystem.""" log.info(f"Starting {self.title} task...") diff --git a/backend/tasks/manual/cleanup_missing_roms.py b/backend/tasks/manual/cleanup_missing_roms.py index e4f2b2fbd..7dabc7b29 100644 --- a/backend/tasks/manual/cleanup_missing_roms.py +++ b/backend/tasks/manual/cleanup_missing_roms.py @@ -1,6 +1,7 @@ -from dataclasses import dataclass -from typing import Any +from dataclasses import asdict, dataclass +from typing import Any, cast +from endpoints.responses import MissingRomsCleanupStats from handler.database import db_rom_handler from handler.filesystem import fs_resource_handler from logger.logger import log @@ -24,13 +25,8 @@ class CleanupMissingRomsStats: update_job_meta({"cleanup_stats": self.to_dict()}) - def to_dict(self) -> dict: - return { - "platform_ids": self.platform_ids, - "roms_found": self.roms_found, - "roms_deleted": self.roms_deleted, - "errors": self.errors, - } + def to_dict(self) -> MissingRomsCleanupStats: + return cast(MissingRomsCleanupStats, asdict(self)) class CleanupMissingRomsTask(Task): @@ -45,7 +41,9 @@ class CleanupMissingRomsTask(Task): ) @initialize_context() - async def run(self, platform_ids: list[int] | None = None) -> dict: + async def run( + self, platform_ids: list[int] | None = None + ) -> MissingRomsCleanupStats: """Clean up ROMs that are flagged as missing from the filesystem.""" log.info(f"Starting {self.title} task...") diff --git a/backend/tests/config/fixtures/config/config.yml b/backend/tests/config/fixtures/config/config.yml index daee39102..5bde2c5d6 100644 --- a/backend/tests/config/fixtures/config/config.yml +++ b/backend/tests/config/fixtures/config/config.yml @@ -73,7 +73,7 @@ emulatorjs: cache_limit: 1000 disable_auto_unload: true disable_batch_bootup: true - auto_save_sync: true + auto_save_sync: false netplay: enabled: true ice_servers: diff --git a/backend/tests/config/test_config_loader.py b/backend/tests/config/test_config_loader.py index b5030c55a..325741c33 100644 --- a/backend/tests/config/test_config_loader.py +++ b/backend/tests/config/test_config_loader.py @@ -58,7 +58,7 @@ def test_config_loader(): assert loader.config.EJS_DEBUG assert loader.config.EJS_DISABLE_AUTO_UNLOAD assert loader.config.EJS_DISABLE_BATCH_BOOTUP - assert loader.config.EJS_ENABLE_AUTO_SAVE_SYNC + assert not loader.config.EJS_ENABLE_AUTO_SAVE_SYNC assert loader.config.EJS_CACHE_LIMIT == 1000 assert loader.config.EJS_NETPLAY_ENABLED assert loader.config.EJS_NETPLAY_ICE_SERVERS == [ @@ -161,7 +161,7 @@ def test_empty_config_loader(): assert loader.config.EJS_CACHE_LIMIT is None assert not loader.config.EJS_DISABLE_AUTO_UNLOAD assert not loader.config.EJS_DISABLE_BATCH_BOOTUP - assert not loader.config.EJS_ENABLE_AUTO_SAVE_SYNC + assert loader.config.EJS_ENABLE_AUTO_SAVE_SYNC assert not loader.config.EJS_NETPLAY_ENABLED assert loader.config.EJS_NETPLAY_ICE_SERVERS == [] assert loader.config.EJS_DEFAULT_CORES == {} diff --git a/backend/tests/endpoints/roms/conftest.py b/backend/tests/endpoints/roms/conftest.py index ee7c2d0cd..b7d2c67fb 100644 --- a/backend/tests/endpoints/roms/conftest.py +++ b/backend/tests/endpoints/roms/conftest.py @@ -1,11 +1,35 @@ +from pathlib import Path + import pytest from handler.database import 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 +@pytest.fixture +def real_library(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Point fs_rom_handler at a real temp library so file moves and listings + actually happen.""" + lib = tmp_path / "library" + lib.mkdir() + monkeypatch.setattr(fs_rom_handler, "base_path", lib.resolve()) + return lib + + +@pytest.fixture +def game_folder_on_disk(real_library: Path, game_folder_rom: Rom) -> Path: + """The folder ROM's directory in the real library, with every file row + written to disk so a refresh keeps them.""" + for rom_file in game_folder_rom.files: + path = real_library / rom_file.full_path + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"\0" * rom_file.file_size_bytes) + return real_library / game_folder_rom.full_path + + @pytest.fixture def game_folder_rom(admin_user: User, platform: Platform) -> Rom: """A folder-based ROM with two top-level files (so has_simple_single_file is False).""" diff --git a/backend/tests/endpoints/roms/test_convert_to_folder.py b/backend/tests/endpoints/roms/test_convert_to_folder.py index 5f4b80450..4743173fa 100644 --- a/backend/tests/endpoints/roms/test_convert_to_folder.py +++ b/backend/tests/endpoints/roms/test_convert_to_folder.py @@ -22,15 +22,6 @@ def _auth(token: str) -> dict[str, str]: return {"Authorization": f"Bearer {token}"} -@pytest.fixture -def real_library(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: - """Point fs_rom_handler at a real temp library so FS moves actually happen.""" - lib = tmp_path / "library" - lib.mkdir() - monkeypatch.setattr(fs_rom_handler, "base_path", lib.resolve()) - return lib - - def _single_file_rom( platform: Platform, admin_user: User, diff --git a/backend/tests/endpoints/roms/test_manual.py b/backend/tests/endpoints/roms/test_manual.py index dd08986a9..bf7de1b99 100644 --- a/backend/tests/endpoints/roms/test_manual.py +++ b/backend/tests/endpoints/roms/test_manual.py @@ -40,33 +40,11 @@ def manual_fs_resources(tmp_path: Path, mocker: MockerFixture): @pytest.fixture -def manual_fs_folder(tmp_path: Path, mocker: MockerFixture): - """Mock fs_rom_handler so /manuals/files (folder path) writes to tmp_path.""" - folder_dir = tmp_path / "library" - folder_dir.mkdir() - - def validate_path(path: str) -> Path: - return folder_dir / Path(path).name - - async def remove_file(path: str) -> None: - target = folder_dir / Path(path).name - if target.exists(): - target.unlink() - else: - raise FileNotFoundError(path) - - mocker.patch.object(manual_endpoint.fs_rom_handler, "validate_path", validate_path) - mocker.patch.object( - manual_endpoint.fs_rom_handler, - "make_directory", - AsyncMock(return_value=None), - ) - mocker.patch.object( - manual_endpoint.fs_rom_handler, - "remove_file", - AsyncMock(side_effect=remove_file), - ) - return folder_dir +def manual_fs_folder(game_folder_on_disk: Path) -> Path: + """The ROM's manual folder inside a real temp library.""" + media_dir = game_folder_on_disk / "manual" + media_dir.mkdir() + return media_dir # ---------- POST /api/roms/{id}/manuals (resources) ---------- diff --git a/backend/tests/endpoints/roms/test_screenshot.py b/backend/tests/endpoints/roms/test_screenshot.py index 1723e29f0..38954203f 100644 --- a/backend/tests/endpoints/roms/test_screenshot.py +++ b/backend/tests/endpoints/roms/test_screenshot.py @@ -1,11 +1,9 @@ from pathlib import Path -from unittest.mock import AsyncMock import pytest from fastapi import status from fastapi.testclient import TestClient -from endpoints.roms import screenshot as screenshot_endpoint from handler.database import db_rom_handler from models.rom import Rom, RomFile, RomFileCategory @@ -17,34 +15,11 @@ def _auth(token: str) -> dict[str, str]: @pytest.fixture -def screenshot_fs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - folder_dir = tmp_path / "library" - folder_dir.mkdir() - - def validate_path(path: str) -> Path: - return folder_dir / Path(path).name - - async def remove_file(path: str) -> None: - target = folder_dir / Path(path).name - if target.exists(): - target.unlink() - else: - raise FileNotFoundError(path) - - monkeypatch.setattr( - screenshot_endpoint.fs_rom_handler, "validate_path", validate_path - ) - monkeypatch.setattr( - screenshot_endpoint.fs_rom_handler, - "make_directory", - AsyncMock(return_value=None), - ) - monkeypatch.setattr( - screenshot_endpoint.fs_rom_handler, - "remove_file", - AsyncMock(side_effect=remove_file), - ) - return folder_dir +def screenshot_fs(game_folder_on_disk: Path) -> Path: + """The ROM's screenshots folder inside a real temp library.""" + media_dir = game_folder_on_disk / "screenshots" + media_dir.mkdir() + return media_dir # ---------- POST /api/roms/{id}/screenshots ---------- diff --git a/backend/tests/endpoints/roms/test_soundtrack.py b/backend/tests/endpoints/roms/test_soundtrack.py index c9149354e..92fb36cc1 100644 --- a/backend/tests/endpoints/roms/test_soundtrack.py +++ b/backend/tests/endpoints/roms/test_soundtrack.py @@ -1,13 +1,14 @@ from pathlib import Path -from unittest.mock import AsyncMock import pytest from fastapi import status from fastapi.testclient import TestClient from endpoints.roms import soundtrack as soundtrack_endpoint +from handler import scan_handler from handler.database import db_rom_handler from models.rom import Rom, RomFile, RomFileCategory, TrackMeta +from utils import audio_tags from utils.audio_tags import AudioTags, track_meta_columns MP3_BYTES = b"ID3\x03\x00\x00\x00\x00\x00\x21fake mp3 payload" @@ -18,34 +19,11 @@ def _auth(token: str) -> dict[str, str]: @pytest.fixture -def soundtrack_fs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - folder_dir = tmp_path / "library" - folder_dir.mkdir() - - def validate_path(path: str) -> Path: - return folder_dir / Path(path).name - - async def remove_file(path: str) -> None: - target = folder_dir / Path(path).name - if target.exists(): - target.unlink() - else: - raise FileNotFoundError(path) - - monkeypatch.setattr( - soundtrack_endpoint.fs_rom_handler, "validate_path", validate_path - ) - monkeypatch.setattr( - soundtrack_endpoint.fs_rom_handler, - "make_directory", - AsyncMock(return_value=None), - ) - monkeypatch.setattr( - soundtrack_endpoint.fs_rom_handler, - "remove_file", - AsyncMock(side_effect=remove_file), - ) - return folder_dir +def soundtrack_fs(game_folder_on_disk: Path) -> Path: + """The ROM's soundtrack folder inside a real temp library.""" + media_dir = game_folder_on_disk / "soundtrack" + media_dir.mkdir() + return media_dir # ---------- POST /api/roms/{id}/soundtracks ---------- @@ -99,6 +77,64 @@ def test_upload_soundtrack_upserts_on_reupload( assert len(soundtracks) == 1 +def test_upload_soundtrack_creates_missing_folder( + client: TestClient, + access_token: str, + game_folder_rom: Rom, + soundtrack_fs: Path, +): + soundtrack_fs.rmdir() + + response = client.post( + f"/api/roms/{game_folder_rom.id}/soundtracks", + headers={**_auth(access_token), "x-upload-filename": "track1.mp3"}, + files={"track1.mp3": ("track1.mp3", MP3_BYTES, "audio/mpeg")}, + ) + + assert response.status_code == status.HTTP_201_CREATED + assert (soundtrack_fs / "track1.mp3").read_bytes() == MP3_BYTES + assert db_rom_handler.get_rom_files_by_category( + game_folder_rom.id, RomFileCategory.SOUNDTRACK + ) + + +def test_upload_soundtrack_keeps_the_other_files( + client: TestClient, + access_token: str, + game_folder_rom: Rom, + soundtrack_fs: Path, +): + before = {f.file_name for f in game_folder_rom.files} + + response = client.post( + f"/api/roms/{game_folder_rom.id}/soundtracks", + headers={**_auth(access_token), "x-upload-filename": "track1.mp3"}, + files={"track1.mp3": ("track1.mp3", MP3_BYTES, "audio/mpeg")}, + ) + + assert response.status_code == status.HTTP_201_CREATED + rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert {f.file_name for f in rom_after.files} == before | {"track1.mp3"} + assert not list(soundtrack_fs.glob(".*")) + + +def test_upload_soundtrack_without_matching_part_returns_400( + client: TestClient, + access_token: str, + game_folder_rom: Rom, + soundtrack_fs: Path, +): + response = client.post( + f"/api/roms/{game_folder_rom.id}/soundtracks", + headers={**_auth(access_token), "x-upload-filename": "track1.mp3"}, + files={"other.mp3": ("other.mp3", MP3_BYTES, "audio/mpeg")}, + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert "no file part named track1.mp3" in response.json()["detail"] + assert not list(soundtrack_fs.iterdir()) + + # Single-file auto-convert on upload is covered in test_convert_to_folder.py. @@ -220,11 +256,9 @@ def test_upload_soundtrack_extracts_audio_meta( "file_mtime": 1_700_000_000.0, "file_size": len(MP3_BYTES), } + monkeypatch.setattr(audio_tags, "extract_audio_meta", lambda _path: fake_meta) monkeypatch.setattr( - soundtrack_endpoint, "extract_audio_meta", lambda _path: fake_meta - ) - monkeypatch.setattr( - soundtrack_endpoint, + scan_handler, "persist_embedded_cover", lambda **kw: ( f"roms/{kw['platform_id']}/{kw['rom_id']}" @@ -268,18 +302,14 @@ def test_upload_soundtrack_no_cover_leaves_cover_path_unset( monkeypatch: pytest.MonkeyPatch, ): monkeypatch.setattr( - soundtrack_endpoint, - "extract_audio_meta", - lambda _path: {"has_embedded_cover": False}, + audio_tags, "extract_audio_meta", lambda _path: {"has_embedded_cover": False} ) cover_calls: list[dict] = [] def _record_cover_call(**kw: object) -> None: cover_calls.append(kw) - monkeypatch.setattr( - soundtrack_endpoint, "persist_embedded_cover", _record_cover_call - ) + monkeypatch.setattr(scan_handler, "persist_embedded_cover", _record_cover_call) response = client.post( f"/api/roms/{game_folder_rom.id}/soundtracks", @@ -468,7 +498,6 @@ def test_upload_soundtrack_rejects_dotdot_only_filename( files={"..": ("..", MP3_BYTES, "audio/mpeg")}, ) assert response.status_code == status.HTTP_400_BAD_REQUEST - assert "filename" in response.json()["detail"].lower() # ---------- 404 metadata ---------- diff --git a/backend/tests/endpoints/roms/test_upload.py b/backend/tests/endpoints/roms/test_upload.py index e30ad92cc..a51c834bb 100644 --- a/backend/tests/endpoints/roms/test_upload.py +++ b/backend/tests/endpoints/roms/test_upload.py @@ -5,13 +5,14 @@ from unittest.mock import AsyncMock from uuid import UUID import pytest -from fastapi import HTTPException, status +from fastapi import status from fastapi.testclient import TestClient from endpoints.roms import upload as upload_endpoint +from handler import rom_upload from handler.database import db_platform_handler, db_rom_handler from models.platform import Platform -from models.rom import Rom, RomFile, RomFileCategory +from models.rom import DocSource, Rom, RomFile, RomFileCategory from models.user import User @@ -364,10 +365,13 @@ def _start_into_rom( folder: str | None, total_size: int, platform_id: int | None = None, + overwrite: bool = False, ): - target: dict[str, int | str] = {"rom_id": rom.id} + target: dict[str, int | str | bool] = {"rom_id": rom.id} if folder is not None: target["folder"] = folder + if overwrite: + target["overwrite"] = True return client.post( "/api/roms/upload/start", headers={ @@ -389,9 +393,16 @@ def _upload_into_rom( filename: str, folder: str | None, data: bytes, + overwrite: bool = False, ): start = _start_into_rom( - client, token, rom, filename=filename, folder=folder, total_size=len(data) + client, + token, + rom, + filename=filename, + folder=folder, + total_size=len(data), + overwrite=overwrite, ) assert start.status_code == status.HTTP_201_CREATED, start.json() upload_id = start.json()["upload_id"] @@ -523,6 +534,40 @@ def test_start_into_rom_rejects_existing_destination( assert response.status_code == status.HTTP_409_CONFLICT +def test_overwrite_replaces_an_existing_file( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + rom = _folder_rom( + platform, admin_user, rom_upload_fs, {"game.bin": b"game", "hack/x.ips": b"old"} + ) + + refused = _start_into_rom( + client, access_token, rom, filename="x.ips", folder="hack", total_size=3 + ) + assert refused.status_code == status.HTTP_409_CONFLICT + + response = _upload_into_rom( + client, + access_token, + rom, + filename="x.ips", + folder="hack", + data=b"new", + overwrite=True, + ) + + assert response.status_code == status.HTTP_201_CREATED, response.json() + on_disk = rom_upload_fs / rom.fs_path / ROM_FOLDER / "hack" / "x.ips" + assert on_disk.read_bytes() == b"new" + rows = [f for f in db_rom_handler.get_rom(rom.id).files if f.file_name == "x.ips"] + assert len(rows) == 1 + assert rows[0].file_size_bytes == 3 + + def test_complete_registers_nested_file( client: TestClient, access_token: str, @@ -690,12 +735,149 @@ def test_complete_collision_does_not_promote_a_single_file_rom( assert (rom_upload_fs / rom.fs_path / "solo.zip").read_bytes() == b"romdata" +def test_start_takes_the_filename_from_the_body_over_the_header( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + """A browser cannot put a name outside Latin-1 in a header, so the body + names the file and the header only has to be present.""" + rom = _folder_rom(platform, admin_user, rom_upload_fs, {"game.bin": b"game"}) + name = "Relax \uff5c 432Hz.mp3" + + start = client.post( + "/api/roms/upload/start", + headers={ + **_auth_headers(access_token), + "x-upload-platform": str(rom.platform_id), + "x-upload-filename": "Relax%20%EF%BD%9C%20432Hz.mp3", + "x-upload-total-size": "5", + "x-upload-total-chunks": "1", + }, + json={"rom_id": rom.id, "folder": "soundtrack", "filename": name}, + ) + assert start.status_code == status.HTTP_201_CREATED, start.json() + upload_id = start.json()["upload_id"] + client.put( + f"/api/roms/upload/{upload_id}", + headers={**_auth_headers(access_token), "x-chunk-index": "0"}, + content=b"audio", + ) + complete = client.post( + f"/api/roms/upload/{upload_id}/complete", headers=_auth_headers(access_token) + ) + + assert complete.status_code == status.HTTP_201_CREATED, complete.json() + on_disk = rom_upload_fs / rom.fs_path / ROM_FOLDER / "soundtrack" / name + assert on_disk.read_bytes() == b"audio" + track = db_rom_handler.get_rom_files_by_category(rom.id, RomFileCategory.SOUNDTRACK) + assert [f.file_name for f in track] == [name] + + +def test_start_refuses_a_file_the_folder_category_cannot_hold( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + rom = _folder_rom(platform, admin_user, rom_upload_fs, {"game.bin": b"game"}) + + response = _start_into_rom( + client, + access_token, + rom, + filename="notes.txt", + folder="screenshots", + total_size=3, + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert "Unsupported image file type" in response.json()["detail"] + + +def test_start_rejects_an_empty_body_filename( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + rom = _folder_rom(platform, admin_user, rom_upload_fs, {"game.bin": b"game"}) + + response = client.post( + "/api/roms/upload/start", + headers={ + **_auth_headers(access_token), + "x-upload-platform": str(rom.platform_id), + "x-upload-filename": "fallback.bin", + "x-upload-total-size": "3", + "x-upload-total-chunks": "1", + }, + json={"rom_id": rom.id, "filename": ""}, + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert "filename" in response.json()["detail"].lower() + + +def test_complete_into_the_walkthrough_folder_records_the_upload_source( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + rom = _folder_rom(platform, admin_user, rom_upload_fs, {"game.bin": b"game"}) + + response = _upload_into_rom( + client, + access_token, + rom, + filename="guide.txt", + folder="walkthrough", + data=b"Step 1: leave home.", + ) + + assert response.status_code == status.HTTP_201_CREATED, response.json() + guides = db_rom_handler.get_rom_files_by_category( + rom.id, RomFileCategory.WALKTHROUGH + ) + assert [f.file_name for f in guides] == ["guide.txt"] + assert guides[0].doc_meta is not None + assert guides[0].doc_meta.source == DocSource.UPLOAD + + +def test_complete_into_a_category_folder_registers_the_category( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + rom = _folder_rom(platform, admin_user, rom_upload_fs, {"game.bin": b"game"}) + + response = _upload_into_rom( + client, + access_token, + rom, + filename="shot.png", + folder="screenshots", + data=b"\x89PNG", + ) + + assert response.status_code == status.HTTP_201_CREATED, response.json() + shots = db_rom_handler.get_rom_files_by_category(rom.id, RomFileCategory.SCREENSHOT) + assert [f.file_name for f in shots] == ["shot.png"] + + def test_claim_destination_refuses_an_existing_file(tmp_path: Path): target = tmp_path / "game.bin" - upload_endpoint._claim_destination(target) + rom_upload.claim_destination(target) assert target.exists() - with pytest.raises(HTTPException) as excinfo: - upload_endpoint._claim_destination(target) - assert excinfo.value.status_code == status.HTTP_409_CONFLICT + with pytest.raises(rom_upload.UploadConflictException): + rom_upload.claim_destination(target) diff --git a/backend/tests/endpoints/roms/test_walkthrough.py b/backend/tests/endpoints/roms/test_walkthrough.py index 3e5b0e6aa..5de5d5c78 100644 --- a/backend/tests/endpoints/roms/test_walkthrough.py +++ b/backend/tests/endpoints/roms/test_walkthrough.py @@ -18,43 +18,11 @@ def _auth(token: str) -> dict[str, str]: @pytest.fixture -def walkthrough_fs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - """Mock fs_rom_handler so walkthrough writes land in tmp_path.""" - folder_dir = tmp_path / "library" - folder_dir.mkdir() - - def validate_path(path: str) -> Path: - return folder_dir / Path(path).name - - async def remove_file(path: str) -> None: - target = folder_dir / Path(path).name - if target.exists(): - target.unlink() - else: - raise FileNotFoundError(path) - - async def write_file(file, path: str, filename: str) -> None: - (folder_dir / filename).write_bytes(file) - - monkeypatch.setattr( - walkthrough_endpoint.fs_rom_handler, "validate_path", validate_path - ) - monkeypatch.setattr( - walkthrough_endpoint.fs_rom_handler, - "make_directory", - AsyncMock(return_value=None), - ) - monkeypatch.setattr( - walkthrough_endpoint.fs_rom_handler, - "remove_file", - AsyncMock(side_effect=remove_file), - ) - monkeypatch.setattr( - walkthrough_endpoint.fs_rom_handler, - "write_file", - AsyncMock(side_effect=write_file), - ) - return folder_dir +def walkthrough_fs(game_folder_on_disk: Path) -> Path: + """The ROM's walkthrough folder inside a real temp library.""" + media_dir = game_folder_on_disk / "walkthrough" + media_dir.mkdir() + return media_dir # ---------- POST /api/roms/{id}/walkthroughs/files ---------- diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index bc5045bc1..ae92101c2 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -5,7 +5,9 @@ import pytest from fastapi import status from rq.exceptions import NoSuchJobError -from handler.redis_handler import redis_client +from handler.redis_handler import low_prio_queue, redis_client +from tasks.manual.cleanup_missing_firmware import CleanupMissingFirmwareStats +from tasks.manual.cleanup_missing_roms import CleanupMissingRomsStats from tasks.tasks import Task, TaskType @@ -23,6 +25,13 @@ def _job_with_meta(meta: dict[str, Any]) -> Mock: return job +@pytest.fixture(autouse=True) +def task_worker_listening(): + """A live task worker, so a run is accepted unless a test takes it away.""" + with patch("endpoints.tasks.has_live_worker", return_value=True) as mocked: + yield mocked + + @pytest.fixture def mock_task(): """Create a mock task for testing""" @@ -236,28 +245,15 @@ class TestRunSingleTask: """Test suite for the run_single_task endpoint""" @patch("endpoints.tasks.enqueue_task", return_value=create_mock_job()) - @patch( - "endpoints.tasks.RUNNABLE_TASKS", - { - "test_task": Mock( - spec=Task, - task_type=TaskType.CLEANUP, - title="Test Task", - description="Test Description", - enabled=True, - manual_run=True, - can_run_manually=True, - timeout=300, - run=Mock(), - ), - }, - ) - def test_run_single_task_success(self, mock_enqueue, client, access_token): + def test_run_single_task_success( + self, mock_enqueue, client, access_token, mock_task, task_worker_listening + ): """Test successful running of a single task""" - response = client.post( - "/api/tasks/run/test_task", - headers={"Authorization": f"Bearer {access_token}"}, - ) + with patch("endpoints.tasks.RUNNABLE_TASKS", {"test_task": mock_task}): + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) assert response.status_code == status.HTTP_200_OK data = response.json() @@ -269,7 +265,26 @@ class TestRunSingleTask: assert "created_at" in data assert "enqueued_at" in data - mock_enqueue.assert_called_once() + # The worker check and the enqueue must name the same queue. + task_worker_listening.assert_called_once_with(low_prio_queue) + mock_enqueue.assert_called_once_with( + "test_task", queue=low_prio_queue, task_kwargs={} + ) + + @patch("endpoints.tasks.enqueue_task") + def test_run_single_task_without_a_worker_is_refused( + self, mock_enqueue, client, access_token, mock_task, task_worker_listening + ): + task_worker_listening.return_value = False + with patch("endpoints.tasks.RUNNABLE_TASKS", {"test_task": mock_task}): + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE + assert "worker" in response.json()["detail"] + mock_enqueue.assert_not_called() @patch("endpoints.tasks.RUNNABLE_TASKS", {}) def test_run_single_task_not_found(self, client, access_token): @@ -382,6 +397,58 @@ class TestGetTasksStatus: class TestGetTaskById: """Test suite for the get_task_by_id endpoint""" + @pytest.mark.parametrize( + "stats", + [ + CleanupMissingRomsStats(platform_ids=[3], roms_found=2, roms_deleted=2), + CleanupMissingFirmwareStats(firmware_found=1, firmware_deleted=1), + ], + ) + @patch("endpoints.tasks.Job.fetch") + def test_a_finished_cleanup_reports_its_stats( + self, mock_job_fetch, client, access_token, stats + ): + mock_job_fetch.return_value = _job_with_meta({"cleanup_stats": stats.to_dict()}) + + response = client.get( + "/api/tasks/test-job-id-123", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["meta"]["cleanup_stats"] == stats.to_dict() + + @pytest.mark.parametrize(("platform_id", "platform_ids"), [(3, [3]), (None, None)]) + @patch("endpoints.tasks.Job.fetch") + def test_a_cleanup_predating_platform_ids_reports_them( + self, mock_job_fetch, client, access_token, platform_id, platform_ids + ): + """Stats stored by an older release name a single platform.""" + mock_job_fetch.return_value = _job_with_meta( + { + # The shape 5.2.0 stored. + "cleanup_stats": { + "platform_id": platform_id, + "roms_found": 2, + "roms_deleted": 2, + "errors": 0, + }, + } + ) + + response = client.get( + "/api/tasks/test-job-id-123", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["meta"]["cleanup_stats"] == { + "platform_ids": platform_ids, + "roms_found": 2, + "roms_deleted": 2, + "errors": 0, + } + @patch("endpoints.tasks.Job.fetch") def test_get_task_by_id_success(self, mock_job_fetch, client, access_token): """Test successful retrieval of a task by job ID""" diff --git a/backend/tests/handler/test_redis_handler.py b/backend/tests/handler/test_redis_handler.py index 8ccecde33..3e2dc0804 100644 --- a/backend/tests/handler/test_redis_handler.py +++ b/backend/tests/handler/test_redis_handler.py @@ -1,5 +1,6 @@ -from unittest.mock import MagicMock, PropertyMock +from unittest.mock import MagicMock, PropertyMock, patch +import pytest from rq import Worker from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobError from rq.job import Job, JobStatus @@ -10,6 +11,8 @@ from handler.redis_handler import ( get_job_kwargs, get_job_status, get_worker_current_job, + has_live_worker, + low_prio_queue, ) @@ -112,3 +115,35 @@ class TestGetWorkerCurrentJob: worker = self._worker(side_effect=NoSuchJobError) assert get_worker_current_job(worker) is None + + +class TestHasLiveWorker: + @staticmethod + def _worker(state: str, death_date: str | None = None) -> MagicMock: + worker = MagicMock(spec=Worker) + worker.get_state.return_value = state + worker.death_date = death_date + return worker + + @pytest.mark.parametrize( + ("workers", "expected"), + [ + ([], False), + ([("suspended", None)], False), + ([("idle", "2026-09-16T10:00:00")], False), + ([("suspended", None), ("idle", None)], True), + ([("busy", None)], True), + ], + ids=["none-registered", "suspended", "announced-dead", "one-live", "busy"], + ) + def test_counts_only_workers_that_would_take_a_job( + self, workers: list[tuple[str, str | None]], expected: bool + ): + registered = [self._worker(state, death) for state, death in workers] + + with patch( + "handler.redis_handler.Worker.all", return_value=registered + ) as mock_all: + assert has_live_worker(low_prio_queue) is expected + + mock_all.assert_called_once_with(queue=low_prio_queue) diff --git a/backend/tests/utils/test_m3u.py b/backend/tests/utils/test_m3u.py index 9b43e354f..3ce9580b5 100644 --- a/backend/tests/utils/test_m3u.py +++ b/backend/tests/utils/test_m3u.py @@ -1,6 +1,6 @@ from unittest.mock import MagicMock -from utils.m3u import first_playlist_entry, generate_m3u_content +from utils.m3u import first_playlist_entry, generate_m3u_content, playlist_files class TestFirstPlaylistEntry: @@ -110,11 +110,113 @@ class TestGenerateM3uContent: assert result == b".hidden/game.chd" files[0].file_name_for_download.assert_called_once_with(True) - def test_no_cue_files_lists_all(self): + def test_no_descriptor_files_lists_all(self): files = [ _make_file("disc1.chd", "chd"), _make_file("disc2.chd", "chd"), ] result = generate_m3u_content(files, hidden_folder=False) - lines = result.decode().split("\n") - assert len(lines) == 2 + assert result == b"disc1.chd\ndisc2.chd" + + def test_gdi_preferred_over_raw_tracks(self): + files = [ + _make_file("track01.bin", "bin"), + _make_file("track02.raw", "raw"), + _make_file("game.gdi", "gdi"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"game.gdi" + + def test_ccd_preferred_over_img_and_sub(self): + files = [ + _make_file("game.img", "img"), + _make_file("game.sub", "sub"), + _make_file("game.ccd", "ccd"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"game.ccd" + + def test_mds_preferred_over_mdf(self): + files = [ + _make_file("game.mdf", "mdf"), + _make_file("game.mds", "mds"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"game.mds" + + def test_descriptor_case_insensitive(self): + files = [ + _make_file("track01.bin", "bin"), + _make_file("game.GDI", "GDI", download_name="game.GDI"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"game.GDI" + + def test_every_disc_descriptor_listed(self): + files = [ + _make_file("disc1/track01.bin", "bin"), + _make_file("disc1.gdi", "gdi"), + _make_file("disc2/track01.bin", "bin"), + _make_file("disc2.gdi", "gdi"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"disc1.gdi\ndisc2.gdi" + + def test_standalone_disc_kept_beside_a_descriptor(self): + # A set is not required to be all one format. The .gdi's tracks are + # data, but the .chd is a disc that boots on its own. + files = [ + _make_file("disc1.gdi", "gdi"), + _make_file("track01.bin", "bin"), + _make_file("disc2.chd", "chd"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"disc1.gdi\ndisc2.chd" + + def test_standalone_disc_kept_beside_a_cue(self): + files = [ + _make_file("disc1.cue", "cue"), + _make_file("disc1.bin", "bin"), + _make_file("disc2.chd", "chd"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"disc1.cue\ndisc2.chd" + + def test_audio_tracks_are_not_discs(self): + # A cue's CDDA tracks are data the sheet names, not discs beside it. + files = [ + _make_file("game.cue", "cue"), + _make_file("track01.bin", "bin"), + _make_file("track02.wav", "wav"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"game.cue" + + +class TestPlaylistFiles: + """The disc swapper reads this directly, so the files themselves matter.""" + + def test_m3u_is_never_a_disc(self): + m3u = _make_file("game.m3u", "m3u") + disc = _make_file("game.chd", "chd") + assert playlist_files([m3u, disc]) == [disc] + + def test_raw_tracks_are_not_discs(self): + track = _make_file("track01.bin", "bin") + gdi = _make_file("game.gdi", "gdi") + assert playlist_files([track, gdi]) == [gdi] + + def test_bare_files_are_all_discs(self): + discs = [_make_file("disc1.chd", "chd"), _make_file("disc2.chd", "chd")] + assert playlist_files(discs) == discs + + def test_standalone_disc_survives_a_descriptor(self): + gdi = _make_file("disc1.gdi", "gdi") + track = _make_file("track01.bin", "bin") + chd = _make_file("disc2.chd", "chd") + assert playlist_files([gdi, track, chd]) == [gdi, chd] + + def test_bare_tracks_without_a_descriptor_are_discs(self): + # Nothing describes them, so they are all there is to play. + tracks = [_make_file("track01.bin", "bin"), _make_file("track02.bin", "bin")] + assert playlist_files(tracks) == tracks diff --git a/backend/utils/m3u.py b/backend/utils/m3u.py index 363a623fe..1df11a3ee 100644 --- a/backend/utils/m3u.py +++ b/backend/utils/m3u.py @@ -6,6 +6,19 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from models.rom import RomFile +# Sheet formats that describe a disc by pointing at raw track files: .cue for +# BIN/CUE, .gdi for Dreamcast, .ccd for CloneCD and .mds for Alcohol. No one +# format is privileged over the others. +DESCRIPTOR_EXTENSIONS = frozenset({"cue", "gdi", "ccd", "mds"}) + +# The raw tracks those sheets point at, data and CDDA audio alike. None of them +# is loadable on its own, so a sheet in the set means its tracks are data rather +# than discs -- but only those tracks. Anything else present stays a disc in its +# own right. Kept in step with the shell's own list in src/main/discs/m3u.ts. +COMPANION_EXTENSIONS = frozenset( + {"bin", "raw", "img", "sub", "mdf", "wav", "ogg", "flac", "mp3"} +) + def first_playlist_entry(m3u_path: Path) -> Path | None: """Resolve an .m3u playlist to the first disc file it lists. @@ -37,14 +50,17 @@ def first_playlist_entry(m3u_path: Path) -> Path | None: def playlist_files(files: list[RomFile]) -> list[RomFile]: """The files of a multi-file ROM that name a playable disc. - The .m3u itself is never one, and where .cue files are present only those - are, since the raw .bin tracks they reference are not loadable on their own. - One home for the rule: the playlist, the download endpoint and the disc - swapper all have to agree on which files are discs. + The .m3u itself is never one. Where a descriptor is present the raw tracks + it references are not discs either, since they are not loadable alone -- + but a set is not required to be all one format, so a disc that stands on + its own (a .chd beside a .gdi) is kept. One home for the rule: the + playlist, the download endpoint and the disc swapper all have to agree on + which files are discs. """ discs = [f for f in files if f.file_extension.lower() != "m3u"] - cue_files = [f for f in discs if f.file_extension.lower() == "cue"] - return cue_files or discs + if not any(f.file_extension.lower() in DESCRIPTOR_EXTENSIONS for f in discs): + return discs + return [f for f in discs if f.file_extension.lower() not in COMPANION_EXTENSIONS] def generate_m3u_content( diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index 9039f40c7..765294970 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -1416,7 +1416,7 @@ Toggled via environment variables: ### Manual Tasks -Triggered via `POST /api/tasks/run/{task_name}`: +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 | | ---------------------- | --------------------------------------------- | diff --git a/examples/config.example.yml b/examples/config.example.yml index 5bac71808..e4a87cde1 100644 --- a/examples/config.example.yml +++ b/examples/config.example.yml @@ -182,7 +182,7 @@ # cache_limit: null # Cache limit per ROM (in bytes) # disable_batch_bootup: false # disable_auto_unload: false -# auto_save_sync: false # Upload the save to the server whenever it changes, without Save & Quit +# auto_save_sync: true # Upload the save to the server seconds after the game writes it, without Save & Quit # default_cores: # Core preselected per platform, unless overridden on the device # # Use the exact core name, as listed for the platform in the docs # nds: desmume diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 95ca60ceb..7ef424937 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -130,6 +130,7 @@ export type { MemoryCardVersionSchema } from './models/MemoryCardVersionSchema'; export type { MetadataCoverageItem } from './models/MetadataCoverageItem'; export type { MetadataMediaType } from './models/MetadataMediaType'; export type { MetadataSourcesDict } from './models/MetadataSourcesDict'; +export type { MissingFirmwareCleanupStats } from './models/MissingFirmwareCleanupStats'; export type { MissingRomsCleanupStats } from './models/MissingRomsCleanupStats'; export type { MobyMetadataPlatform } from './models/MobyMetadataPlatform'; export type { MusicGameFacetSchema } from './models/MusicGameFacetSchema'; diff --git a/frontend/src/__generated__/models/CleanupTaskMeta.ts b/frontend/src/__generated__/models/CleanupTaskMeta.ts index ad55db405..1e0897265 100644 --- a/frontend/src/__generated__/models/CleanupTaskMeta.ts +++ b/frontend/src/__generated__/models/CleanupTaskMeta.ts @@ -2,9 +2,10 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ +import type { MissingFirmwareCleanupStats } from './MissingFirmwareCleanupStats'; import type { MissingRomsCleanupStats } from './MissingRomsCleanupStats'; import type { OrphanedResourcesCleanupStats } from './OrphanedResourcesCleanupStats'; export type CleanupTaskMeta = { - cleanup_stats: (OrphanedResourcesCleanupStats | MissingRomsCleanupStats | null); + cleanup_stats: (OrphanedResourcesCleanupStats | MissingRomsCleanupStats | MissingFirmwareCleanupStats | null); }; diff --git a/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts b/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts new file mode 100644 index 000000000..ed5c09be1 --- /dev/null +++ b/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts @@ -0,0 +1,11 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type MissingFirmwareCleanupStats = { + platform_ids: (Array | null); + firmware_found: number; + firmware_deleted: number; + errors: number; +}; + diff --git a/frontend/src/__generated__/models/MissingRomsCleanupStats.ts b/frontend/src/__generated__/models/MissingRomsCleanupStats.ts index ced1b85cb..59d8bffc4 100644 --- a/frontend/src/__generated__/models/MissingRomsCleanupStats.ts +++ b/frontend/src/__generated__/models/MissingRomsCleanupStats.ts @@ -3,7 +3,7 @@ /* tslint:disable */ /* eslint-disable */ export type MissingRomsCleanupStats = { - platform_id: (number | null); + platform_ids: (Array | null); roms_found: number; roms_deleted: number; errors: number; diff --git a/frontend/src/__generated__/models/UploadTargetPayload.ts b/frontend/src/__generated__/models/UploadTargetPayload.ts index 7be852bc9..a4b24158f 100644 --- a/frontend/src/__generated__/models/UploadTargetPayload.ts +++ b/frontend/src/__generated__/models/UploadTargetPayload.ts @@ -4,13 +4,24 @@ /* eslint-disable */ /** * Optional body of `/start`: upload into a ROM's folder instead of the - * platform folder. + * platform folder, and name the file where the header cannot. */ export type UploadTargetPayload = { - rom_id: number; + /** + * Upload into this ROM's folder instead of the platform folder. + */ + rom_id?: (number | null); /** * Subfolder inside the ROM's folder, relative and forward-slashed. Empty for the root. */ folder?: string; + /** + * The file name. Takes precedence over the header, which cannot carry characters outside Latin-1. + */ + filename?: (string | null); + /** + * Replace a file of the same name in the ROM's folder instead of refusing the upload. + */ + overwrite?: boolean; }; diff --git a/frontend/src/console/views/Play.vue b/frontend/src/console/views/Play.vue index 46ae447ee..2616e1712 100644 --- a/frontend/src/console/views/Play.vue +++ b/frontend/src/console/views/Play.vue @@ -12,10 +12,7 @@ import { } from "vue"; import { useI18n } from "vue-i18n"; import { useRoute, useRouter } from "vue-router"; -import type { - Body_add_state_api_states_post as AddStateInput, - FirmwareSchema, -} from "@/__generated__"; +import type { FirmwareSchema } from "@/__generated__"; import NavigationText from "@/console/components/NavigationText.vue"; import { useInputScope } from "@/console/composables/useInputScope"; import { useThemeAssets } from "@/console/composables/useThemeAssets"; @@ -35,7 +32,10 @@ import { areThreadsRequiredForEJSCore, getDownloadPath, } from "@/utils"; -import { buildFormInput } from "@/utils/formData"; +import { + buildStateFormData, + resolveStateScreenshot, +} from "@/views/Player/EmulatorJS/utils"; import { installEJSDefaultOptionsTrap, invalidateEmulatorJSRomCacheIfRenamed, @@ -530,20 +530,14 @@ async function boot() { // Set up EmulatorJS callbacks window.EJS_onSaveState = async function ({ state: stateFile, - screenshot: screenshotFile, + screenshot: emulatorScreenshot, }: { state: ArrayBuffer; - screenshot: ArrayBuffer; + screenshot?: ArrayBuffer; }) { + const screenshotFile = await resolveStateScreenshot(emulatorScreenshot); try { - const formData = buildFormInput([ - ["stateFile", new Blob([stateFile]), "state.save"], - [ - "screenshotFile", - new Blob([screenshotFile], { type: "image/png" }), - "screenshot.png", - ], - ]); + const formData = buildStateFormData(stateFile, screenshotFile); await api.post("/states", formData, { headers: { "Content-Type": "multipart/form-data" }, diff --git a/frontend/src/locales/bg_BG/common.json b/frontend/src/locales/bg_BG/common.json index 38045fe4f..2b3797aa9 100644 --- a/frontend/src/locales/bg_BG/common.json +++ b/frontend/src/locales/bg_BG/common.json @@ -100,6 +100,7 @@ "not-linked": "Не е свързано", "offline": "Офлайн", "online": "Онлайн", + "overwrite": "Презапиши", "owned": "Притежавани", "page": "Страница", "password-length": "Паролата трябва да е между 6 и 255 символа", diff --git a/frontend/src/locales/bg_BG/rom.json b/frontend/src/locales/bg_BG/rom.json index c788951ec..4d5fba7ba 100644 --- a/frontend/src/locales/bg_BG/rom.json +++ b/frontend/src/locales/bg_BG/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Завършеност", "metric-difficulty": "Трудност", "metric-rating": "Оценка", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Липсваща платформа от файловата система", "more-actions": "Още действия", "my-notes": "Моите бележки", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Няма намерени бързи записи", "no-states-uploaded": "Не са качени бързи записи.", - "no-tracks-uploaded": "Не са качени песни.", "note-content": "Съдържание на бележката", "note-title": "Заглавие на бележката", "note-title-exists": "Вече съществува бележка с това заглавие", @@ -471,8 +471,6 @@ "title-id": "ID на заглавието", "tracks-n": "{n} песен | {n} песни", "tracks-summary": "{count} песни · {duration}", - "tracks-uploaded-n": "Качена е {n} песен. | Качени са {n} песни.", - "tracks-uploaded-with-failed": "Качена е {n} песен, {failed} неуспешни. | Качени са {n} песни, {failed} неуспешни.", "unmatch": "Премахни разпознаването", "unmatch-success": "Разпознаването на ROM-а е премахнато успешно", "unselect-all": "Премахни избора на всички", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Нова папка…", "upload-new-folder-hint": "Спрямо папката на играта, напр. hack/v2", + "upload-overwrite-body": "{names} вече съществува в тази папка и ще бъде заменен от новото качване. | {names} вече съществуват в тази папка и ще бъдат заменени от новите качвания.", + "upload-overwrite-title": "Презаписване на {n} съществуващ файл? | Презаписване на {n} съществуващи файла?", "upload-saves": "Качи записи", "upload-screenshots": "Качи екранни снимки", "upload-slot-hint": "Записите в слот се синхронизират с устройствата; без слот файлът остава ръчен архив.", diff --git a/frontend/src/locales/bg_BG/settings.json b/frontend/src/locales/bg_BG/settings.json index 1438be469..5383b7dc1 100644 --- a/frontend/src/locales/bg_BG/settings.json +++ b/frontend/src/locales/bg_BG/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Това ще изтрие окончателно всички липсващи ROM-ове{platform} от базата данни и техните директории. Това действие е необратимо.", "cleanup-firmware-confirm": "Това ще изтрие окончателно всеки запис за фърмуер{platform}, чийто файл липсва от файловата система. Нищо няма да бъде премахнато от диска.", "cleanup-firmware-queued": "Задачата за почистване е на опашка, липсващият фърмуер ще бъде изтрит скоро", - "cleanup-queued": "Задачата за почистване е на опашка — липсващите ROM-ове ще бъдат изтрити скоро", + "cleanup-queued": "Задачата за почистване е на опашка, липсващите ROM-ове ще бъдат изтрити скоро", "client-api-tokens": "API токени", "client-token-confirm-delete": "Сигурен ли си, че искаш да отмениш този токен? Всички устройства които го използват ще загубят достъп.", "client-token-confirm-regenerate": "Това ще анулира текущия токен. Всички устройства използващи стария токен ще трябва да се сдвоят отново.", diff --git a/frontend/src/locales/cs_CZ/common.json b/frontend/src/locales/cs_CZ/common.json index c5a9c5179..c5ec0b811 100644 --- a/frontend/src/locales/cs_CZ/common.json +++ b/frontend/src/locales/cs_CZ/common.json @@ -100,6 +100,7 @@ "not-linked": "Nepropojeno", "offline": "Offline", "online": "Online", + "overwrite": "Přepsat", "owned": "Vlastněno", "page": "Stránka", "password-length": "Heslo musí mít 6 až 255 znaků", diff --git a/frontend/src/locales/cs_CZ/rom.json b/frontend/src/locales/cs_CZ/rom.json index dc81473e6..7ec6c40c1 100644 --- a/frontend/src/locales/cs_CZ/rom.json +++ b/frontend/src/locales/cs_CZ/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Dokončení", "metric-difficulty": "Obtížnost", "metric-rating": "Hodnocení", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Chybějící platforma ze souborového systému", "more-actions": "Další akce", "my-notes": "Mé poznámky", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Nebyly nalezeny žádné stavy", "no-states-uploaded": "Žádné stavy nebyly nahrány.", - "no-tracks-uploaded": "Žádné skladby nebyly nahrány.", "note-content": "Obsah poznámky", "note-title": "Název poznámky", "note-title-exists": "Poznámka s tímto názvem již existuje", @@ -471,8 +471,6 @@ "title-id": "ID titulu", "tracks-n": "{n} skladeb | {n} skladba | {n} skladby | {n} skladeb", "tracks-summary": "{count} skladeb · {duration}", - "tracks-uploaded-n": "Nahráno {n} skladeb. | Nahrána {n} skladba. | Nahrány {n} skladby. | Nahráno {n} skladeb.", - "tracks-uploaded-with-failed": "Nahráno {n} skladeb, {failed} selhalo. | Nahrána {n} skladba, {failed} selhalo. | Nahrány {n} skladby, {failed} selhalo. | Nahráno {n} skladeb, {failed} selhalo.", "unmatch": "Odpojit ROM", "unmatch-success": "ROM úspěšně odpojena", "unselect-all": "Zrušit výběr všeho", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Nová složka…", "upload-new-folder-hint": "Relativně ke složce hry, např. hack/v2", + "upload-overwrite-body": "{names} v této složce již existuje a bude nahrazen novým nahráním. | {names} v této složce již existují a budou nahrazeny novými nahráními.", + "upload-overwrite-title": "Přepsat {n} existující soubor? | Přepsat {n} existující soubory?", "upload-saves": "Nahrát uložené pozice", "upload-screenshots": "Nahrát screenshoty", "upload-slot-hint": "Uložené pozice ve slotu se synchronizují se zařízeními; bez slotu zůstává soubor ručním archivem.", diff --git a/frontend/src/locales/cs_CZ/settings.json b/frontend/src/locales/cs_CZ/settings.json index 8dc1bf679..c4166b911 100644 --- a/frontend/src/locales/cs_CZ/settings.json +++ b/frontend/src/locales/cs_CZ/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Tímto se z databáze trvale odstraní každý záznam firmwaru{platform}, jehož soubor v souborovém systému chybí. Na disku se nic nesmaže.", "cleanup-firmware-queued": "Úloha vyčištění zařazena do fronty, chybějící firmware bude brzy smazán", - "cleanup-queued": "Úloha vyčištění zařazena do fronty — chybějící ROMy budou brzy smazány", + "cleanup-queued": "Úloha vyčištění zařazena do fronty, chybějící ROMy budou brzy smazány", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/de_DE/common.json b/frontend/src/locales/de_DE/common.json index b9440ff09..791856f4c 100644 --- a/frontend/src/locales/de_DE/common.json +++ b/frontend/src/locales/de_DE/common.json @@ -100,6 +100,7 @@ "not-linked": "Nicht verknüpft", "offline": "Offline", "online": "Online", + "overwrite": "Überschreiben", "owned": "Besitz", "page": "Seite", "password-length": "Passwort muss zwischen 6 und 255 Zeichen lang sein", diff --git a/frontend/src/locales/de_DE/rom.json b/frontend/src/locales/de_DE/rom.json index 37156652a..a695a2f06 100644 --- a/frontend/src/locales/de_DE/rom.json +++ b/frontend/src/locales/de_DE/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Abschluss", "metric-difficulty": "Schwierigkeit", "metric-rating": "Bewertung", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Plattform im Dateisystem fehlt", "more-actions": "Weitere Aktionen", "my-notes": "Meine Notizen", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Keine Spielstände gefunden", "no-states-uploaded": "Keine Zustände wurden hochgeladen.", - "no-tracks-uploaded": "Keine Tracks wurden hochgeladen.", "note-content": "Notiz-Inhalt", "note-title": "Notiz-Titel", "note-title-exists": "Eine Notiz mit diesem Titel existiert bereits", @@ -471,8 +471,6 @@ "title-id": "Titel-ID", "tracks-n": "{n} Track | {n} Tracks", "tracks-summary": "{count} Tracks · {duration}", - "tracks-uploaded-n": "{n} Track hochgeladen. | {n} Tracks hochgeladen.", - "tracks-uploaded-with-failed": "{n} Track hochgeladen, {failed} fehlgeschlagen. | {n} Tracks hochgeladen, {failed} fehlgeschlagen.", "unmatch": "Zuweisung aufheben", "unmatch-success": "ROM-Zuweisung erfolgreich aufgehoben", "unselect-all": "Alles abwählen", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Neuer Ordner…", "upload-new-folder-hint": "Relativ zum Spielordner, z. B. hack/v2", + "upload-overwrite-body": "{names} existiert bereits in diesem Ordner und wird durch den neuen Upload ersetzt. | {names} existieren bereits in diesem Ordner und werden durch die neuen Uploads ersetzt.", + "upload-overwrite-title": "{n} vorhandene Datei überschreiben? | {n} vorhandene Dateien überschreiben?", "upload-saves": "Spielstände hochladen", "upload-screenshots": "Screenshots hochladen", "upload-slot-hint": "Spielstände in einem Slot nehmen an der Gerätesynchronisierung teil; ohne Slot bleibt die Datei ein manuelles Archiv.", diff --git a/frontend/src/locales/de_DE/settings.json b/frontend/src/locales/de_DE/settings.json index ffca1a99c..00105af77 100644 --- a/frontend/src/locales/de_DE/settings.json +++ b/frontend/src/locales/de_DE/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Dadurch wird jeder Firmware-Eintrag{platform}, dessen Datei im Dateisystem fehlt, dauerhaft aus der Datenbank gelöscht. Auf der Festplatte wird nichts entfernt.", "cleanup-firmware-queued": "Bereinigungsaufgabe in Warteschlange, fehlende Firmware wird in Kürze gelöscht", - "cleanup-queued": "Bereinigungsaufgabe in Warteschlange — fehlende ROMs werden in Kürze gelöscht", + "cleanup-queued": "Bereinigungsaufgabe in Warteschlange, fehlende ROMs werden in Kürze gelöscht", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/en_GB/common.json b/frontend/src/locales/en_GB/common.json index 182d59172..a5bfc1bd9 100644 --- a/frontend/src/locales/en_GB/common.json +++ b/frontend/src/locales/en_GB/common.json @@ -100,6 +100,7 @@ "not-linked": "Not linked", "offline": "Offline", "online": "Online", + "overwrite": "Overwrite", "owned": "Owned", "page": "Page", "password-length": "Password must be between 6 and 255 characters", diff --git a/frontend/src/locales/en_GB/rom.json b/frontend/src/locales/en_GB/rom.json index 2b7b0d2c7..e18833362 100644 --- a/frontend/src/locales/en_GB/rom.json +++ b/frontend/src/locales/en_GB/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Completion", "metric-difficulty": "Difficulty", "metric-rating": "Rating", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Missing platform from filesystem", "more-actions": "More actions", "my-notes": "My notes", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "No states found", "no-states-uploaded": "No states were uploaded.", - "no-tracks-uploaded": "No tracks were uploaded.", "note-content": "Note Content", "note-title": "Note Title", "note-title-exists": "A note with this title already exists", @@ -471,8 +471,6 @@ "title-id": "Title ID", "tracks-n": "{n} track | {n} tracks", "tracks-summary": "{count} tracks · {duration}", - "tracks-uploaded-n": "Uploaded {n} track. | Uploaded {n} tracks.", - "tracks-uploaded-with-failed": "Uploaded {n} track, {failed} failed. | Uploaded {n} tracks, {failed} failed.", "unmatch": "Unmatch ROM", "unmatch-success": "ROM unmatched successfully", "unselect-all": "Unselect all", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "New folder…", "upload-new-folder-hint": "Relative to the game folder, e.g. hack/v2", + "upload-overwrite-body": "{names} already exists in this folder and will be replaced by the new upload. | {names} already exist in this folder and will be replaced by the new uploads.", + "upload-overwrite-title": "Overwrite {n} existing file? | Overwrite {n} existing files?", "upload-saves": "Upload saves", "upload-screenshots": "Upload screenshots", "upload-slot-hint": "Slotted saves join device sync; without a slot the file stays a manual archive.", diff --git a/frontend/src/locales/en_GB/settings.json b/frontend/src/locales/en_GB/settings.json index f7817aa26..aa03d137f 100644 --- a/frontend/src/locales/en_GB/settings.json +++ b/frontend/src/locales/en_GB/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "This will permanently delete every firmware entry{platform} whose file is missing from the filesystem. Nothing is removed from disk.", "cleanup-firmware-queued": "Cleanup task queued, missing firmware will be deleted shortly", - "cleanup-queued": "Cleanup task queued — missing ROMs will be deleted shortly", + "cleanup-queued": "Cleanup task queued, missing ROMs will be deleted shortly", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/en_US/common.json b/frontend/src/locales/en_US/common.json index 182d59172..a5bfc1bd9 100644 --- a/frontend/src/locales/en_US/common.json +++ b/frontend/src/locales/en_US/common.json @@ -100,6 +100,7 @@ "not-linked": "Not linked", "offline": "Offline", "online": "Online", + "overwrite": "Overwrite", "owned": "Owned", "page": "Page", "password-length": "Password must be between 6 and 255 characters", diff --git a/frontend/src/locales/en_US/rom.json b/frontend/src/locales/en_US/rom.json index 61cdebea1..8c49a65a9 100644 --- a/frontend/src/locales/en_US/rom.json +++ b/frontend/src/locales/en_US/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Completion", "metric-difficulty": "Difficulty", "metric-rating": "Rating", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Missing platform from filesystem", "more-actions": "More actions", "my-notes": "My notes", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "No states found", "no-states-uploaded": "No states were uploaded.", - "no-tracks-uploaded": "No tracks were uploaded.", "note-content": "Note Content", "note-title": "Note Title", "note-title-exists": "A note with this title already exists", @@ -471,8 +471,6 @@ "title-id": "Title ID", "tracks-n": "{n} track | {n} tracks", "tracks-summary": "{count} tracks · {duration}", - "tracks-uploaded-n": "Uploaded {n} track. | Uploaded {n} tracks.", - "tracks-uploaded-with-failed": "Uploaded {n} track, {failed} failed. | Uploaded {n} tracks, {failed} failed.", "unmatch": "Unmatch ROM", "unmatch-success": "ROM unmatched successfully", "unselect-all": "Unselect all", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "New folder…", "upload-new-folder-hint": "Relative to the game folder, e.g. hack/v2", + "upload-overwrite-body": "{names} already exists in this folder and will be replaced by the new upload. | {names} already exist in this folder and will be replaced by the new uploads.", + "upload-overwrite-title": "Overwrite {n} existing file? | Overwrite {n} existing files?", "upload-saves": "Upload saves", "upload-screenshots": "Upload screenshots", "upload-slot-hint": "Slotted saves join device sync; without a slot the file stays a manual archive.", diff --git a/frontend/src/locales/en_US/settings.json b/frontend/src/locales/en_US/settings.json index 4c4387247..c7b8dc7cb 100644 --- a/frontend/src/locales/en_US/settings.json +++ b/frontend/src/locales/en_US/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "This will permanently delete every firmware entry{platform} whose file is missing from the filesystem. Nothing is removed from disk.", "cleanup-firmware-queued": "Cleanup task queued, missing firmware will be deleted shortly", - "cleanup-queued": "Cleanup task queued — missing ROMs will be deleted shortly", + "cleanup-queued": "Cleanup task queued, missing ROMs will be deleted shortly", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/es_ES/common.json b/frontend/src/locales/es_ES/common.json index 2f3e8c7ce..ce0fa4ed8 100644 --- a/frontend/src/locales/es_ES/common.json +++ b/frontend/src/locales/es_ES/common.json @@ -100,6 +100,7 @@ "not-linked": "Sin vincular", "offline": "Sin conexión", "online": "En línea", + "overwrite": "Sobrescribir", "owned": "En propiedad", "page": "Página", "password-length": "La contraseña debe tener entre 6 y 255 caracteres", diff --git a/frontend/src/locales/es_ES/rom.json b/frontend/src/locales/es_ES/rom.json index c7af7452c..f5b9e8ef0 100644 --- a/frontend/src/locales/es_ES/rom.json +++ b/frontend/src/locales/es_ES/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Completado", "metric-difficulty": "Dificultad", "metric-rating": "Valoración", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Plataforma ausente en el sistema de archivos", "more-actions": "Más acciones", "my-notes": "Mis notas", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "No se encontraron estados", "no-states-uploaded": "Aún no hay estados subidos", - "no-tracks-uploaded": "Aún no hay pistas subidas", "note-content": "Contenido de la Nota", "note-title": "Título de la Nota", "note-title-exists": "Ya existe una nota con este título", @@ -471,8 +471,6 @@ "title-id": "ID del título", "tracks-n": "{n} pista | {n} pistas", "tracks-summary": "{tracks}, {duration}", - "tracks-uploaded-n": "{n} pista subida | {n} pistas subidas", - "tracks-uploaded-with-failed": "{n} pista subida, {failed} con error | {n} pistas subidas, {failed} con error", "unmatch": "Desvincular ROM", "unmatch-success": "ROM desvinculada con éxito", "unselect-all": "Deseleccionar todos", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Nueva carpeta…", "upload-new-folder-hint": "Relativa a la carpeta del juego, p. ej. hack/v2", + "upload-overwrite-body": "{names} ya existe en esta carpeta y se reemplazará con la nueva subida. | {names} ya existen en esta carpeta y se reemplazarán con las nuevas subidas.", + "upload-overwrite-title": "¿Sobrescribir {n} archivo existente? | ¿Sobrescribir {n} archivos existentes?", "upload-saves": "Subir partidas", "upload-screenshots": "Subir capturas", "upload-slot-hint": "Las partidas con ranura entran en la sincronización de dispositivos; sin ranura el archivo queda como copia manual.", diff --git a/frontend/src/locales/es_ES/settings.json b/frontend/src/locales/es_ES/settings.json index f7d2de8ea..d0569c26e 100644 --- a/frontend/src/locales/es_ES/settings.json +++ b/frontend/src/locales/es_ES/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Esto eliminará permanentemente de la base de datos cada entrada de firmware{platform} cuyo archivo falte en el sistema de archivos. No se elimina nada del disco.", "cleanup-firmware-queued": "Tarea de limpieza en cola, el firmware ausente se eliminará en breve", - "cleanup-queued": "Tarea de limpieza en cola — las ROMs ausentes se eliminarán en breve", + "cleanup-queued": "Tarea de limpieza en cola, las ROMs ausentes se eliminarán en breve", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/fr_FR/common.json b/frontend/src/locales/fr_FR/common.json index c6843a9c4..ebc316d6f 100644 --- a/frontend/src/locales/fr_FR/common.json +++ b/frontend/src/locales/fr_FR/common.json @@ -100,6 +100,7 @@ "not-linked": "Non associé", "offline": "Hors ligne", "online": "En ligne", + "overwrite": "Écraser", "owned": "Possédé", "page": "Page", "password-length": "Le mot de passe doit contenir entre 6 et 255 caractères", diff --git a/frontend/src/locales/fr_FR/rom.json b/frontend/src/locales/fr_FR/rom.json index a8926070b..e3a9dea68 100644 --- a/frontend/src/locales/fr_FR/rom.json +++ b/frontend/src/locales/fr_FR/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Complétion", "metric-difficulty": "Difficulté", "metric-rating": "Note", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Plateforme manquante du système de fichiers", "more-actions": "Plus d'actions", "my-notes": "Mes notes", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Aucun état trouvé", "no-states-uploaded": "Aucun état n'a été téléversé.", - "no-tracks-uploaded": "Aucune piste n'a été téléversée.", "note-content": "Contenu de la Note", "note-title": "Titre de la Note", "note-title-exists": "Une note avec ce titre existe déjà", @@ -471,8 +471,6 @@ "title-id": "ID du titre", "tracks-n": "{n} piste | {n} pistes", "tracks-summary": "{count} pistes · {duration}", - "tracks-uploaded-n": "{n} piste téléversée. | {n} pistes téléversées.", - "tracks-uploaded-with-failed": "{n} piste téléversée, {failed} en échec. | {n} pistes téléversées, {failed} en échec.", "unmatch": "Dissocier le ROM", "unmatch-success": "ROM dissociée avec succès", "unselect-all": "Désélectionner tous", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Nouveau dossier…", "upload-new-folder-hint": "Relatif au dossier du jeu, par ex. hack/v2", + "upload-overwrite-body": "{names} existe déjà dans ce dossier et sera remplacé par le nouvel envoi. | {names} existent déjà dans ce dossier et seront remplacés par les nouveaux envois.", + "upload-overwrite-title": "Écraser {n} fichier existant ? | Écraser {n} fichiers existants ?", "upload-saves": "Téléverser des sauvegardes", "upload-screenshots": "Téléverser des captures d'écran", "upload-slot-hint": "Les sauvegardes dans un emplacement rejoignent la synchronisation des appareils ; sans emplacement, le fichier reste une archive manuelle.", diff --git a/frontend/src/locales/fr_FR/settings.json b/frontend/src/locales/fr_FR/settings.json index b40745ca7..44a925f2d 100644 --- a/frontend/src/locales/fr_FR/settings.json +++ b/frontend/src/locales/fr_FR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Cette action supprimera définitivement de la base de données chaque entrée de firmware{platform} dont le fichier est absent du système de fichiers. Rien n'est supprimé du disque.", "cleanup-firmware-queued": "Tâche de nettoyage mise en file d'attente, les firmwares manquants seront supprimés sous peu", - "cleanup-queued": "Tâche de nettoyage mise en file d'attente — les ROMs manquantes seront supprimées sous peu", + "cleanup-queued": "Tâche de nettoyage mise en file d'attente, les ROMs manquantes seront supprimées sous peu", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/hu_HU/common.json b/frontend/src/locales/hu_HU/common.json index 1658cd48f..3eb6def12 100644 --- a/frontend/src/locales/hu_HU/common.json +++ b/frontend/src/locales/hu_HU/common.json @@ -100,6 +100,7 @@ "not-linked": "Nincs összekötve", "offline": "Offline", "online": "Online", + "overwrite": "Felülírás", "owned": "Tulajdonolt", "page": "Oldal", "password-length": "A jelszó hossza 6 és 255 karakter hosszú lehet", diff --git a/frontend/src/locales/hu_HU/rom.json b/frontend/src/locales/hu_HU/rom.json index 9e1b8c12d..41ca20502 100644 --- a/frontend/src/locales/hu_HU/rom.json +++ b/frontend/src/locales/hu_HU/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Befejezés", "metric-difficulty": "Nehézség", "metric-rating": "Értékelés", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Hiányzó platform a fájlrendszerből", "more-actions": "További műveletek", "my-notes": "Jegyzeteim", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Nem található állás", "no-states-uploaded": "Egyetlen állás sem lett feltöltve.", - "no-tracks-uploaded": "Egyetlen szám sem lett feltöltve.", "note-content": "Megjegyzés tartalma", "note-title": "Megjegyzés címe", "note-title-exists": "Már létezik egy ilyen címmel ellátott jegyzet", @@ -471,8 +471,6 @@ "title-id": "Cím ID", "tracks-n": "{n} szám | {n} szám", "tracks-summary": "{count} szám · {duration}", - "tracks-uploaded-n": "{n} szám feltöltve. | {n} szám feltöltve.", - "tracks-uploaded-with-failed": "{n} szám feltöltve, {failed} sikertelen. | {n} szám feltöltve, {failed} sikertelen.", "unmatch": "Nem egyező ROM", "unmatch-success": "A ROM sikeresen nem egyeztetettként lett jelölve", "unselect-all": "Minden kijelölés visszavonása", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Új mappa…", "upload-new-folder-hint": "A játék mappájához képest, pl. hack/v2", + "upload-overwrite-body": "{names} már létezik ebben a mappában, és az új feltöltés felülírja. | {names} már léteznek ebben a mappában, és az új feltöltések felülírják.", + "upload-overwrite-title": "Felülírja a(z) {n} meglévő fájlt? | Felülírja a(z) {n} meglévő fájlt?", "upload-saves": "Mentések feltöltése", "upload-screenshots": "Képernyőképek feltöltése", "upload-slot-hint": "A helyre tett mentések részt vesznek az eszközszinkronban; hely nélkül a fájl kézi archívum marad.", diff --git a/frontend/src/locales/hu_HU/settings.json b/frontend/src/locales/hu_HU/settings.json index 61248d518..f9ed2f981 100644 --- a/frontend/src/locales/hu_HU/settings.json +++ b/frontend/src/locales/hu_HU/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Ez véglegesen törli az adatbázisból minden olyan firmware-bejegyzést{platform}, amelynek a fájlja hiányzik a fájlrendszerből. A lemezről semmi sem törlődik.", "cleanup-firmware-queued": "Takarítási feladat sorba állítva, a hiányzó firmware hamarosan törlődik", - "cleanup-queued": "Takarítási feladat sorba állítva — a hiányzó ROM-ok hamarosan törlődnek", + "cleanup-queued": "Takarítási feladat sorba állítva, a hiányzó ROM-ok hamarosan törlődnek", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/it_IT/common.json b/frontend/src/locales/it_IT/common.json index 02ae92876..d200eec8c 100644 --- a/frontend/src/locales/it_IT/common.json +++ b/frontend/src/locales/it_IT/common.json @@ -100,6 +100,7 @@ "not-linked": "Non collegato", "offline": "Offline", "online": "Online", + "overwrite": "Sovrascrivi", "owned": "Posseduti", "page": "Pagina", "password-length": "La password deve essere compresa tra 6 e 255 caratteri", diff --git a/frontend/src/locales/it_IT/rom.json b/frontend/src/locales/it_IT/rom.json index 07a1550ff..6f77c6e1e 100644 --- a/frontend/src/locales/it_IT/rom.json +++ b/frontend/src/locales/it_IT/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Completamento", "metric-difficulty": "Difficoltà", "metric-rating": "Valutazione", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Piattaforma mancante dal filesystem", "more-actions": "Altre azioni", "my-notes": "Mie note", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Nessun stato trovato", "no-states-uploaded": "Nessuno stato caricato.", - "no-tracks-uploaded": "Nessuna traccia caricata.", "note-content": "Contenuto della Nota", "note-title": "Titolo della Nota", "note-title-exists": "Una nota con questo titolo esiste già", @@ -471,8 +471,6 @@ "title-id": "ID titolo", "tracks-n": "{n} traccia | {n} tracce", "tracks-summary": "{count} tracce · {duration}", - "tracks-uploaded-n": "Caricata {n} traccia. | Caricate {n} tracce.", - "tracks-uploaded-with-failed": "Caricata {n} traccia, {failed} fallite. | Caricate {n} tracce, {failed} fallite.", "unmatch": "Rimuovi associazione rom", "unmatch-success": "Associazione ROM rimossa con successo", "unselect-all": "Deseleziona tutto", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Nuova cartella…", "upload-new-folder-hint": "Relativo alla cartella del gioco, es. hack/v2", + "upload-overwrite-body": "{names} esiste già in questa cartella e verrà sostituito dal nuovo caricamento. | {names} esistono già in questa cartella e verranno sostituiti dai nuovi caricamenti.", + "upload-overwrite-title": "Sovrascrivere {n} file esistente? | Sovrascrivere {n} file esistenti?", "upload-saves": "Carica salvataggi", "upload-screenshots": "Carica screenshot", "upload-slot-hint": "I salvataggi in uno slot entrano nella sincronizzazione dei dispositivi; senza slot il file resta un archivio manuale.", diff --git a/frontend/src/locales/it_IT/settings.json b/frontend/src/locales/it_IT/settings.json index e0d1ad6b2..36cdbe4c1 100644 --- a/frontend/src/locales/it_IT/settings.json +++ b/frontend/src/locales/it_IT/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Questa azione eliminerà definitivamente dal database ogni voce di firmware{platform} il cui file manca dal filesystem. Nulla viene rimosso dal disco.", "cleanup-firmware-queued": "Attività di pulizia accodata, il firmware mancante verrà eliminato a breve", - "cleanup-queued": "Attività di pulizia accodata — le ROM mancanti verranno eliminate a breve", + "cleanup-queued": "Attività di pulizia accodata, le ROM mancanti verranno eliminate a breve", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ja_JP/common.json b/frontend/src/locales/ja_JP/common.json index c7248684c..d1b2a925e 100644 --- a/frontend/src/locales/ja_JP/common.json +++ b/frontend/src/locales/ja_JP/common.json @@ -100,6 +100,7 @@ "not-linked": "未連携", "offline": "オフライン", "online": "オンライン", + "overwrite": "上書き", "owned": "所有", "page": "ページ", "password-length": "パスワードは6文字から255文字の間である必要があります", diff --git a/frontend/src/locales/ja_JP/rom.json b/frontend/src/locales/ja_JP/rom.json index ded5e27a7..bb520ecfd 100644 --- a/frontend/src/locales/ja_JP/rom.json +++ b/frontend/src/locales/ja_JP/rom.json @@ -242,6 +242,7 @@ "metric-completion": "完了度", "metric-difficulty": "難易度", "metric-rating": "評価", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "ファイルシステムにプラットフォームが存在しません", "more-actions": "その他の操作", "my-notes": "メモ", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "ステートセーブが見つかりません", "no-states-uploaded": "アップロードされたステートセーブはありません。", - "no-tracks-uploaded": "アップロードされたトラックはありません。", "note-content": "ノート内容", "note-title": "ノートタイトル", "note-title-exists": "このタイトルのノートがすでに存在します", @@ -471,8 +471,6 @@ "title-id": "タイトルID", "tracks-n": "{n}件のトラック | {n}件のトラック", "tracks-summary": "{count}件のトラック · {duration}", - "tracks-uploaded-n": "{n}件のトラックをアップロードしました。 | {n}件のトラックをアップロードしました。", - "tracks-uploaded-with-failed": "{n}件のトラックをアップロードしました。{failed}件失敗しました。 | {n}件のトラックをアップロードしました。{failed}件失敗しました。", "unmatch": "検索結果無し", "unmatch-success": "ROMの関連付けが正常に解除されました", "unselect-all": "すべて選択解除", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "新しいフォルダ…", "upload-new-folder-hint": "ゲームフォルダからの相対パス (例: hack/v2)", + "upload-overwrite-body": "{names} はこのフォルダにすでに存在し、新しいアップロードで置き換えられます。 | {names} はこのフォルダにすでに存在し、新しいアップロードで置き換えられます。", + "upload-overwrite-title": "既存の {n} 件のファイルを上書きしますか? | 既存の {n} 件のファイルを上書きしますか?", "upload-saves": "セーブをアップロード", "upload-screenshots": "スクリーンショットをアップロード", "upload-slot-hint": "スロット付きのセーブは端末間で同期されます。スロットなしのファイルは手動のアーカイブとして保持されます。", diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index 38a2e353b..f11071644 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "ファイルシステムにファイルが存在しないファームウェアの登録{platform}をデータベースから完全に削除します。ディスク上のファイルは削除されません。", "cleanup-firmware-queued": "クリーンアップタスクをキューに追加しました。不足しているファームウェアはまもなく削除されます", - "cleanup-queued": "クリーンアップタスクをキューに追加しました — 不足しているROMはまもなく削除されます", + "cleanup-queued": "クリーンアップタスクをキューに追加しました。不足しているROMはまもなく削除されます", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ko_KR/common.json b/frontend/src/locales/ko_KR/common.json index 4b1f6dab5..9d337814f 100644 --- a/frontend/src/locales/ko_KR/common.json +++ b/frontend/src/locales/ko_KR/common.json @@ -100,6 +100,7 @@ "not-linked": "연결되지 않음", "offline": "오프라인", "online": "온라인", + "overwrite": "덮어쓰기", "owned": "보유 중", "page": "페이지", "password-length": "비밀번호는 6자에서 255자 사이여야 합니다", diff --git a/frontend/src/locales/ko_KR/rom.json b/frontend/src/locales/ko_KR/rom.json index dfe85c624..e060b2245 100644 --- a/frontend/src/locales/ko_KR/rom.json +++ b/frontend/src/locales/ko_KR/rom.json @@ -242,6 +242,7 @@ "metric-completion": "완료율", "metric-difficulty": "난이도", "metric-rating": "평가", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "파일 시스템에서 누락된 플랫폼", "more-actions": "추가 작업", "my-notes": "개인 노트", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "저장 상태 없음", "no-states-uploaded": "업로드된 상태가 없습니다.", - "no-tracks-uploaded": "업로드된 트랙이 없습니다.", "note-content": "노트 내용", "note-title": "노트 제목", "note-title-exists": "이 제목의 노트가 이미 존재합니다", @@ -471,8 +471,6 @@ "title-id": "타이틀 ID", "tracks-n": "{n}개 트랙 | {n}개 트랙", "tracks-summary": "{count}개 트랙 · {duration}", - "tracks-uploaded-n": "{n}개 트랙을 업로드했습니다. | {n}개 트랙을 업로드했습니다.", - "tracks-uploaded-with-failed": "{n}개 트랙을 업로드했습니다, {failed}개 실패. | {n}개 트랙을 업로드했습니다, {failed}개 실패.", "unmatch": "DB 대응 해제", "unmatch-success": "ROM 연결이 성공적으로 해제되었습니다", "unselect-all": "모두 선택 해제", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "새 폴더…", "upload-new-folder-hint": "게임 폴더 기준 상대 경로, 예: hack/v2", + "upload-overwrite-body": "{names}은(는) 이 폴더에 이미 존재하며 새 업로드로 대체됩니다. | {names}은(는) 이 폴더에 이미 존재하며 새 업로드로 대체됩니다.", + "upload-overwrite-title": "기존 파일 {n}개를 덮어쓸까요? | 기존 파일 {n}개를 덮어쓸까요?", "upload-saves": "세이브 업로드", "upload-screenshots": "스크린샷 업로드", "upload-slot-hint": "슬롯이 있는 세이브는 기기 동기화에 포함됩니다. 슬롯이 없으면 파일은 수동 보관본으로 남습니다.", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index 194e70318..5bf1a67fc 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "파일 시스템에서 파일이 사라진 모든 펌웨어 항목{platform}을 데이터베이스에서 영구적으로 삭제합니다. 디스크에서는 아무것도 삭제되지 않습니다.", "cleanup-firmware-queued": "정리 작업이 대기열에 추가되었습니다. 누락된 펌웨어는 곧 삭제됩니다", - "cleanup-queued": "정리 작업이 대기열에 추가되었습니다 — 누락된 ROM은 곧 삭제됩니다", + "cleanup-queued": "정리 작업이 대기열에 추가되었습니다. 누락된 ROM은 곧 삭제됩니다", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/pl_PL/common.json b/frontend/src/locales/pl_PL/common.json index 82e2560a5..79cc045d0 100644 --- a/frontend/src/locales/pl_PL/common.json +++ b/frontend/src/locales/pl_PL/common.json @@ -100,6 +100,7 @@ "not-linked": "Niepowiązane", "offline": "Offline", "online": "Online", + "overwrite": "Nadpisz", "owned": "Posiadane", "page": "Strona", "password-length": "Hasło musi mieć od 6 do 255 znaków", diff --git a/frontend/src/locales/pl_PL/rom.json b/frontend/src/locales/pl_PL/rom.json index 9653a6c92..36709b802 100644 --- a/frontend/src/locales/pl_PL/rom.json +++ b/frontend/src/locales/pl_PL/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Ukończenie", "metric-difficulty": "Trudność", "metric-rating": "Ocena", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Brakująca platforma z systemu plików", "more-actions": "Więcej akcji", "my-notes": "Moje notatki", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Nie znaleziono stanów", "no-states-uploaded": "Nie przesłano żadnych stanów.", - "no-tracks-uploaded": "Nie przesłano żadnych utworów.", "note-content": "Treść Notatki", "note-title": "Tytuł Notatki", "note-title-exists": "Notatka z tym tytułem już istnieje", @@ -471,8 +471,6 @@ "title-id": "ID tytułu", "tracks-n": "{n} utwór | {n} utwory | {n} utworów", "tracks-summary": "{count} utworów · {duration}", - "tracks-uploaded-n": "Przesłano {n} utwór. | Przesłano {n} utwory. | Przesłano {n} utworów.", - "tracks-uploaded-with-failed": "Przesłano {n} utwór, {failed} niepowodzeń. | Przesłano {n} utwory, {failed} niepowodzeń.", "unmatch": "Odłącz ROM", "unmatch-success": "ROM został pomyślnie odłączony", "unselect-all": "Odznacz wszystkie", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Nowy folder…", "upload-new-folder-hint": "Względem folderu gry, np. hack/v2", + "upload-overwrite-body": "{names} już istnieje w tym folderze i zostanie zastąpiony nowym plikiem. | {names} już istnieją w tym folderze i zostaną zastąpione nowymi plikami.", + "upload-overwrite-title": "Nadpisać {n} istniejący plik? | Nadpisać {n} istniejące pliki?", "upload-saves": "Prześlij zapisy", "upload-screenshots": "Prześlij zrzuty ekranu", "upload-slot-hint": "Zapisy w slocie biorą udział w synchronizacji urządzeń; bez slotu plik pozostaje ręcznym archiwum.", diff --git a/frontend/src/locales/pl_PL/settings.json b/frontend/src/locales/pl_PL/settings.json index 30f83fabd..57b74a7e8 100644 --- a/frontend/src/locales/pl_PL/settings.json +++ b/frontend/src/locales/pl_PL/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Spowoduje to trwałe usunięcie z bazy danych każdego wpisu oprogramowania{platform}, którego plik nie istnieje w systemie plików. Nic nie zostanie usunięte z dysku.", "cleanup-firmware-queued": "Zadanie czyszczenia w kolejce, brakujące oprogramowanie zostanie wkrótce usunięte", - "cleanup-queued": "Zadanie czyszczenia w kolejce — brakujące ROM-y zostaną wkrótce usunięte", + "cleanup-queued": "Zadanie czyszczenia w kolejce, brakujące ROM-y zostaną wkrótce usunięte", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/pt_BR/common.json b/frontend/src/locales/pt_BR/common.json index 79edf22bf..f4e940bc2 100644 --- a/frontend/src/locales/pt_BR/common.json +++ b/frontend/src/locales/pt_BR/common.json @@ -100,6 +100,7 @@ "not-linked": "Não vinculado", "offline": "Offline", "online": "Online", + "overwrite": "Sobrescrever", "owned": "Possuído", "page": "Página", "password-length": "Senha deve ter entre 6 e 255 caracteres", diff --git a/frontend/src/locales/pt_BR/rom.json b/frontend/src/locales/pt_BR/rom.json index 50888d596..d695fe14d 100644 --- a/frontend/src/locales/pt_BR/rom.json +++ b/frontend/src/locales/pt_BR/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Conclusão", "metric-difficulty": "Dificuldade", "metric-rating": "Avaliação", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Plataforma ausente do sistema de arquivos", "more-actions": "Mais ações", "my-notes": "Minhas notas", @@ -263,7 +264,6 @@ "no-soundtrack": "Nenhuma trilha sonora disponível para este jogo.", "no-states-found": "Nenhum estado encontrado", "no-states-uploaded": "Nenhum state foi enviado.", - "no-tracks-uploaded": "Nenhuma faixa foi enviada.", "note-content": "Conteúdo da Nota", "note-title": "Título da Nota", "note-title-exists": "Uma nota com esse título já existe", @@ -471,8 +471,6 @@ "title-id": "ID do título", "tracks-n": "{n} faixa | {n} faixas", "tracks-summary": "{count} faixas · {duration}", - "tracks-uploaded-n": "{n} faixa enviada. | {n} faixas enviadas.", - "tracks-uploaded-with-failed": "{n} faixa enviada, {failed} com falha. | {n} faixas enviadas, {failed} com falha.", "unmatch": "Desvincular ROM", "unmatch-success": "ROM desvinculada com sucesso", "unselect-all": "Desselecionar todos", @@ -490,6 +488,8 @@ "upload-manual": "Enviar manual", "upload-new-folder": "Nova pasta…", "upload-new-folder-hint": "Relativo à pasta do jogo, ex.: hack/v2", + "upload-overwrite-body": "{names} já existe nesta pasta e será substituído pelo novo envio. | {names} já existem nesta pasta e serão substituídos pelos novos envios.", + "upload-overwrite-title": "Sobrescrever {n} arquivo existente? | Sobrescrever {n} arquivos existentes?", "upload-saves": "Enviar saves", "upload-screenshots": "Enviar capturas de tela", "upload-slot-hint": "Saves em um slot entram na sincronização de dispositivos; sem slot o arquivo fica como cópia manual.", diff --git a/frontend/src/locales/pt_BR/settings.json b/frontend/src/locales/pt_BR/settings.json index 2a32496e9..591148603 100644 --- a/frontend/src/locales/pt_BR/settings.json +++ b/frontend/src/locales/pt_BR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Isso excluirá permanentemente do banco de dados todas as ROMs ausentes{platform} e seus diretórios de recursos. Esta ação não pode ser desfeita.", "cleanup-firmware-confirm": "Isso excluirá permanentemente do banco de dados cada entrada de firmware{platform} cujo arquivo esteja ausente no sistema de arquivos. Nada é removido do disco.", "cleanup-firmware-queued": "Tarefa de limpeza na fila, o firmware ausente será excluído em breve", - "cleanup-queued": "Tarefa de limpeza na fila — as ROMs ausentes serão excluídas em breve", + "cleanup-queued": "Tarefa de limpeza na fila, as ROMs ausentes serão excluídas em breve", "client-api-tokens": "Tokens de API de cliente", "client-token-confirm-delete": "Tem certeza de que deseja revogar este token? Qualquer dispositivo que o utilize perderá o acesso.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ro_RO/common.json b/frontend/src/locales/ro_RO/common.json index 108ff7ecd..eb1b5435e 100644 --- a/frontend/src/locales/ro_RO/common.json +++ b/frontend/src/locales/ro_RO/common.json @@ -100,6 +100,7 @@ "not-linked": "Neasociat", "offline": "Offline", "online": "Online", + "overwrite": "Suprascrie", "owned": "Deținut", "page": "Pagină", "password-length": "Parola trebuie să conțină între 6 și 255 de caractere", diff --git a/frontend/src/locales/ro_RO/rom.json b/frontend/src/locales/ro_RO/rom.json index c34b0108e..305fe9ac3 100644 --- a/frontend/src/locales/ro_RO/rom.json +++ b/frontend/src/locales/ro_RO/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Finalizare", "metric-difficulty": "Dificultate", "metric-rating": "Evaluare", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Platformă lipsă din sistemul de fișiere", "more-actions": "Mai multe acțiuni", "my-notes": "Notițele mele", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Niciun stare găsită", "no-states-uploaded": "Nicio stare nu a fost încărcată.", - "no-tracks-uploaded": "Nicio piesă nu a fost încărcată.", "note-content": "Conținutul Notației", "note-title": "Titlul Notației", "note-title-exists": "Există deja o notație cu acest titlu", @@ -471,8 +471,6 @@ "title-id": "ID titlu", "tracks-n": "{n} piesă | {n} piese", "tracks-summary": "{count} piese · {duration}", - "tracks-uploaded-n": "S-a încărcat {n} piesă. | S-au încărcat {n} piese.", - "tracks-uploaded-with-failed": "S-a încărcat {n} piesă, {failed} au eșuat. | S-au încărcat {n} piese, {failed} au eșuat.", "unmatch": "Dissociază ROM-ul", "unmatch-success": "ROM-ul a fost disociat cu succes", "unselect-all": "Deselectează toate", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Folder nou…", "upload-new-folder-hint": "Relativ la folderul jocului, de ex. hack/v2", + "upload-overwrite-body": "{names} există deja în acest folder și va fi înlocuit de noua încărcare. | {names} există deja în acest folder și vor fi înlocuite de noile încărcări.", + "upload-overwrite-title": "Suprascrii {n} fișier existent? | Suprascrii {n} fișiere existente?", "upload-saves": "Încarcă salvări", "upload-screenshots": "Încarcă capturi de ecran", "upload-slot-hint": "Salvările dintr-un slot intră în sincronizarea dispozitivelor; fără slot fișierul rămâne o arhivă manuală.", diff --git a/frontend/src/locales/ro_RO/settings.json b/frontend/src/locales/ro_RO/settings.json index 4ac3d4e8c..ed1fcbb02 100644 --- a/frontend/src/locales/ro_RO/settings.json +++ b/frontend/src/locales/ro_RO/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Aceasta va șterge definitiv din baza de date fiecare intrare de firmware{platform} al cărei fișier lipsește din sistemul de fișiere. Nu se șterge nimic de pe disc.", "cleanup-firmware-queued": "Sarcina de curățare a fost pusă în coadă, firmware-ul lipsă va fi șters în scurt timp", - "cleanup-queued": "Sarcina de curățare a fost pusă în coadă — ROM-urile lipsă vor fi șterse în scurt timp", + "cleanup-queued": "Sarcina de curățare a fost pusă în coadă, ROM-urile lipsă vor fi șterse în scurt timp", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ru_RU/common.json b/frontend/src/locales/ru_RU/common.json index fffa8623d..e9625bb78 100644 --- a/frontend/src/locales/ru_RU/common.json +++ b/frontend/src/locales/ru_RU/common.json @@ -100,6 +100,7 @@ "not-linked": "Не привязано", "offline": "Не в сети", "online": "В сети", + "overwrite": "Перезаписать", "owned": "В наличии", "page": "Страница", "password-length": "Пароль должен содержать от 6 до 255 символов", diff --git a/frontend/src/locales/ru_RU/rom.json b/frontend/src/locales/ru_RU/rom.json index 56a0b5d8f..43c61c191 100644 --- a/frontend/src/locales/ru_RU/rom.json +++ b/frontend/src/locales/ru_RU/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Прохождение", "metric-difficulty": "Сложность", "metric-rating": "Рейтинг", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Платформа отсутствует в файловой системе", "more-actions": "Ещё действия", "my-notes": "Мои заметки", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Состояний не найдено", "no-states-uploaded": "Состояния не были загружены.", - "no-tracks-uploaded": "Треки не были загружены.", "note-content": "Содержание Заметки", "note-title": "Заголовок Заметки", "note-title-exists": "Заметка с таким заголовком уже существует", @@ -471,8 +471,6 @@ "title-id": "ID тайтла", "tracks-n": "{n} трек | {n} треков", "tracks-summary": "{count} треков · {duration}", - "tracks-uploaded-n": "Загружен {n} трек. | Загружено {n} треков.", - "tracks-uploaded-with-failed": "Загружен {n} трек, {failed} с ошибкой. | Загружено {n} треков, {failed} с ошибкой.", "unmatch": "Отменить совпадение", "unmatch-success": "Связь с ROM успешно отменена", "unselect-all": "Отменить выбор всех", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Новая папка…", "upload-new-folder-hint": "Относительно папки игры, например hack/v2", + "upload-overwrite-body": "{names} уже существует в этой папке и будет заменён новой загрузкой. | {names} уже существуют в этой папке и будут заменены новыми загрузками.", + "upload-overwrite-title": "Перезаписать {n} существующий файл? | Перезаписать {n} существующих файлов?", "upload-saves": "Загрузить сохранения", "upload-screenshots": "Загрузить скриншоты", "upload-slot-hint": "Сохранения в слоте участвуют в синхронизации устройств; без слота файл остаётся ручным архивом.", diff --git a/frontend/src/locales/ru_RU/settings.json b/frontend/src/locales/ru_RU/settings.json index 56e5865b1..b0dc66c8c 100644 --- a/frontend/src/locales/ru_RU/settings.json +++ b/frontend/src/locales/ru_RU/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Это навсегда удалит из базы данных каждую запись прошивки{platform}, файл которой отсутствует в файловой системе. С диска ничего не удаляется.", "cleanup-firmware-queued": "Задача очистки поставлена в очередь, отсутствующие прошивки скоро будут удалены", - "cleanup-queued": "Задача очистки поставлена в очередь — отсутствующие ROM-ы скоро будут удалены", + "cleanup-queued": "Задача очистки поставлена в очередь, отсутствующие ROM-ы скоро будут удалены", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/tr_TR/common.json b/frontend/src/locales/tr_TR/common.json index a8a48e5f0..8e6f97ba9 100644 --- a/frontend/src/locales/tr_TR/common.json +++ b/frontend/src/locales/tr_TR/common.json @@ -100,6 +100,7 @@ "not-linked": "Bağlı değil", "offline": "Çevrimdışı", "online": "Çevrimiçi", + "overwrite": "Üzerine yaz", "owned": "Sahip olunan", "page": "Sayfa", "password-length": "Şifre 6 ile 255 karakter arasında olmalıdır", diff --git a/frontend/src/locales/tr_TR/rom.json b/frontend/src/locales/tr_TR/rom.json index 2d495233c..48c43899f 100644 --- a/frontend/src/locales/tr_TR/rom.json +++ b/frontend/src/locales/tr_TR/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Tamamlama", "metric-difficulty": "Zorluk", "metric-rating": "Puan", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Platform dosya sisteminde bulunamadı", "more-actions": "Daha fazla işlem", "my-notes": "Notlarım", @@ -263,7 +264,6 @@ "no-soundtrack": "Bu oyun için müzik paketi mevcut değil.", "no-states-found": "Durum kaydı bulunamadı", "no-states-uploaded": "Hiç durum kaydı yüklenmedi.", - "no-tracks-uploaded": "Hiç parça yüklenmedi.", "note-content": "Not İçeriği", "note-title": "Not Başlığı", "note-title-exists": "Bu başlıkta bir not zaten mevcut", @@ -471,8 +471,6 @@ "title-id": "Başlık ID", "tracks-n": "{n} parça | {n} parça", "tracks-summary": "{count} parça · {duration}", - "tracks-uploaded-n": "{n} parça yüklendi. | {n} parça yüklendi.", - "tracks-uploaded-with-failed": "{n} parça yüklendi, {failed} başarısız. | {n} parça yüklendi, {failed} başarısız.", "unmatch": "ROM eşleşmesini kaldır", "unmatch-success": "ROM eşleşmesi başarıyla kaldırıldı", "unselect-all": "Tümünün seçimini kaldır", @@ -490,6 +488,8 @@ "upload-manual": "Kılavuz yükle", "upload-new-folder": "Yeni klasör…", "upload-new-folder-hint": "Oyun klasörüne göre, örn. hack/v2", + "upload-overwrite-body": "{names} bu klasörde zaten mevcut ve yeni yüklemeyle değiştirilecek. | {names} bu klasörde zaten mevcut ve yeni yüklemelerle değiştirilecek.", + "upload-overwrite-title": "{n} mevcut dosyanın üzerine yazılsın mı? | {n} mevcut dosyanın üzerine yazılsın mı?", "upload-saves": "Kayıt yükle", "upload-screenshots": "Ekran görüntüsü yükle", "upload-slot-hint": "Yuvadaki kayıtlar cihaz eşitlemesine katılır; yuva yoksa dosya elle alınmış bir arşiv olarak kalır.", diff --git a/frontend/src/locales/tr_TR/settings.json b/frontend/src/locales/tr_TR/settings.json index e047f54b8..cb2f8171a 100644 --- a/frontend/src/locales/tr_TR/settings.json +++ b/frontend/src/locales/tr_TR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Bu işlem, veritabanından tüm eksik ROM'ları{platform} ve kaynak dizinlerini kalıcı olarak siler. Bu işlem geri alınamaz.", "cleanup-firmware-confirm": "Bu işlem, dosyası dosya sisteminde bulunmayan her firmware kaydını{platform} veritabanından kalıcı olarak siler. Diskten hiçbir şey silinmez.", "cleanup-firmware-queued": "Temizlik görevi sıraya alındı, eksik firmware kısa süre içinde silinecek", - "cleanup-queued": "Temizlik görevi sıraya alındı — eksik ROM'lar kısa süre içinde silinecek", + "cleanup-queued": "Temizlik görevi sıraya alındı, eksik ROM'lar kısa süre içinde silinecek", "client-api-tokens": "İstemci API Tokenları", "client-token-confirm-delete": "Bu tokenı iptal etmek istediğinizden emin misiniz? Kullanan tüm cihazlar erişimini kaybedecek.", "client-token-confirm-regenerate": "Bu işlem mevcut kimlik bilgisini geçersiz kılacak. Eski tokenı kullanan cihazların yeniden eşleştirilmesi gerekecek.", diff --git a/frontend/src/locales/zh_CN/common.json b/frontend/src/locales/zh_CN/common.json index c45621e78..cfbcefb53 100644 --- a/frontend/src/locales/zh_CN/common.json +++ b/frontend/src/locales/zh_CN/common.json @@ -100,6 +100,7 @@ "not-linked": "未关联", "offline": "离线", "online": "在线", + "overwrite": "覆盖", "owned": "已拥有", "page": "页", "password-length": "密码必须介于6到255个字符之间", diff --git a/frontend/src/locales/zh_CN/rom.json b/frontend/src/locales/zh_CN/rom.json index beeb4c337..4881fa163 100644 --- a/frontend/src/locales/zh_CN/rom.json +++ b/frontend/src/locales/zh_CN/rom.json @@ -242,6 +242,7 @@ "metric-completion": "完成度", "metric-difficulty": "难度", "metric-rating": "评分", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "文件系统中缺失的平台", "more-actions": "更多操作", "my-notes": "我的笔记", @@ -263,7 +264,6 @@ "no-soundtrack": "此游戏暂无原声音乐。", "no-states-found": "未找到状态", "no-states-uploaded": "未上传任何状态。", - "no-tracks-uploaded": "未上传任何曲目。", "note-content": "笔记内容", "note-title": "笔记标题", "note-title-exists": "已存在此标题的笔记", @@ -471,8 +471,6 @@ "title-id": "标题ID", "tracks-n": "{n} 个曲目 | {n} 个曲目", "tracks-summary": "{count} 个曲目 · {duration}", - "tracks-uploaded-n": "已上传 {n} 个曲目。 | 已上传 {n} 个曲目。", - "tracks-uploaded-with-failed": "已上传 {n} 个曲目,{failed} 个失败。 | 已上传 {n} 个曲目,{failed} 个失败。", "unmatch": "未匹配的 ROM", "unmatch-success": "ROM 取消匹配成功", "unselect-all": "取消选择所有", @@ -490,6 +488,8 @@ "upload-manual": "上传手册", "upload-new-folder": "新建文件夹…", "upload-new-folder-hint": "相对于游戏文件夹,例如 hack/v2", + "upload-overwrite-body": "{names} 已存在于此文件夹中,将被新上传的文件替换。 | {names} 已存在于此文件夹中,将被新上传的文件替换。", + "upload-overwrite-title": "覆盖 {n} 个已有文件? | 覆盖 {n} 个已有文件?", "upload-saves": "上传存档", "upload-screenshots": "上传截图", "upload-slot-hint": "带存档位的存档会参与设备同步;没有存档位的文件将作为手动存档保留。", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index 01d4a57b9..d0d2de8ee 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "这会从数据库中永久删除所有缺失的 ROM{platform} 及其资源目录。此操作无法撤销。", "cleanup-firmware-confirm": "这将从数据库中永久删除文件已从文件系统中缺失的所有固件条目{platform}。磁盘上的文件不会被删除。", "cleanup-firmware-queued": "清理任务已排队,缺失的固件将很快被删除", - "cleanup-queued": "清理任务已排队 — 缺失的 ROM 将很快被删除", + "cleanup-queued": "清理任务已排队,缺失的 ROM 将很快被删除", "client-api-tokens": "客户端 API 令牌", "client-token-confirm-delete": "确定要吊销此令牌吗?任何使用它的设备都将失去访问权限。", "client-token-confirm-regenerate": "这会使当前凭据失效。任何使用旧令牌的设备都需要重新配对。", diff --git a/frontend/src/locales/zh_TW/common.json b/frontend/src/locales/zh_TW/common.json index 489992272..37b0c53bf 100644 --- a/frontend/src/locales/zh_TW/common.json +++ b/frontend/src/locales/zh_TW/common.json @@ -100,6 +100,7 @@ "not-linked": "未連結", "offline": "離線", "online": "線上", + "overwrite": "覆蓋", "owned": "已擁有", "page": "頁面", "password-length": "密碼必須介於 6 到 255 個字元之間", diff --git a/frontend/src/locales/zh_TW/rom.json b/frontend/src/locales/zh_TW/rom.json index 163aa5e5f..61cbad50d 100644 --- a/frontend/src/locales/zh_TW/rom.json +++ b/frontend/src/locales/zh_TW/rom.json @@ -242,6 +242,7 @@ "metric-completion": "完成度", "metric-difficulty": "難度", "metric-rating": "評分", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "檔案系統中缺少平台", "more-actions": "更多動作", "my-notes": "我的筆記", @@ -263,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "未找到即時存檔", "no-states-uploaded": "未上傳任何即時存檔。", - "no-tracks-uploaded": "未上傳任何音軌。", "note-content": "筆記內容", "note-title": "筆記標題", "note-title-exists": "已存在此標題的筆記", @@ -471,8 +471,6 @@ "title-id": "標題ID", "tracks-n": "{n} 個音軌 | {n} 個音軌", "tracks-summary": "{count} 個音軌 · {duration}", - "tracks-uploaded-n": "已上傳 {n} 個音軌。 | 已上傳 {n} 個音軌。", - "tracks-uploaded-with-failed": "已上傳 {n} 個音軌,{failed} 個失敗。 | 已上傳 {n} 個音軌,{failed} 個失敗。", "unmatch": "清除匹配資料", "unmatch-success": "ROM 取消匹配成功", "unselect-all": "取消選擇所有", @@ -490,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "新增資料夾…", "upload-new-folder-hint": "相對於遊戲資料夾,例如 hack/v2", + "upload-overwrite-body": "{names} 已存在於此資料夾中,將被新上傳的檔案取代。 | {names} 已存在於此資料夾中,將被新上傳的檔案取代。", + "upload-overwrite-title": "覆蓋 {n} 個現有檔案? | 覆蓋 {n} 個現有檔案?", "upload-saves": "上傳存檔", "upload-screenshots": "上傳截圖", "upload-slot-hint": "有存檔槽的存檔會參與裝置同步;沒有存檔槽的檔案將作為手動存檔保留。", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index 6e41e976f..96771d79b 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "這將從資料庫中永久刪除檔案已從檔案系統中缺失的所有韌體項目{platform}。磁碟上的檔案不會被刪除。", "cleanup-firmware-queued": "清理任務已排程,缺失的韌體將在稍後被刪除", - "cleanup-queued": "清理任務已排程 — 缺失的 ROM 將在稍後被刪除", + "cleanup-queued": "清理任務已排程,缺失的 ROM 將在稍後被刪除", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/services/api/rom.test.ts b/frontend/src/services/api/rom.test.ts index a55288121..b215c99af 100644 --- a/frontend/src/services/api/rom.test.ts +++ b/frontend/src/services/api/rom.test.ts @@ -100,7 +100,11 @@ describe("romApi.uploadRoms", () => { "X-Upload-Platform": "3", "X-Upload-Filename": "fix.ips", }); - expect(startCall().body).toEqual({ rom_id: 42, folder: "hack/v2" }); + expect(startCall().body).toEqual({ + filename: "fix.ips", + rom_id: 42, + folder: "hack/v2", + }); expect(post).toHaveBeenCalledWith( "/roms/upload/u-1/complete", null, @@ -108,16 +112,47 @@ describe("romApi.uploadRoms", () => { ); }); - it("sends no body for a platform upload", async () => { + it("names only the file for a platform upload", async () => { await romApi.uploadRoms({ platformId: 3, filesToUpload: [new File(["abc"], "game.zip")], }); - expect(startCall().body).toBeNull(); + expect(startCall().body).toEqual({ filename: "game.zip" }); expect(startCall().headers["X-Upload-Filename"]).toBe("game.zip"); }); + it("keeps a name outside Latin-1 out of the header", async () => { + const name = "Relax \uff5c 432Hz.mp3"; + await romApi.uploadRoms({ + platformId: 3, + romId: 42, + filesToUpload: [new File(["abc"], name)], + }); + + expect(startCall().body).toEqual({ filename: name, rom_id: 42 }); + expect(startCall().headers["X-Upload-Filename"]).toBe( + "Relax%20%EF%BD%9C%20432Hz.mp3", + ); + }); + + it("asks the server to replace an existing file only when told to", async () => { + await romApi.uploadRoms({ + platformId: 3, + romId: 42, + folder: "hack", + overwrite: true, + filesToUpload: [new File(["abc"], "fix.ips")], + }); + + expect(startCall().body).toEqual({ + filename: "fix.ips", + rom_id: 42, + folder: "hack", + overwrite: true, + }); + }); + it("treats an empty folder as the rom root", async () => { await romApi.uploadRoms({ platformId: 3, @@ -126,7 +161,7 @@ describe("romApi.uploadRoms", () => { filesToUpload: [new File(["abc"], "readme.txt")], }); - expect(startCall().body).toEqual({ rom_id: 42 }); + expect(startCall().body).toEqual({ filename: "readme.txt", rom_id: 42 }); }); }); diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index b7bd2998d..7020d3561 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -44,6 +44,7 @@ async function uploadRomChunked({ file, romId, folder, + overwrite = false, }: { platformId: number; file: File; @@ -51,16 +52,26 @@ async function uploadRomChunked({ romId?: number; /** Subfolder inside the ROM folder; empty or omitted for the root. */ folder?: string; + /** Replace a file of the same name in the ROM folder. */ + overwrite?: boolean; }): Promise { const uploadStore = storeUpload(); const totalChunks = Math.ceil(file.size / UPLOAD_CHUNK_SIZE); - const target: UploadTargetPayload | null = - romId !== undefined ? { rom_id: romId, ...(folder && { folder }) } : null; + // The header cannot carry characters outside Latin-1, so it gets the + // percent-encoded name and the body the real one. + const target: UploadTargetPayload = { + filename: file.name, + ...(romId !== undefined && { + rom_id: romId, + ...(folder && { folder }), + ...(overwrite && { overwrite }), + }), + }; const { data: startData } = await api.post("/roms/upload/start", target, { headers: { "X-Upload-Platform": platformId.toString(), - "X-Upload-Filename": file.name, + "X-Upload-Filename": encodeURIComponent(file.name), "X-Upload-Total-Size": file.size.toString(), "X-Upload-Total-Chunks": totalChunks.toString(), }, @@ -129,11 +140,13 @@ async function uploadRoms({ filesToUpload, romId, folder, + overwrite, }: { platformId: number; filesToUpload: File[]; romId?: number; folder?: string; + overwrite?: boolean; }) { if (!socket.connected) socket.connect(); const uploadStore = storeUpload(); @@ -141,7 +154,7 @@ async function uploadRoms({ const promises = filesToUpload.map((file) => { uploadStore.start(file.name); - return uploadRomChunked({ platformId, file, romId, folder }) + return uploadRomChunked({ platformId, file, romId, folder, overwrite }) .then(() => null as null) .catch((error) => { uploadStore.fail( @@ -820,43 +833,6 @@ async function removeSoundtrack({ return api.delete(`/roms/${romId}/soundtracks/${fileId}`); } -async function uploadScreenshots({ - romId, - filesToUpload, -}: { - romId: number; - filesToUpload: File[]; -}) { - const uploadStore = storeUpload(); - - const promises = filesToUpload.map((file) => { - const formData = new FormData(); - formData.append(file.name, file); - - uploadStore.start(file.name); - return new Promise((resolve, reject) => { - api - .post(`/roms/${romId}/screenshots`, formData, { - headers: { - "Content-Type": "multipart/form-data", - "X-Upload-Filename": file.name, - }, - params: {}, - onUploadProgress: (progressEvent: AxiosProgressEvent) => { - uploadStore.update(file.name, progressEvent); - }, - }) - .then(resolve) - .catch((error) => { - uploadStore.fail(file.name, error.response?.data?.detail); - reject(error); - }); - }); - }); - - return Promise.allSettled(promises); -} - async function removeScreenshot({ romId, fileId, @@ -939,43 +915,6 @@ async function deleteRomFile({ return api.delete(`/roms/${romId}/files/${fileId}`); } -async function uploadWalkthroughFiles({ - romId, - filesToUpload, -}: { - romId: number; - filesToUpload: File[]; -}) { - const uploadStore = storeUpload(); - - const promises = filesToUpload.map((file) => { - const formData = new FormData(); - formData.append(file.name, file); - - uploadStore.start(file.name); - return new Promise((resolve, reject) => { - api - .post(`/roms/${romId}/walkthroughs/files`, formData, { - headers: { - "Content-Type": "multipart/form-data", - "X-Upload-Filename": file.name, - }, - params: {}, - onUploadProgress: (progressEvent: AxiosProgressEvent) => { - uploadStore.update(file.name, progressEvent); - }, - }) - .then(resolve) - .catch((error) => { - uploadStore.fail(file.name, error.response?.data?.detail); - reject(error); - }); - }); - }); - - return Promise.allSettled(promises); -} - async function deleteWalkthroughFile({ romId, fileId, @@ -1148,7 +1087,6 @@ export default { uploadManualFiles, deleteManualFile, deleteRomFile, - uploadWalkthroughFiles, deleteWalkthroughFile, addGamefaqsWalkthrough, getFileProgress, @@ -1156,7 +1094,6 @@ export default { uploadSoundtracks, removeSoundtrack, getSoundtrackMetadata, - uploadScreenshots, removeScreenshot, updateUserRomProps, deleteRoms, diff --git a/frontend/src/services/api/save.test.ts b/frontend/src/services/api/save.test.ts new file mode 100644 index 000000000..9ad792fcb --- /dev/null +++ b/frontend/src/services/api/save.test.ts @@ -0,0 +1,90 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { DetailedRomSchema, SaveSchema } from "@/__generated__"; +import saveApi, { UNLOAD_SAVE_MAX_BYTES } from "@/services/api/save"; + +vi.mock("@/services/api", () => ({ + default: { + getUri: ({ + url, + params, + }: { + url: string; + params?: Record; + }) => { + const query = new URLSearchParams(); + for (const [key, value] of Object.entries(params ?? {})) { + if (value !== undefined && value !== null) { + query.append(key, String(value)); + } + } + const search = query.toString(); + return `/api${url}${search ? `?${search}` : ""}`; + }, + }, +})); + +const rom = { id: 1 } as DetailedRomSchema; +const saveOf = (size: number) => new File([new Uint8Array(size)], "game.srm"); + +describe("sendSaveOnUnload", () => { + const fetchMock = vi.fn().mockResolvedValue(new Response()); + + beforeEach(() => { + vi.stubGlobal("fetch", fetchMock); + document.cookie = "romm_csrftoken=token"; + }); + + afterEach(() => { + vi.unstubAllGlobals(); + fetchMock.mockClear(); + }); + + it("opens a version with a keepalive request the page does not wait for", () => { + const sent = saveApi.sendSaveOnUnload({ + rom, + save: null, + saveFile: saveOf(16), + emulator: "snes9x", + deviceId: "dev", + slot: "autosave", + autocleanup: true, + }); + + expect(sent).toBe(true); + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe( + "/api/saves?rom_id=1&emulator=snes9x&device_id=dev&slot=autosave&autocleanup=true&overwrite=true", + ); + expect(init).toMatchObject({ + method: "POST", + keepalive: true, + credentials: "same-origin", + headers: { "x-csrftoken": "token" }, + }); + expect((init?.body as FormData).get("saveFile")).toBeInstanceOf(File); + }); + + it("updates the session's version in place", () => { + saveApi.sendSaveOnUnload({ + rom, + save: { id: 3 } as SaveSchema, + saveFile: saveOf(16), + deviceId: "dev", + }); + + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe("/api/saves/3?device_id=dev"); + expect(init).toMatchObject({ method: "PUT", keepalive: true }); + }); + + it("refuses a save a keepalive body cannot carry", () => { + const sent = saveApi.sendSaveOnUnload({ + rom, + save: null, + saveFile: saveOf(UNLOAD_SAVE_MAX_BYTES + 1), + }); + + expect(sent).toBe(false); + expect(fetchMock).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/services/api/save.ts b/frontend/src/services/api/save.ts index 243d0585c..671facfd8 100644 --- a/frontend/src/services/api/save.ts +++ b/frontend/src/services/api/save.ts @@ -1,3 +1,4 @@ +import { default as Cookies } from "js-cookie"; import type { Body_add_save_api_saves_post as AddSaveInput, Body_update_save_api_saves__id__put as UpdateSaveInput, @@ -14,6 +15,9 @@ export const saveApi = api; export const AUTOSAVE_SLOT = "autosave"; // Mirrors the backend's SAVE_SLOT_MAX_LENGTH so the field stops at the limit. export const SAVE_SLOT_MAX_LENGTH = 255; +// A keepalive request outlives its document, which is why the browser caps +// its body at 64 KB; the rest is left for the multipart framing. +export const UNLOAD_SAVE_MAX_BYTES = 60 * 1024; type SaveUploadInput = Omit & { saveFile: File; @@ -28,44 +32,53 @@ type UpdateSaveUploadInput = Omit< screenshotFile?: File; }; -async function uploadSaves({ - rom, - savesToUpload, - emulator, - deviceId, - slot, - autocleanup, - overwrite, -}: { +interface SaveVersionParams { rom: DetailedRomSchema; - savesToUpload: SaveUploadInput[]; emulator?: string; deviceId?: string; slot?: string; autocleanup?: boolean; /** Skip the stale-device conflict check and the content-hash dedupe. */ overwrite?: boolean; -}) { - const promises = savesToUpload.map(({ saveFile, screenshotFile }) => { - const formData = buildFormInput([ - ["saveFile", saveFile], - ["screenshotFile", screenshotFile], - ]); +} +function saveVersionQuery({ + rom, + emulator, + deviceId, + slot, + autocleanup, + overwrite, +}: SaveVersionParams) { + return { + rom_id: rom.id, + emulator, + device_id: deviceId, + slot, + autocleanup, + overwrite, + }; +} + +function saveFormData(saveFile: File, screenshotFile?: File): FormData { + return buildFormInput([ + ["saveFile", saveFile], + ["screenshotFile", screenshotFile], + ]); +} + +async function uploadSaves({ + savesToUpload, + ...version +}: SaveVersionParams & { savesToUpload: SaveUploadInput[] }) { + const promises = savesToUpload.map(({ saveFile, screenshotFile }) => { return new Promise((resolve, reject) => { api - .post("/saves", formData, { + .post("/saves", saveFormData(saveFile, screenshotFile), { headers: { "Content-Type": "multipart/form-data", }, - params: { - rom_id: rom.id, - emulator, - device_id: deviceId, - slot, - autocleanup, - overwrite, - }, + params: saveVersionQuery(version), }) .then(({ data }) => { resolve(data); @@ -98,6 +111,41 @@ async function updateSave({ }); } +/** + * Sends a save while the page unloads, updating `save` in place or opening a + * version in `slot`. Nothing outlives the document to await it. + * + * Returns: + * False when the save is too big for a keepalive body. + */ +function sendSaveOnUnload({ + save, + saveFile, + ...version +}: SaveVersionParams & { save: SaveSchema | null; saveFile: File }): boolean { + if (saveFile.size > UNLOAD_SAVE_MAX_BYTES) return false; + const request = save + ? { + url: `/saves/${save.id}`, + method: "PUT", + params: { device_id: version.deviceId }, + } + : { + url: "/saves", + method: "POST", + params: saveVersionQuery({ ...version, overwrite: true }), + }; + const csrfToken = Cookies.get("romm_csrftoken"); + void fetch(api.getUri(request), { + method: request.method, + body: saveFormData(saveFile), + keepalive: true, + credentials: "same-origin", + headers: csrfToken ? { "x-csrftoken": csrfToken } : undefined, + }).catch(() => undefined); + return true; +} + async function deleteSaves({ saves }: { saves: SaveSchema[] }) { return api.post("/saves/delete", { saves: saves.map((s) => s.id) }); } @@ -117,6 +165,7 @@ async function setSaveVisibility({ export default { uploadSaves, updateSave, + sendSaveOnUnload, deleteSaves, setSaveVisibility, }; diff --git a/frontend/src/stores/config.ts b/frontend/src/stores/config.ts index ecb9dd307..aa395e6a9 100644 --- a/frontend/src/stores/config.ts +++ b/frontend/src/stores/config.ts @@ -30,7 +30,7 @@ const defaultConfig = { EJS_CACHE_LIMIT: null, EJS_DISABLE_AUTO_UNLOAD: false, EJS_DISABLE_BATCH_BOOTUP: false, - EJS_ENABLE_AUTO_SAVE_SYNC: false, + EJS_ENABLE_AUTO_SAVE_SYNC: true, EJS_NETPLAY_ICE_SERVERS: [], EJS_DEFAULT_CORES: {}, EJS_SETTINGS: {}, diff --git a/frontend/src/test-utils/serverError.ts b/frontend/src/test-utils/serverError.ts new file mode 100644 index 000000000..00bef7986 --- /dev/null +++ b/frontend/src/test-utils/serverError.ts @@ -0,0 +1,8 @@ +import { AxiosError } from "axios"; + +/** A refused request as axios rejects it, carrying FastAPI's `detail`. */ +export function serverError(detail: string, status = 503): AxiosError { + return Object.assign(new AxiosError(`HTTP ${status}`), { + response: { status, data: { detail } }, + }); +} diff --git a/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue b/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue index 5fde135cb..c17f84c37 100644 --- a/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue +++ b/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue @@ -423,7 +423,7 @@ function closeDialog() { } .r-v2-del-rom__append { - padding: 10px 14px 0; + padding: 10px 14px 12px; display: flex; flex-direction: column; gap: 8px; diff --git a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.test.ts b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.test.ts index 9b843598c..59db548f2 100644 --- a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.test.ts +++ b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.test.ts @@ -8,9 +8,11 @@ import ManualUploadTargetDialog from "./ManualUploadTargetDialog.vue"; type UploadArgs = { romId: number; filesToUpload: File[] }; -const { uploadManuals, uploadManualFiles, getRom } = vi.hoisted(() => ({ +const { uploadManuals, uploadFiles, getRom } = vi.hoisted(() => ({ uploadManuals: vi.fn((_args: UploadArgs) => Promise.resolve([])), - uploadManualFiles: vi.fn((_args: UploadArgs) => Promise.resolve([])), + uploadFiles: vi.fn((_rom: DetailedRom, _folder: string, _files: File[]) => + Promise.resolve({ uploaded: 1, failed: 0 }), + ), getRom: vi.fn(() => Promise.resolve({ data: {} })), })); @@ -19,7 +21,14 @@ vi.mock("vue-i18n", () => ({ })); vi.mock("@/services/api/rom", () => ({ - default: { uploadManuals, uploadManualFiles, getRom }, + default: { uploadManuals, getRom }, +})); + +vi.mock("@/v2/composables/useRomFileUpload", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("@/v2/composables/useRomFileUpload") + >()), + useRomFileUpload: () => ({ uploadFiles }), })); vi.mock("@/v2/composables/useSnackbar", () => ({ @@ -105,14 +114,17 @@ describe("ManualUploadTargetDialog", () => { const wrapper = await upload(rom({ has_simple_single_file: true })); expect(uploadManuals).toHaveBeenCalledOnce(); - expect(uploadManualFiles).not.toHaveBeenCalled(); + expect(uploadFiles).not.toHaveBeenCalled(); expect(wrapper.find("[data-test-dialog]").exists()).toBe(false); }); it("appends to the ROM folder without asking once it holds a manual", async () => { - const wrapper = await upload(rom({ files: [manualFile()] })); + const target = rom({ files: [manualFile()] }); + const wrapper = await upload(target); - expect(uploadManualFiles).toHaveBeenCalledOnce(); + expect(uploadFiles).toHaveBeenCalledWith(target, "manual", [ + expect.objectContaining({ name: "manual.pdf" }), + ]); expect(uploadManuals).not.toHaveBeenCalled(); expect(wrapper.find("[data-test-dialog]").exists()).toBe(false); }); @@ -150,7 +162,7 @@ describe("ManualUploadTargetDialog", () => { const wrapper = await upload(rom()); expect(uploadManuals).not.toHaveBeenCalled(); - expect(uploadManualFiles).not.toHaveBeenCalled(); + expect(uploadFiles).not.toHaveBeenCalled(); expect(wrapper.find("[data-test-dialog]").exists()).toBe(true); }); }); diff --git a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue index f6ee5266f..b47c2c6d1 100644 --- a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue +++ b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue @@ -10,6 +10,10 @@ import romApi from "@/services/api/rom"; import type { DetailedRom } from "@/stores/roms"; import storeUpload from "@/stores/upload"; import type { Events } from "@/types/emitter"; +import { + ROM_UPLOAD_FOLDERS, + useRomFileUpload, +} from "@/v2/composables/useRomFileUpload"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; @@ -19,22 +23,12 @@ const { t } = useI18n(); const emitter = inject>("emitter"); const snackbar = useSnackbar(); const { refetchRom } = useRomSync(); +const { uploadFiles } = useRomFileUpload(); const uploadStore = storeUpload(); -const TARGETS = { - resources: { - upload: romApi.uploadManuals, - successKey: "rom.manuals-upload-success", - skippedKey: "rom.manuals-upload-skipped", - }, - folder: { - upload: romApi.uploadManualFiles, - successKey: "rom.manual-files-upload-success", - skippedKey: "rom.manual-files-upload-skipped", - }, -} as const; - -type UploadTarget = keyof typeof TARGETS; +// The resources copy replaces the scraped manual on the ROM record; the folder +// copy is a ROM file like any other upload. +type UploadTarget = "resources" | "folder"; const show = ref(false); const rom = ref(null); @@ -57,25 +51,24 @@ const handleShow = (payload: Events["showManualUploadTargetDialog"]) => { emitter?.on("showManualUploadTargetDialog", handleShow); onBeforeUnmount(() => emitter?.off("showManualUploadTargetDialog", handleShow)); -async function handleUploadResult( - responses: PromiseSettledResult[], - successKey: string, - skippedKey: string, - target: DetailedRom, -) { +async function uploadToResources(targetRom: DetailedRom, targetFiles: File[]) { + const responses = await romApi.uploadManuals({ + romId: targetRom.id, + filesToUpload: targetFiles, + }); const successful = responses.filter((r) => r.status === "fulfilled").length; const failed = responses.length - successful; if (failed === 0) uploadStore.reset(); if (successful > 0) { - snackbar.success(t(successKey, { count: successful, failed }), { - icon: "mdi-check-bold", - timeout: 3000, - }); - await refetchRom(target.id); + snackbar.success( + t("rom.manuals-upload-success", { count: successful, failed }), + { icon: "mdi-check-bold", timeout: 3000 }, + ); + await refetchRom(targetRom.id); } else { - snackbar.warning(t(skippedKey), { + snackbar.warning(t("rom.manuals-upload-skipped"), { icon: "mdi-close-circle", timeout: 5000, }); @@ -87,12 +80,11 @@ async function uploadTo( targetRom: DetailedRom, targetFiles: File[], ) { - const { upload, successKey, skippedKey } = TARGETS[target]; - const responses = await upload({ - romId: targetRom.id, - filesToUpload: targetFiles, - }); - await handleUploadResult(responses, successKey, skippedKey, targetRom); + if (target === "folder") { + await uploadFiles(targetRom, ROM_UPLOAD_FOLDERS.manual, targetFiles); + return; + } + await uploadToResources(targetRom, targetFiles); } // Serialized so a drop mid-upload waits rather than replacing the one running. diff --git a/frontend/src/v2/components/Dialogs/MatchRomDialog.vue b/frontend/src/v2/components/Dialogs/MatchRomDialog.vue index 3f673e76e..a81b8fa25 100644 --- a/frontend/src/v2/components/Dialogs/MatchRomDialog.vue +++ b/frontend/src/v2/components/Dialogs/MatchRomDialog.vue @@ -296,6 +296,7 @@ function closeDialog() { - - + diff --git a/frontend/src/v2/components/shared/AssetList.test.ts b/frontend/src/v2/components/shared/AssetList.test.ts index 57881b3f0..4820dfc9e 100644 --- a/frontend/src/v2/components/shared/AssetList.test.ts +++ b/frontend/src/v2/components/shared/AssetList.test.ts @@ -59,7 +59,7 @@ function mountList(props: { selectedId?: number; type?: "save" | "state" }) { } const titles = (wrapper: ReturnType) => - wrapper.findAll(".r-asset-list__group-title").map((el) => el.text()); + wrapper.findAll(".r-asset-group-head__title").map((el) => el.text()); const names = (wrapper: ReturnType) => wrapper.findAll(".r-asset-list__name").map((el) => el.text()); @@ -72,7 +72,7 @@ describe("AssetList slot grouping", () => { "main_quest", "play.slot-none", ]); - expect(wrapper.findAll(".r-asset-list__group-count")).toHaveLength(3); + expect(wrapper.findAll(".r-asset-group-head__count")).toHaveLength(3); }); it("shows only the newest version per slot until unfolded", async () => { diff --git a/frontend/src/v2/components/shared/AssetList.vue b/frontend/src/v2/components/shared/AssetList.vue index f0ae87011..794894ebd 100644 --- a/frontend/src/v2/components/shared/AssetList.vue +++ b/frontend/src/v2/components/shared/AssetList.vue @@ -17,6 +17,7 @@ import { useI18n } from "vue-i18n"; import { AUTOSAVE_SLOT } from "@/services/api/save"; import { formatTimestamp } from "@/utils"; import AssetChips from "@/v2/components/shared/AssetChips.vue"; +import AssetGroupHead from "@/v2/components/shared/AssetGroupHead.vue"; import AssetOwnerChip from "@/v2/components/shared/AssetOwnerChip.vue"; import AssetTimestamp from "@/v2/components/shared/AssetTimestamp.vue"; import { useGroupFold } from "@/v2/composables/useGroupFold"; @@ -146,28 +147,20 @@ const fadeIndex = computed(() => class="r-asset-list__group" :class="{ 'r-asset-list__group--slot': grouped }" > -
- - - {{ group.slot ?? t("play.slot-none") }} - + - - {{ t("play.slot-versions", group.versions.length) }} - -
+
  • .r-asset-list__groups { margin: 0; - /* Top padding gives the first row breathing room and absorbs the - -1px lift on hover/active so it never clips against the panel - edge. Bottom padding keeps the same gutter at the other end. */ - padding: 4px 0; + padding: 0; list-style: none; display: flex; flex-direction: column; gap: 12px; min-height: 0; } -/* Internal scroll only where the parent does not own scrolling. */ +/* Internal scroll only where the parent does not own scrolling. The + vertical padding absorbs the rows' -1px hover lift at the scroll edges. */ .r-asset-list--scroll .r-asset-list__groups { overflow-y: auto; max-height: 380px; - padding-right: 10px; + padding: 4px 10px 4px 0; } .r-asset-list__group { @@ -330,36 +321,6 @@ const fadeIndex = computed(() => background: color-mix(in srgb, var(--r-color-fg) 5%, transparent); } -.r-asset-list__group-head { - display: flex; - align-items: center; - gap: 8px; - padding: 4px 2px; - color: var(--r-color-fg-secondary); -} -.r-asset-list__group-icon { - color: var(--r-color-fg-muted); -} -.r-asset-list__group-icon--slot { - color: var(--r-color-brand-primary); -} -.r-asset-list__group-title { - font-size: 11px; - font-weight: var(--r-font-weight-semibold); - text-transform: uppercase; - letter-spacing: 0.06em; - color: var(--r-color-fg); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} -.r-asset-list__group-count { - margin-left: auto; - font-size: 10px; - white-space: nowrap; - font-variant-numeric: tabular-nums; -} - .r-asset-list__items { margin: 0; padding: 0; diff --git a/frontend/src/v2/components/shared/AssetStrip.test.ts b/frontend/src/v2/components/shared/AssetStrip.test.ts index 0912d051b..94f7c4979 100644 --- a/frontend/src/v2/components/shared/AssetStrip.test.ts +++ b/frontend/src/v2/components/shared/AssetStrip.test.ts @@ -45,7 +45,7 @@ describe("AssetStrip grouped by core", () => { const wrapper = mountStrip({ groupBy: "emulator" }); expect( - wrapper.findAll(".r-asset-strip__group-title").map((el) => el.text()), + wrapper.findAll(".r-asset-group-head__title").map((el) => el.text()), ).toEqual(["snes9x", "mgba", "play.any-core"]); expect(wrapper.findAll(".tag").map((el) => el.text())).toEqual([ "play.latest-version", @@ -65,7 +65,7 @@ describe("AssetStrip grouped by core", () => { it("shows the emulator tag and no Latest when ungrouped", () => { const wrapper = mountStrip(); - expect(wrapper.findAll(".r-asset-strip__group-title")).toHaveLength(0); + expect(wrapper.findAll(".r-asset-group-head__title")).toHaveLength(0); expect(wrapper.findAll(".tag").map((el) => el.text())).toEqual([ "snes9x", "snes9x", diff --git a/frontend/src/v2/components/shared/AssetStrip.vue b/frontend/src/v2/components/shared/AssetStrip.vue index f64800916..96dacb7da 100644 --- a/frontend/src/v2/components/shared/AssetStrip.vue +++ b/frontend/src/v2/components/shared/AssetStrip.vue @@ -6,6 +6,7 @@ import { computed } from "vue"; import { useI18n } from "vue-i18n"; import { formatTimestamp } from "@/utils"; import AssetChips from "@/v2/components/shared/AssetChips.vue"; +import AssetGroupHead from "@/v2/components/shared/AssetGroupHead.vue"; import AssetOwnerChip from "@/v2/components/shared/AssetOwnerChip.vue"; import AssetTimestamp from "@/v2/components/shared/AssetTimestamp.vue"; import { useGroupFold } from "@/v2/composables/useGroupFold"; @@ -145,36 +146,25 @@ const fadeIndex = computed(() => class="r-asset-strip" :class="[`r-asset-strip--${layout}`, { 'r-asset-strip--grouped': groupBy }]" > -
    - +
    @@ -319,54 +309,6 @@ const fadeIndex = computed(() => border-radius: var(--r-radius-md); background: color-mix(in srgb, var(--r-color-fg) 5%, transparent); } -.r-asset-strip__group-head { - appearance: none; - border: 0; - background: none; - width: 100%; - display: flex; - align-items: center; - gap: 8px; - padding: 4px 2px; - border-radius: var(--r-radius-sm); - font: inherit; - text-align: left; - color: var(--r-color-fg-secondary); - cursor: pointer; - transition: background var(--r-motion-fast) var(--r-motion-ease-out); -} -.r-asset-strip__group-head:hover { - background: color-mix(in srgb, var(--r-color-fg) 8%, transparent); -} -/* Same tone as the emulator tag on the tiles. */ -.r-asset-strip__group-icon { - color: var(--r-color-warning); -} -.r-asset-strip__group-title { - font-size: 11px; - font-weight: var(--r-font-weight-semibold); - text-transform: uppercase; - letter-spacing: 0.06em; - color: var(--r-color-fg); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} -.r-asset-strip__group--disabled .r-asset-strip__group-title { - color: var(--r-color-fg-muted); -} -.r-asset-strip__group-count { - margin-left: auto; - font-size: 10px; - font-variant-numeric: tabular-nums; -} -.r-asset-strip__group-chevron { - transition: transform var(--r-motion-fast) var(--r-motion-ease-out); -} -.r-asset-strip__group-head[aria-expanded="true"] .r-asset-strip__group-chevron { - transform: rotate(180deg); -} - .r-asset-strip__track { display: flex; gap: 10px; diff --git a/frontend/src/v2/composables/useGameActions/index.test.ts b/frontend/src/v2/composables/useGameActions/index.test.ts index fe02a6696..bb8c69caa 100644 --- a/frontend/src/v2/composables/useGameActions/index.test.ts +++ b/frontend/src/v2/composables/useGameActions/index.test.ts @@ -387,6 +387,76 @@ describe("useGameActions.play — launch confirmation", () => { }); }); +describe("useGameActions.needsLaunchConfirm", () => { + it.each(["retired", "never_playing"] as const)( + "asks before launching a %s game", + (status) => { + expect( + useGameActions(() => makeRom(status)).needsLaunchConfirm.value, + ).toBe(true); + }, + ); + + it("asks nothing for a game that is not shelved", () => { + expect(useGameActions(() => makeRom()).needsLaunchConfirm.value).toBe( + false, + ); + }); + + it("asks nothing when the preference is disabled", () => { + confirmProtectedLaunch.value = false; + expect( + useGameActions(() => makeRom("retired")).needsLaunchConfirm.value, + ).toBe(false); + }); +}); + +describe("useGameActions.playPath", () => { + it("points the local launch at EmulatorJS", () => { + const actions = useGameActions(() => makeRom()); + + expect(actions.playPath("local")).toBe("/rom/1/ejs"); + expect(actions.playPath()).toBe("/rom/1/ejs"); + }); + + it("prefers the stream only when nobody asked for the local player", () => { + streamContainer.value = {}; + const actions = useGameActions(() => makeRom()); + + expect(actions.playPath()).toBe("/rom/1/stream"); + expect(actions.playPath("stream")).toBe("/rom/1/stream"); + expect(actions.playPath("local")).toBe("/rom/1/ejs"); + }); + + it("has nowhere to go when the asked-for player cannot run the rom", () => { + const actions = useGameActions(() => makeRom()); + + expect(actions.playPath("stream")).toBeNull(); + }); + + it("orders the in-browser players the way play() launches them", () => { + const actions = useGameActions(() => makeRom()); + + canPlayJsDos.value = true; + expect(actions.playPath("local")).toBe("/rom/1/jsdos"); + + canPlayJsDos.value = false; + canPlayEJS.value = false; + canPlayPico8.value = true; + canPlayRuffle.value = true; + expect(actions.playPath("local")).toBe("/rom/1/pico8"); + + canPlayPico8.value = false; + expect(actions.playPath("local")).toBe("/rom/1/ruffle"); + }); + + it("resolves nothing without a rom", () => { + const actions = useGameActions(() => null); + + expect(actions.playPath()).toBeNull(); + }); +}); + describe("useGameActions — write/destructive gates", () => { it("exposes every write action when the grants allow it", () => { const actions = useGameActions(() => makeRom()); diff --git a/frontend/src/v2/composables/useGameActions/index.ts b/frontend/src/v2/composables/useGameActions/index.ts index 4adce3e43..ff4575c56 100644 --- a/frontend/src/v2/composables/useGameActions/index.ts +++ b/frontend/src/v2/composables/useGameActions/index.ts @@ -47,6 +47,13 @@ export interface GameActionsOptions { /** Which player a launch is asking for. "auto" lets availability decide. */ export type PlayTarget = "auto" | "local" | "stream"; +type PlayerSlug = "stream" | "jsdos" | "ejs" | "pico8" | "ruffle"; + +// EmulatorJS and js-dos need SharedArrayBuffer. Nginx only attaches the +// necessary COOP/COEP headers to the player document, so an SPA navigation +// cannot enable cross-origin isolation: these load the document directly. +const ISOLATED_PLAYERS: ReadonlySet = new Set(["jsdos", "ejs"]); + // Validate flashpoint game IDs are UUIDs const FLASHPOINT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -287,18 +294,23 @@ export function useGameActions( ); }); + // Launching a game the user deliberately shelved asks first. `retired` / + // `never_playing` encode an opt-in "don't play" intent; the prompt is + // gated by a per-user preference (on by default). + const needsLaunchConfirm = computed(() => { + const status = getRom()?.rom_user?.status; + return ( + confirmProtectedLaunch.value && + (status === "retired" || status === "never_playing") + ); + }); + async function play(player: PlayTarget = "auto") { const rom = getRom(); if (!rom) return; - // Guard launching a game the user deliberately shelved. `retired` / - // `never_playing` encode an opt-in "don't play" intent, so confirm - // before booting one. Gated by a per-user preference (on by default). const status = rom.rom_user?.status; - if ( - confirmProtectedLaunch.value && - (status === "retired" || status === "never_playing") - ) { + if (needsLaunchConfirm.value) { const ok = await confirm({ title: t("rom.confirm-launch-protected-title"), body: t("rom.confirm-launch-protected-body", { @@ -315,41 +327,20 @@ export function useGameActions( if (!ok) return; } - // A platform can be served by both an in-browser core and a streaming - // container, and they are different products (local latency versus the - // container's own emulator and save library). The caller says which it - // wants; "auto" keeps the single-button surfaces working by preferring - // the stream, as they did before either could be asked for by name. - const streaming = - player === "stream" || (player === "auto" && canPlayStream.value); - const inBrowser = player === "local" || player === "auto"; - - // EmulatorJS and js-dos need SharedArrayBuffer. Nginx only attaches the - // necessary COOP/COEP headers to the player document, so an SPA navigation - // cannot enable cross-origin isolation. Load the document directly instead. - const isolated = canPlayJsDos.value - ? "jsdos" - : canPlayEJS.value - ? "ejs" - : null; - if (!streaming && inBrowser && isolated) { - window.location.assign(`/rom/${rom.id}/${isolated}`); + const launch = launchTarget(player); + if (!launch) return; + const target = launch.path; + if (ISOLATED_PLAYERS.has(launch.player)) { + window.location.assign(target); return; } // The launch "load" flourish (disc/cartridge insert) lives on the // player view itself — see EmulatorJS's onPlay — so navigation is - // immediate here. - let path: string | null = null; - if (streaming && canPlayStream.value) path = `/rom/${rom.id}/stream`; - else if (inBrowser && canPlayPico8.value) path = `/rom/${rom.id}/pico8`; - else if (inBrowser && canPlayRuffle.value) path = `/rom/${rom.id}/ruffle`; - if (!path) return; - const target = path; - // When the caller supplies a cover element (the gallery card / detail - // hero), morph it into the player's hero cover — same `rom-cover-` - // tag the player paints statically. Degrades to a plain push where view - // transitions aren't available. + // immediate here. When the caller supplies a cover element (the gallery + // card / detail hero), morph it into the player's hero cover — same + // `rom-cover-` tag the player paints statically. Degrades to a plain + // push where view transitions aren't available. const el = options.coverEl?.(); if (el) { // Await the push inside the transition so the browser snapshots the @@ -363,6 +354,31 @@ export function useGameActions( } } + // A platform can be served by both an in-browser core and a streaming + // container, and they are different products (local latency versus the + // container's own emulator and save library). The caller says which it + // wants; "auto" keeps the single-button surfaces working by preferring + // the stream, as they did before either could be asked for by name. + function launchTarget( + player: PlayTarget, + ): { player: PlayerSlug; path: string } | null { + const rom = getRom(); + if (!rom) return null; + let slug: PlayerSlug | null = null; + if (player === "stream") slug = canPlayStream.value ? "stream" : null; + else if (player === "auto" && canPlayStream.value) slug = "stream"; + else if (canPlayJsDos.value) slug = "jsdos"; + else if (canPlayEJS.value) slug = "ejs"; + else if (canPlayPico8.value) slug = "pico8"; + else if (canPlayRuffle.value) slug = "ruffle"; + return slug ? { player: slug, path: `/rom/${rom.id}/${slug}` } : null; + } + + /** Path `play(player)` would open, for surfaces that render the launch as a link. */ + function playPath(player: PlayTarget = "auto"): string | null { + return launchTarget(player)?.path ?? null; + } + // Joining is its own navigation: the stream view claims a container when it // opens normally, so the join intent has to reach it in the URL. Confirming // first is what stands in for the start page, which a joiner never sees: @@ -587,7 +603,9 @@ export function useGameActions( setStatus, setStatusEnum, setScore, + needsLaunchConfirm, play, + playPath, goToPlatform, platformPath, download, diff --git a/frontend/src/v2/composables/usePlayerNav/index.ts b/frontend/src/v2/composables/usePlayerNav/index.ts index de95ee8ab..d24ce8bff 100644 --- a/frontend/src/v2/composables/usePlayerNav/index.ts +++ b/frontend/src/v2/composables/usePlayerNav/index.ts @@ -1,26 +1,27 @@ // usePlayerNav — the two back links every v2 player view carries. The route id // is used rather than the hero's, so the links work during the seed window. -import { useRouter } from "vue-router"; +import { computed, type ComputedRef } from "vue"; +import type { RouteLocationRaw } from "vue-router"; import { ROUTES } from "@/plugins/router"; export function usePlayerNav( romId: number, platformId: () => number | null | undefined, ): { - backToRom: () => void; - backToPlatform: () => void; + romRoute: RouteLocationRaw; + /** Undefined until the hero says which platform the rom belongs to. */ + platformRoute: ComputedRef; } { - const router = useRouter(); + const romRoute: RouteLocationRaw = { + name: ROUTES.ROM, + params: { rom: romId }, + }; - function backToRom() { - router.push({ name: ROUTES.ROM, params: { rom: romId } }); - } - - function backToPlatform() { + const platformRoute = computed(() => { const platform = platformId(); - if (platform == null) return; - router.push({ name: ROUTES.PLATFORM, params: { platform } }); - } + if (platform == null) return undefined; + return { name: ROUTES.PLATFORM, params: { platform } }; + }); - return { backToRom, backToPlatform }; + return { romRoute, platformRoute }; } diff --git a/frontend/src/v2/composables/useRomFileUpload/index.test.ts b/frontend/src/v2/composables/useRomFileUpload/index.test.ts new file mode 100644 index 000000000..7a8dfa59c --- /dev/null +++ b/frontend/src/v2/composables/useRomFileUpload/index.test.ts @@ -0,0 +1,165 @@ +import { createPinia, setActivePinia } from "pinia"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import storeUpload from "@/stores/upload"; +import { ROM_UPLOAD_FOLDERS, useRomFileUpload } from "./index"; + +const { uploadRoms, refetchRom, confirmFn, snackbar } = vi.hoisted(() => ({ + uploadRoms: vi.fn(), + refetchRom: vi.fn(), + confirmFn: vi.fn(), + snackbar: { + success: vi.fn(), + error: vi.fn(), + warning: vi.fn(), + info: vi.fn(), + }, +})); + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ t: (key: string) => key }), +})); +vi.mock("@/services/api/rom", () => ({ + default: { uploadRoms }, +})); +vi.mock("@/v2/composables/useConfirm", () => ({ + useConfirm: () => confirmFn, +})); +vi.mock("@/v2/composables/useRomSync", () => ({ + useRomSync: () => ({ refetchRom }), +})); +vi.mock("@/v2/composables/useSnackbar", () => ({ + useSnackbar: () => snackbar, +})); + +const folderRom = { id: 1, platform_id: 7, has_simple_single_file: false }; +const singleFileRom = { ...folderRom, has_simple_single_file: true }; +const files = [new File(["x"], "track.mp3")]; +const exists = { isAxiosError: true, response: { status: 409 } }; + +describe("useRomFileUpload", () => { + beforeEach(() => { + setActivePinia(createPinia()); + vi.clearAllMocks(); + uploadRoms.mockResolvedValue([{ status: "fulfilled", value: null }]); + confirmFn.mockResolvedValue(true); + }); + + it("uploads into the folder, reports and refetches the rom", async () => { + const { uploadFiles } = useRomFileUpload(); + + const outcome = await uploadFiles( + folderRom, + ROM_UPLOAD_FOLDERS.soundtrack, + files, + ); + + expect(outcome).toEqual({ uploaded: 1, failed: 0 }); + expect(uploadRoms).toHaveBeenCalledWith({ + platformId: 7, + romId: 1, + folder: "soundtrack", + filesToUpload: files, + }); + expect(confirmFn).not.toHaveBeenCalled(); + expect(snackbar.success).toHaveBeenCalledWith( + "rom.files-uploaded-n", + expect.anything(), + ); + expect(refetchRom).toHaveBeenCalledWith(1); + }); + + it("asks before promoting a single-file rom and respects a no", async () => { + confirmFn.mockResolvedValue(false); + const { uploadFiles } = useRomFileUpload(); + + const outcome = await uploadFiles(singleFileRom, "", files); + + expect(outcome).toEqual({ uploaded: 0, failed: 0 }); + expect(confirmFn).toHaveBeenCalledWith( + expect.objectContaining({ tone: "warning" }), + ); + expect(uploadRoms).not.toHaveBeenCalled(); + }); + + it("asks before replacing an existing file and retries with overwrite", async () => { + const both = [new File(["x"], "track.mp3"), new File(["y"], "b.mp3")]; + uploadRoms + .mockResolvedValueOnce([ + { status: "fulfilled", value: null }, + { status: "rejected", reason: exists }, + ]) + .mockResolvedValueOnce([{ status: "fulfilled", value: null }]); + const { uploadFiles } = useRomFileUpload(); + + const outcome = await uploadFiles(folderRom, "soundtrack", both); + + expect(outcome).toEqual({ uploaded: 2, failed: 0 }); + expect(confirmFn).toHaveBeenCalledWith( + expect.objectContaining({ + title: "rom.upload-overwrite-title", + confirmText: "common.overwrite", + tone: "danger", + }), + ); + expect(uploadRoms).toHaveBeenLastCalledWith( + expect.objectContaining({ filesToUpload: [both[1]], overwrite: true }), + ); + expect(snackbar.error).not.toHaveBeenCalled(); + expect(refetchRom).toHaveBeenCalledWith(1); + }); + + it("drops a file the user declines to overwrite without complaint", async () => { + uploadRoms.mockResolvedValue([{ status: "rejected", reason: exists }]); + confirmFn.mockResolvedValue(false); + const { uploadFiles } = useRomFileUpload(); + + const outcome = await uploadFiles(folderRom, "soundtrack", files); + + expect(outcome).toEqual({ uploaded: 0, failed: 0 }); + expect(uploadRoms).toHaveBeenCalledOnce(); + expect(snackbar.error).not.toHaveBeenCalled(); + expect(snackbar.warning).not.toHaveBeenCalled(); + expect(refetchRom).not.toHaveBeenCalled(); + }); + + it("explains a rejected file and keeps the failed entry in the upload toast", async () => { + uploadRoms.mockResolvedValue([ + { + status: "rejected", + reason: { isAxiosError: true, response: { status: 400 } }, + }, + ]); + const uploadStore = storeUpload(); + uploadStore.start("track.mp3"); + const { uploadFiles } = useRomFileUpload(); + + const outcome = await uploadFiles(folderRom, "soundtrack", files); + + expect(outcome).toEqual({ uploaded: 0, failed: 1 }); + expect(snackbar.error).toHaveBeenCalledWith("rom.upload-file-rejected"); + expect(snackbar.warning).toHaveBeenCalledWith( + "rom.no-files-uploaded", + expect.anything(), + ); + expect(refetchRom).not.toHaveBeenCalled(); + expect(uploadStore.files).toHaveLength(1); + }); + + it("tracks in-flight uploads", async () => { + let release: (() => void) | undefined; + uploadRoms.mockImplementationOnce( + () => + new Promise((resolve) => { + release = () => resolve([{ status: "fulfilled", value: null }]); + }), + ); + const { uploading, uploadFiles } = useRomFileUpload(); + + const pending = uploadFiles(folderRom, "", files); + expect(uploading.value).toBe(true); + + release?.(); + await pending; + expect(uploading.value).toBe(false); + }); +}); diff --git a/frontend/src/v2/composables/useRomFileUpload/index.ts b/frontend/src/v2/composables/useRomFileUpload/index.ts new file mode 100644 index 000000000..3813a2222 --- /dev/null +++ b/frontend/src/v2/composables/useRomFileUpload/index.ts @@ -0,0 +1,165 @@ +// useRomFileUpload: the one way a v2 tab puts files into a ROM's folder. +// +// The Files tab targets any subfolder and the Media subtabs target the folder +// the scanner maps to their category, but the upload itself is the same: +// confirm the single-file promotion, stream through the chunked upload, ask +// before replacing a file the folder already holds, report the outcome and +// refetch the ROM. +import axios from "axios"; +import { computed, ref } from "vue"; +import { useI18n } from "vue-i18n"; +import type { DetailedRomSchema } from "@/__generated__"; +import romApi from "@/services/api/rom"; +import storeUpload from "@/stores/upload"; +import { useConfirm } from "@/v2/composables/useConfirm"; +import { useIsAlive } from "@/v2/composables/useIsAlive"; +import { useRomSync } from "@/v2/composables/useRomSync"; +import { useSnackbar } from "@/v2/composables/useSnackbar"; +import { errorMessage } from "@/v2/utils/errorMessage"; + +/** The subfolder each Media subtab uploads into. The scanner maps these + * names to the file category, so the file registers as the tab expects. */ +export const ROM_UPLOAD_FOLDERS = { + manual: "manual", + walkthrough: "walkthrough", + screenshots: "screenshots", + soundtrack: "soundtrack", +} as const; + +export type UploadableRom = Pick< + DetailedRomSchema, + "id" | "platform_id" | "has_simple_single_file" +>; + +export interface RomFileUploadOutcome { + uploaded: number; + failed: number; +} + +const NOTHING_UPLOADED: RomFileUploadOutcome = { uploaded: 0, failed: 0 }; + +type Attempt = { file: File; result: PromiseSettledResult }; + +/** The server refuses a name the folder already holds with a 409. */ +function isExisting({ result }: Attempt): boolean { + return ( + result.status === "rejected" && + axios.isAxiosError(result.reason) && + result.reason.response?.status === 409 + ); +} + +export function useRomFileUpload() { + const { t } = useI18n(); + const snackbar = useSnackbar(); + const confirm = useConfirm(); + const uploadStore = storeUpload(); + const { refetchRom } = useRomSync(); + const alive = useIsAlive(); + + const inFlight = ref(0); + const uploading = computed(() => inFlight.value > 0); + + function failureMessage(name: string, reason: unknown): string { + const status = axios.isAxiosError(reason) + ? reason.response?.status + : undefined; + if (status === 409) return t("rom.upload-file-exists", { name }); + const error = errorMessage(reason); + if (status === 400) return t("rom.upload-file-rejected", { name, error }); + return t("rom.upload-file-failed", { name, error }); + } + + /** Upload `files` into `folder` inside the ROM ("" for its root). A lone + * file ROM is promoted to a folder first, after the user agrees. */ + async function uploadFiles( + rom: UploadableRom, + folder: string, + files: File[], + ): Promise { + if (files.length === 0) return NOTHING_UPLOADED; + if (rom.has_simple_single_file) { + const ok = await confirm({ + title: t("rom.convert-to-folder-title"), + body: t("rom.convert-to-folder-body"), + tone: "warning", + }); + if (!ok) return NOTHING_UPLOADED; + } + + inFlight.value += 1; + try { + const send = async (batch: File[], overwrite = false) => { + const results = await romApi.uploadRoms({ + platformId: rom.platform_id, + romId: rom.id, + folder, + filesToUpload: batch, + ...(overwrite && { overwrite }), + }); + return batch.map((file, i) => ({ file, result: results[i] })); + }; + + let attempts = await send(files); + const existing = attempts.filter(isExisting); + if (existing.length > 0) { + attempts = attempts.filter((attempt) => !isExisting(attempt)); + const names = existing.map(({ file }) => file.name).join(", "); + const ok = await confirm({ + title: t("rom.upload-overwrite-title", existing.length, { + named: { n: existing.length }, + }), + body: t("rom.upload-overwrite-body", existing.length, { + named: { names }, + }), + confirmText: t("common.overwrite"), + tone: "danger", + }); + if (ok) { + // The refused entries are still in the toast; the retry re-adds them. + uploadStore.clearFinished(); + attempts = [ + ...attempts, + ...(await send( + existing.map(({ file }) => file), + true, + )), + ]; + } + } + if (attempts.length === 0) return NOTHING_UPLOADED; + + const results = attempts.map(({ result }) => result); + const uploaded = results.filter((r) => r.status === "fulfilled").length; + const failed = results.length - uploaded; + if (uploaded > 0) { + snackbar.success( + failed + ? t("rom.files-uploaded-with-failed", uploaded, { + named: { n: uploaded, failed }, + }) + : t("rom.files-uploaded-n", uploaded, { named: { n: uploaded } }), + { icon: "mdi-check-bold" }, + ); + } else { + snackbar.warning(t("rom.no-files-uploaded"), { + icon: "mdi-close-circle", + }); + } + const firstFailed = attempts.find( + ({ result }) => result.status === "rejected", + ); + if (firstFailed) { + const rejected = firstFailed.result as PromiseRejectedResult; + snackbar.error(failureMessage(firstFailed.file.name, rejected.reason)); + } + if (failed === 0) uploadStore.reset(); + if (alive.value && uploaded > 0) await refetchRom(rom.id); + return { uploaded, failed }; + } finally { + inFlight.value -= 1; + } + } + + return { uploading, uploadFiles }; +} diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index 1cf499f04..d2ff1dda3 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -137,7 +137,7 @@ const firmwareOptions = ref([]); const resume = ref({ save: null, state: null }); const { romId, heroRom, title, platformLabel } = usePlayerHero(rom); -const { backToRom, backToPlatform } = usePlayerNav( +const { romRoute, platformRoute } = usePlayerNav( romId, () => heroRom.value?.platform_id, ); @@ -588,7 +588,7 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value)); variant="text" size="small" prepend-icon="mdi-arrow-left" - @click="backToRom" + :to="romRoute" > {{ t("play.back-to-game-details") }} @@ -596,7 +596,8 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value)); variant="text" size="small" prepend-icon="mdi-view-grid-outline" - @click="backToPlatform" + :to="platformRoute" + :disabled="!platformRoute" > {{ t("play.back-to-gallery") }} @@ -704,11 +705,7 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
    -