diff --git a/backend/endpoints/roms/manual.py b/backend/endpoints/roms/manual.py index 62d5b071b..f016074d0 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,29 +215,7 @@ 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): + if not _is_allowed_manual_file(filename): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=( @@ -248,61 +224,9 @@ async def add_rom_manual_file( ), ) - 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..90af9c3b8 100644 --- a/backend/endpoints/roms/screenshot.py +++ b/backend/endpoints/roms/screenshot.py @@ -1,26 +1,22 @@ -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 models.rom import RomFileCategory from utils.media_types import ( ALLOWED_IMAGE_EXTENSIONS, is_allowed_image_file, @@ -29,8 +25,6 @@ from utils.router import APIRouter router = APIRouter() -SCREENSHOT_FOLDER = "screenshots" - @protected_route( router.post, @@ -50,7 +44,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,31 +52,7 @@ 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): + if not is_allowed_image_file(filename): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=( @@ -91,61 +61,9 @@ async def add_rom_screenshots( ), ) - 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..38740b31b 100644 --- a/backend/endpoints/roms/soundtrack.py +++ b/backend/endpoints/roms/soundtrack.py @@ -1,41 +1,32 @@ -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 models.rom import RomFileCategory 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 utils.router import APIRouter router = APIRouter() -SOUNDTRACK_FOLDER = "soundtrack" - @protected_route( router.get, @@ -90,7 +81,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,31 +89,7 @@ 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): + if not is_allowed_audio_file(filename): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=( @@ -131,88 +98,9 @@ async def add_rom_soundtracks( ), ) - 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..f48fb1517 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,8 +22,18 @@ 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 utils.router import 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,118 @@ 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 +) -> None: + try: + 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 +) -> UploadDestination: + """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.""" + 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}", + ) + + await _commit(destination, staged, overwrite=True) + return destination + + +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=False + ) 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.", + ) @protected_route( @@ -282,10 +280,13 @@ async def start_chunked_upload( ) platform_fs_slug = db_platform.fs_slug + if target and target.filename: + filename = target.filename safe_filename = _sanitized_filename(filename) + rom_id = target.rom_id if target else 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 +299,18 @@ 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): + 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) + except UploadRejectedException as exc: raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"File {filename} would be ignored by the scanner", - ) - _free_rom_destination(rom, rel_folder, safe_filename) + 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 +324,13 @@ 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, } 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 +424,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 +500,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=False) + 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..ffa193a0c 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,6 +18,7 @@ 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 @@ -31,8 +30,6 @@ from utils.router import APIRouter router = APIRouter() -WALKTHROUGH_FOLDER = "walkthrough" - _SLUG_RE = re.compile(r"[^a-z0-9]+") @@ -91,29 +88,7 @@ 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): + if not _is_allowed_walkthrough_file(filename): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=( @@ -122,73 +97,23 @@ async def add_rom_walkthrough_file( ), ) - 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 + destination = 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, + + rom_file = db_rom_handler.get_rom_file_by_path( + rom_id=rom.id, file_path=destination.rel_dir, file_name=filename + ) + if rom_file: + 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), }, ) - 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 +168,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/handler/rom_upload.py b/backend/handler/rom_upload.py new file mode 100644 index 000000000..3625fd68a --- /dev/null +++ b/backend/handler/rom_upload.py @@ -0,0 +1,205 @@ +"""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.filesystem import fs_rom_handler +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 Rom, RomFileCategory + +# 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", +} + + +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 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 or the scanner + would never register the file. + UploadConflictException: A file of that name is already there (or will + be, once promoted), unless `overwrite` allows replacing it. + """ + 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 +) -> None: + """Move the staged bytes into place and register the file on its ROM. + + The staged file is removed whatever the outcome. + + 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}") + + if destination.rom is None: + return + try: + await refresh_rom_files(destination.rom) + except Exception as exc: + log.error( + f"Error registering uploaded file for ROM {destination.rom.id}", + exc_info=exc, + ) + raise UploadNotRegisteredException( + "File uploaded but not registered yet, run a quick scan" + ) from exc 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..ec7bd3dda 100644 --- a/backend/tests/endpoints/roms/test_upload.py +++ b/backend/tests/endpoints/roms/test_upload.py @@ -5,10 +5,11 @@ 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 @@ -690,12 +691,75 @@ 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_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/frontend/src/__generated__/models/UploadTargetPayload.ts b/frontend/src/__generated__/models/UploadTargetPayload.ts index 7be852bc9..d579bdf27 100644 --- a/frontend/src/__generated__/models/UploadTargetPayload.ts +++ b/frontend/src/__generated__/models/UploadTargetPayload.ts @@ -4,13 +4,20 @@ /* 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); }; diff --git a/frontend/src/locales/bg_BG/rom.json b/frontend/src/locales/bg_BG/rom.json index f2210488e..855b868fe 100644 --- a/frontend/src/locales/bg_BG/rom.json +++ b/frontend/src/locales/bg_BG/rom.json @@ -264,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": "Вече съществува бележка с това заглавие", @@ -472,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": "Премахни избора на всички", diff --git a/frontend/src/locales/cs_CZ/rom.json b/frontend/src/locales/cs_CZ/rom.json index bdbae7be4..55980c3d2 100644 --- a/frontend/src/locales/cs_CZ/rom.json +++ b/frontend/src/locales/cs_CZ/rom.json @@ -264,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", @@ -472,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", diff --git a/frontend/src/locales/de_DE/rom.json b/frontend/src/locales/de_DE/rom.json index 8b4a5331c..e779ccc8d 100644 --- a/frontend/src/locales/de_DE/rom.json +++ b/frontend/src/locales/de_DE/rom.json @@ -264,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", @@ -472,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", diff --git a/frontend/src/locales/en_GB/rom.json b/frontend/src/locales/en_GB/rom.json index ecac5c738..58cd83e93 100644 --- a/frontend/src/locales/en_GB/rom.json +++ b/frontend/src/locales/en_GB/rom.json @@ -264,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", @@ -472,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", diff --git a/frontend/src/locales/en_US/rom.json b/frontend/src/locales/en_US/rom.json index dc514aeb8..82bf9280d 100644 --- a/frontend/src/locales/en_US/rom.json +++ b/frontend/src/locales/en_US/rom.json @@ -264,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", @@ -472,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", diff --git a/frontend/src/locales/es_ES/rom.json b/frontend/src/locales/es_ES/rom.json index bf3c224eb..61983d9f9 100644 --- a/frontend/src/locales/es_ES/rom.json +++ b/frontend/src/locales/es_ES/rom.json @@ -264,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", @@ -472,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", diff --git a/frontend/src/locales/fr_FR/rom.json b/frontend/src/locales/fr_FR/rom.json index 051204882..631532d5b 100644 --- a/frontend/src/locales/fr_FR/rom.json +++ b/frontend/src/locales/fr_FR/rom.json @@ -264,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à", @@ -472,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", diff --git a/frontend/src/locales/hu_HU/rom.json b/frontend/src/locales/hu_HU/rom.json index b86b444a7..92f72adf1 100644 --- a/frontend/src/locales/hu_HU/rom.json +++ b/frontend/src/locales/hu_HU/rom.json @@ -264,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", @@ -472,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", diff --git a/frontend/src/locales/it_IT/rom.json b/frontend/src/locales/it_IT/rom.json index 06253ffc4..3e556fc6b 100644 --- a/frontend/src/locales/it_IT/rom.json +++ b/frontend/src/locales/it_IT/rom.json @@ -264,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à", @@ -472,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", diff --git a/frontend/src/locales/ja_JP/rom.json b/frontend/src/locales/ja_JP/rom.json index 763b5ab08..8363bc99e 100644 --- a/frontend/src/locales/ja_JP/rom.json +++ b/frontend/src/locales/ja_JP/rom.json @@ -264,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": "このタイトルのノートがすでに存在します", @@ -472,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": "すべて選択解除", diff --git a/frontend/src/locales/ko_KR/rom.json b/frontend/src/locales/ko_KR/rom.json index 96a08f955..355ce0f10 100644 --- a/frontend/src/locales/ko_KR/rom.json +++ b/frontend/src/locales/ko_KR/rom.json @@ -264,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": "이 제목의 노트가 이미 존재합니다", @@ -472,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": "모두 선택 해제", diff --git a/frontend/src/locales/pl_PL/rom.json b/frontend/src/locales/pl_PL/rom.json index 93b15c6d1..a3bc4ff00 100644 --- a/frontend/src/locales/pl_PL/rom.json +++ b/frontend/src/locales/pl_PL/rom.json @@ -264,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", @@ -472,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", diff --git a/frontend/src/locales/pt_BR/rom.json b/frontend/src/locales/pt_BR/rom.json index 3a114a473..45460b746 100644 --- a/frontend/src/locales/pt_BR/rom.json +++ b/frontend/src/locales/pt_BR/rom.json @@ -264,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", @@ -472,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", diff --git a/frontend/src/locales/ro_RO/rom.json b/frontend/src/locales/ro_RO/rom.json index fa93dd3c6..8f9d0c770 100644 --- a/frontend/src/locales/ro_RO/rom.json +++ b/frontend/src/locales/ro_RO/rom.json @@ -264,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", @@ -472,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", diff --git a/frontend/src/locales/ru_RU/rom.json b/frontend/src/locales/ru_RU/rom.json index 742c9f71c..1f828fb48 100644 --- a/frontend/src/locales/ru_RU/rom.json +++ b/frontend/src/locales/ru_RU/rom.json @@ -264,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": "Заметка с таким заголовком уже существует", @@ -472,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": "Отменить выбор всех", diff --git a/frontend/src/locales/tr_TR/rom.json b/frontend/src/locales/tr_TR/rom.json index 81f205f3b..0689fa1e4 100644 --- a/frontend/src/locales/tr_TR/rom.json +++ b/frontend/src/locales/tr_TR/rom.json @@ -264,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", @@ -472,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", diff --git a/frontend/src/locales/zh_CN/rom.json b/frontend/src/locales/zh_CN/rom.json index a32f43752..16f714cfc 100644 --- a/frontend/src/locales/zh_CN/rom.json +++ b/frontend/src/locales/zh_CN/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "此游戏暂无原声音乐。", "no-states-found": "未找到状态", "no-states-uploaded": "未上传任何状态。", - "no-tracks-uploaded": "未上传任何曲目。", "note-content": "笔记内容", "note-title": "笔记标题", "note-title-exists": "已存在此标题的笔记", @@ -472,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": "取消选择所有", diff --git a/frontend/src/locales/zh_TW/rom.json b/frontend/src/locales/zh_TW/rom.json index 2ce3e2212..eb0830481 100644 --- a/frontend/src/locales/zh_TW/rom.json +++ b/frontend/src/locales/zh_TW/rom.json @@ -264,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": "已存在此標題的筆記", @@ -472,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": "取消選擇所有", diff --git a/frontend/src/services/api/rom.test.ts b/frontend/src/services/api/rom.test.ts index a55288121..06d12c375 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,30 @@ 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("treats an empty folder as the rom root", async () => { await romApi.uploadRoms({ platformId: 3, @@ -126,7 +144,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..e58738890 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -55,12 +55,16 @@ async function uploadRomChunked({ 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 }) }), + }; 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(), }, @@ -820,43 +824,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 +906,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 +1078,6 @@ export default { uploadManualFiles, deleteManualFile, deleteRomFile, - uploadWalkthroughFiles, deleteWalkthroughFile, addGamefaqsWalkthrough, getFileProgress, @@ -1156,7 +1085,6 @@ export default { uploadSoundtracks, removeSoundtrack, getSoundtrackMetadata, - uploadScreenshots, removeScreenshot, updateUserRomProps, deleteRoms, 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/GameDetails/FilesTab/FilesTab.vue b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue index 379fd34f9..31c54a744 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue @@ -36,7 +36,6 @@ // `rom.delete` permission. Each file is removed from disk and the DB // row is dropped via `DELETE /roms/{rom_id}/files/{file_id}`. import { RBtn, RCheckbox, REmptyState, RIcon, RTooltip } from "@v2/lib"; -import axios from "axios"; import { computed, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; import { useRoute, useRouter } from "vue-router"; @@ -47,11 +46,11 @@ import type { } from "@/__generated__"; import romApi from "@/services/api/rom"; import storeRoms from "@/stores/roms"; -import storeUpload from "@/stores/upload"; import { getDownloadLink } from "@/utils"; import { useCan } from "@/v2/composables/useCan"; import { useConfirm } from "@/v2/composables/useConfirm"; import { useIsAlive } from "@/v2/composables/useIsAlive"; +import { useRomFileUpload } from "@/v2/composables/useRomFileUpload"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { errorMessage } from "@/v2/utils/errorMessage"; @@ -546,9 +545,8 @@ async function deleteSelectedFiles() { // One hidden `` serves every folder: the active subtab decides // the destination, and the dialog covers "All files" or a new folder. const fileInput = ref(null); -const uploading = ref(false); +const { uploading, uploadFiles: uploadRomFiles } = useRomFileUpload(); const uploadDialogOpen = ref(false); -const uploadStore = storeUpload(); const alive = useIsAlive(); const uploadFolders = computed(() => @@ -584,69 +582,12 @@ function onDialogSubmit(payload: { folder: string; files: File[] }) { void uploadFiles(payload.folder, payload.files); } -function uploadErrorMessage(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 }); -} - async function uploadFiles(folder: string, picked: File[]) { if (uploading.value) return; - if (props.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; - } - - uploading.value = true; - try { - const results = await romApi.uploadRoms({ - platformId: props.rom.platform_id, - romId: props.rom.id, - folder, - filesToUpload: picked, - }); - const ok = results.filter((r) => r.status === "fulfilled").length; - const failed = results.length - ok; - if (ok > 0) { - snackbar.success( - failed - ? t("rom.files-uploaded-with-failed", ok, { - named: { n: ok, failed }, - }) - : t("rom.files-uploaded-n", ok, { named: { n: ok } }), - { icon: "mdi-check-bold" }, - ); - } else { - snackbar.warning(t("rom.no-files-uploaded"), { - icon: "mdi-close-circle", - }); - } - // allSettled keeps the input order, so the index maps back to the file. - const firstFailed = results.findIndex((r) => r.status === "rejected"); - if (firstFailed >= 0) { - const rejected = results[firstFailed] as PromiseRejectedResult; - snackbar.error( - uploadErrorMessage(picked[firstFailed].name, rejected.reason), - ); - } - if (failed === 0) uploadStore.reset(); - if (!alive.value || ok === 0) return; - await refreshRom(); - const landed = folder.split("/")[0]; - if (alive.value && landed && validSubtabIds.value.has(landed)) { - subTab.value = landed; - } - } finally { - uploading.value = false; - } + const { uploaded } = await uploadRomFiles(props.rom, folder, picked); + if (!alive.value || uploaded === 0) return; + const landed = folder.split("/")[0]; + if (landed && validSubtabIds.value.has(landed)) subTab.value = landed; } async function refreshRom() { diff --git a/frontend/src/v2/components/GameDetails/MediaTab.vue b/frontend/src/v2/components/GameDetails/MediaTab.vue index e3558614a..cac190673 100644 --- a/frontend/src/v2/components/GameDetails/MediaTab.vue +++ b/frontend/src/v2/components/GameDetails/MediaTab.vue @@ -8,21 +8,21 @@ // * Subtab always rendered; the empty state drives the upload CTA // * The panel doubles as a drag-and-drop target (same affordance as the // Upload / Patcher views): drop files anywhere over it to upload -// * Upload goes through `romApi.uploadSoundtracks` +// * Upload goes through `useRomFileUpload`, into the soundtrack/ folder // // The soundtrack player is reused from v1 for now. import { RBtn, RDropzone, REmptyState, RIcon } from "@v2/lib"; import { computed, defineAsyncComponent, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; import { useRoute, useRouter } from "vue-router"; -import romApi from "@/services/api/rom"; import type { DetailedRom } from "@/stores/roms"; -import storeUpload from "@/stores/upload"; import { useCan } from "@/v2/composables/useCan"; -import { useConfirm } from "@/v2/composables/useConfirm"; +import { + ROM_UPLOAD_FOLDERS, + useRomFileUpload, +} from "@/v2/composables/useRomFileUpload"; import { useRomSoundtrack } from "@/v2/composables/useRomSoundtrack"; import { useRomSync } from "@/v2/composables/useRomSync"; -import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useSoundtrackActions } from "@/v2/composables/useSoundtrackActions"; const ManualSubtab = defineAsyncComponent( @@ -42,16 +42,14 @@ const ArtworkSubtab = defineAsyncComponent( ); const props = defineProps<{ rom: DetailedRom }>(); -const snackbar = useSnackbar(); -const confirm = useConfirm(); const soundtrackActions = useSoundtrackActions(); +const { uploadFiles } = useRomFileUpload(); const { tracks: soundtrackTracks, loading: soundtrackLoading, fallbackArtUrl: soundtrackArtUrl, } = useRomSoundtrack(() => props.rom); const { refetchRom } = useRomSync(); -const uploadStore = storeUpload(); const { t } = useI18n(); // Soundtrack upload / delete both gate on the ROM write grant, so read-only @@ -110,19 +108,6 @@ watch( }, ); -// ---------- Single-file -> folder conversion ---------- -// Soundtracks live inside the ROM folder, so uploading one to a single-file -// ROM promotes it to a folder ROM in place (the backend does this -// automatically on upload). Warn first since it is not reversible. -async function confirmFolderConversionIfNeeded(): Promise { - if (!props.rom.has_simple_single_file) return true; - return confirm({ - title: t("rom.convert-to-folder-title"), - body: t("rom.convert-to-folder-body"), - tone: "warning", - }); -} - // ---------- Subtab nav ---------- // We render the subtab list manually (not via RTabNav) because each // subtab's content panel owns its own section header with title + @@ -169,37 +154,7 @@ async function refreshRom() { // ---------- File handlers (shared by file input + drag-and-drop) ---------- async function handleSoundtrackFiles(files: File[]) { - if (files.length === 0) return; - if (!(await confirmFolderConversionIfNeeded())) return; - - const responses = await romApi.uploadSoundtracks({ - romId: props.rom.id, - filesToUpload: files, - }); - - const successful = responses.filter((r) => r.status === "fulfilled").length; - const failed = responses.length - successful; - - if (failed === 0) uploadStore.reset(); - - if (successful > 0) { - snackbar.success( - failed - ? t("rom.tracks-uploaded-with-failed", successful, { - named: { n: successful, failed }, - }) - : t("rom.tracks-uploaded-n", successful, { - named: { n: successful }, - }), - { icon: "mdi-check-bold", timeout: 3000 }, - ); - await refreshRom(); - } else { - snackbar.warning(t("rom.no-tracks-uploaded"), { - icon: "mdi-close-circle", - timeout: 5000, - }); - } + await uploadFiles(props.rom, ROM_UPLOAD_FOLDERS.soundtrack, files); } async function deleteSoundtrack(fileId: number) { diff --git a/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue b/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue index cc6052b85..787fb8d11 100644 --- a/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue +++ b/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue @@ -4,7 +4,7 @@ // * ROM — shared library screenshots stored in the ROM's // `screenshots/` folder (RomFile, category SCREENSHOT). Only // folder-based multi-file ROMs can host them. Public to every -// user who can see the ROM. Upload → `romApi.uploadScreenshots`. +// user who can see the ROM. Upload → `useRomFileUpload`. // * Mine — per-user screenshots stored under the user's asset folder. // Private by default, with a per-item public/private toggle. // Any ROM. Upload → `screenshotApi.uploadGalleryScreenshots`. @@ -24,6 +24,10 @@ import storeUpload from "@/stores/upload"; import type { ScreenshotItem } from "@/v2/components/GameDetails/ScreenshotsTab.vue"; import { useCan } from "@/v2/composables/useCan"; import { useConfirm } from "@/v2/composables/useConfirm"; +import { + ROM_UPLOAD_FOLDERS, + useRomFileUpload, +} from "@/v2/composables/useRomFileUpload"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { errorMessage } from "@/v2/utils/errorMessage"; @@ -50,6 +54,7 @@ const { t } = useI18n(); const snackbar = useSnackbar(); const confirm = useConfirm(); const { refetchRom } = useRomSync(); +const { uploadFiles } = useRomFileUpload(); const uploadStore = storeUpload(); const authStore = storeAuth(); const { user } = storeToRefs(authStore); @@ -58,17 +63,6 @@ const { user } = storeToRefs(authStore); // section writes per-user assets and stays available to everyone. const canEditRom = useCan("rom.edit"); -// Uploading per-ROM screenshots to a single-file ROM promotes it to a folder -// ROM in place (the backend converts on upload); warn before that happens. -async function confirmFolderConversionIfNeeded(): Promise { - if (!props.rom.has_simple_single_file) return true; - return confirm({ - title: t("rom.convert-to-folder-title"), - body: t("rom.convert-to-folder-body"), - tone: "warning", - }); -} - // ---------- ROM (shared) screenshots — RomFile-backed ---------- const romScreenshots = computed(() => { const cacheBust = encodeURIComponent(props.rom.updated_at); @@ -126,7 +120,7 @@ async function refreshRom() { await refetchRom(props.rom.id); } -// ---------- Upload result toast (shared by both upload paths) ---------- +// ---------- Upload result toast for the per-user gallery ---------- function reportUpload(responses: PromiseSettledResult[]) { const successful = responses.filter((r) => r.status === "fulfilled").length; const failed = responses.length - successful; @@ -155,14 +149,7 @@ const romDz = ref | null>(null); const myDz = ref | null>(null); async function handleRomFiles(files: File[]) { - if (files.length === 0) return; - if (!(await confirmFolderConversionIfNeeded())) return; - const responses = await romApi.uploadScreenshots({ - romId: props.rom.id, - filesToUpload: files, - }); - reportUpload(responses); - if (responses.some((r) => r.status === "fulfilled")) await refreshRom(); + await uploadFiles(props.rom, ROM_UPLOAD_FOLDERS.screenshots, files); } async function handleMyFiles(files: File[]) { diff --git a/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue b/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue index dda63f53f..d9feb8f44 100644 --- a/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue +++ b/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue @@ -11,6 +11,10 @@ import romApi from "@/services/api/rom"; import type { DetailedRom } from "@/stores/roms"; import { useCan } from "@/v2/composables/useCan"; import { useConfirm } from "@/v2/composables/useConfirm"; +import { + ROM_UPLOAD_FOLDERS, + useRomFileUpload, +} from "@/v2/composables/useRomFileUpload"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; @@ -46,6 +50,7 @@ const props = defineProps<{ rom: DetailedRom }>(); const snackbar = useSnackbar(); const confirm = useConfirm(); const { refetchRom } = useRomSync(); +const { uploadFiles } = useRomFileUpload(); const { t } = useI18n(); // Adding and removing walkthroughs both ride the ROMS write grant, matching @@ -124,22 +129,7 @@ async function confirmFolderConversionIfNeeded(): Promise { const walkthroughDz = ref | null>(null); async function handleFiles(files: File[]) { - if (files.length === 0) return; - if (!(await confirmFolderConversionIfNeeded())) return; - const responses = await romApi.uploadWalkthroughFiles({ - romId: props.rom.id, - filesToUpload: files, - }); - const ok = responses.filter((r) => r.status === "fulfilled").length; - if (ok > 0) { - await refreshRom(); - snackbar.success(t("rom.walkthrough-added"), { icon: "mdi-check-bold" }); - } else { - snackbar.error( - t("rom.walkthrough-add-failed", { error: t("common.unknown-error") }), - { icon: "mdi-close-circle" }, - ); - } + await uploadFiles(props.rom, ROM_UPLOAD_FOLDERS.walkthrough, files); } // ---------- Add from GameFAQs URL ---------- 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..1272dc185 --- /dev/null +++ b/frontend/src/v2/composables/useRomFileUpload/index.test.ts @@ -0,0 +1,120 @@ +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")]; + +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("explains a duplicate and keeps the failed entry in the upload toast", async () => { + uploadRoms.mockResolvedValue([ + { + status: "rejected", + reason: { isAxiosError: true, response: { status: 409 } }, + }, + ]); + 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-exists"); + 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([]))), + ); + 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..fe8dd5178 --- /dev/null +++ b/frontend/src/v2/composables/useRomFileUpload/index.ts @@ -0,0 +1,119 @@ +// 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, +// 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 }; + +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 results = await romApi.uploadRoms({ + platformId: rom.platform_id, + romId: rom.id, + folder, + filesToUpload: files, + }); + 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", + }); + } + // allSettled keeps the input order, so the index maps back to the file. + const firstFailed = results.findIndex((r) => r.status === "rejected"); + if (firstFailed >= 0) { + const rejected = results[firstFailed] as PromiseRejectedResult; + snackbar.error( + failureMessage(files[firstFailed].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 }; +}