Files
romm/backend/endpoints/roms/files.py
Sam Dornan 4542998510 fix(backend): make type ignores honest and replace mypy trunk-ignores with fixes (#4711)
* fix(backend): make type ignores match what mypy reports

Third in the staged series clearing the errors #4655 made visible.
Whole-project mypy: 91 errors in 26 files -> 64 in 23.

Twenty `# type: ignore[assignment]` comments in
endpoints/responses/rom.py never suppressed anything. The request-scoped
values `from_orm_with_request` attaches to a Rom (rom_user, has_notes,
user_saves and the rest) are not declared on the model, so mypy reports
`attr-defined`; it does so under 1.19 as well as 2.3, so the code was
wrong when the comments were written rather than drifting since. They
now name the error they were meant to silence.

Seventy-nine ignores across 24 files suppressed nothing at all under
`--warn-unused-ignores`, and are removed. One of them,
`utils/zip_cache.py`, keeps its `attr-defined` code for the private
`zipfile._get_compressor` and drops only `assignment`. The unused set is
identical under mypy 2.3.0 and 2.3.1, and removing them leaves the error
count unchanged under both, so none was quietly needed.

The two `filter` helpers typed as `[QueryT: Select | Update | Delete]`
bound the TypeVar to the union, so `query.filter(...)` returned the union
and could not be assigned back to `QueryT`. Constraining it to the three
types lets mypy check each one separately, and the callers are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

* fix(backend): replace mypy and ASYNC240 trunk-ignores with real fixes

A `trunk-ignore` only suppresses when Trunk runs the linter. Plain mypy
does not read them, so the 13 on mypy findings were all still errors to
`mypy .` and would fail a whole-project check. Each now has a fix.

endpoints/tasks.py: `common_data` was a plain dict literal unpacked into
eight TypedDict constructors, so mypy saw `dict[str, Any]` and could not
match its keys. It holds exactly the fields of BaseTaskStatusResponse and
is now annotated as one, so the unpacking is checked.

handler/metadata/gamelist_handler.py: both media maps were inferred as
`dict[str, str]`, so indexing the TypedDict with their keys was
unprovable. Their keys are now typed `GamelistMediaKey`, the Literal of
the TypedDict's fields. A misspelt map key is now an error at the entry;
before, only the index site could have noticed, and it was suppressed.

handler/metadata/playmatch_handler.py: `attr` was a bare `str`. A TypeIs
guard narrows it to the five lookup attributes, and the frozenset is
derived from that Literal so the names live in one place. mypy now checks
that each name is a real PlaymatchRomMatch key. It does not check that
each takes an int, since mypy is lenient about value types on a union key;
that still rests on which five names are listed.

endpoints/search.py: the per-source tuples mixed ROM-list and handler
types, which mypy joined to `object`. The dict is now annotated with what
the loop uses: Mapping rows and the MetadataHandler base.

tests/handler/metadata/test_launchbox_handler.py: `Path.stat()` inside an
async test (ASYNC240) now goes through `anyio.Path`, as the rest of the
codebase already does.

Whole-project mypy: 64 errors in 23 files -> 51 in 20, identical under
2.3.0 and 2.3.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

* fix(backend): keep gamelist media keys in one place

Review pointed out that `GamelistMediaKey` repeated all fourteen fields
of GamelistMetadataMedia. Python has no `keyof`, so any Literal of a
TypedDict's keys is a second declaration of them, and a field added to
the TypedDict would be left out of it without any error.

The three index sites go back to suppressing `literal-required`, now as
`# type: ignore[literal-required]` so plain mypy reads it as well as
Trunk. The TypedDict stays the only declaration of the key set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-22 16:02:39 -05:00

331 lines
12 KiB
Python

from datetime import datetime, timezone
from typing import Annotated
from anyio import Path
from fastapi import Body, HTTPException
from fastapi import Path as PathVar
from fastapi import Request, status
from fastapi.responses import Response
from starlette.responses import FileResponse
from config import DEV_MODE, DISABLE_DOWNLOAD_ENDPOINT_AUTH
from decorators.auth import protected_route
from endpoints.responses.rom import RomFileSchema, RomFileUserSchema
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from handler.auth.constants import Scope
from handler.auth.dependencies import assert_can, assert_rom_visible, get_permissions
from handler.database import db_rom_handler
from handler.filesystem import fs_rom_handler
from logger.formatter import BLUE
from logger.formatter import highlight as hl
from logger.logger import log
from models.permission import PermAction, PermEntity
from models.rom import DOCUMENT_CATEGORIES, RomFileCategory
from utils.audio_tags import guess_audio_media_type
from utils.media_types import (
guess_media_file_type,
is_allowed_document_file,
is_allowed_media_file,
is_html_document_file,
)
from utils.nginx import FileRedirectResponse
from utils.router import APIRouter
router = APIRouter()
# Signed 32-bit INT ceiling, the narrowest `last_page` column across our DBs.
MAX_LAST_PAGE = 2**31 - 1
@protected_route(
router.get,
"/{id}/files",
[Scope.ROMS_READ],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def get_romfile(
request: Request,
id: Annotated[int, PathVar(description="Rom file internal id.", ge=1)],
) -> RomFileSchema:
"""Retrieve a rom file by ID."""
file = db_rom_handler.get_rom_file_by_id(id)
if not file:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="File not found",
)
# Resolve back to the parent rom and enforce its visibility, so a file
# belonging to a hidden rom can't be read by direct RomFile.id.
rom = db_rom_handler.get_rom_visibility(file.rom_id)
if not rom:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="File not found",
)
assert_rom_visible(request, rom, not_found_detail="File not found")
return RomFileSchema.model_validate(file)
@protected_route(
router.get,
"/{id}/files/content/{file_name}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.ROMS_READ],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def get_romfile_content(
request: Request,
id: Annotated[int, PathVar(description="Rom file internal id.", ge=1)],
file_name: Annotated[str, PathVar(description="File name to download")],
):
"""Download a rom file."""
current_username = (
request.user.username if request.user.is_authenticated else "unknown"
)
file = db_rom_handler.get_rom_file_by_id(id)
if not file:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="File not found",
)
# 404-mask file bytes of roms hidden from the caller: resolve the parent
# rom and apply its visibility before serving any content.
rom = db_rom_handler.get_rom_visibility(file.rom_id)
if not rom:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="File not found",
)
assert_rom_visible(request, rom, not_found_detail="File not found")
log.info(
f"User {hl(current_username, color=BLUE)} is downloading {hl(file.file_name)}"
)
# Derive content type / disposition / download name from the trusted DB
# record, never from the client-supplied file_name path param — otherwise a
# caller could request the same bytes with an arbitrary extension to force a
# mismatched Content-Type while served inline (content-sniffing/XSS).
# Audio, images and videos are served inline so <audio>/<video>/<img> in the
# details view can render and seek them; everything else downloads.
if file.category == RomFileCategory.SOUNDTRACK:
media_type = guess_audio_media_type(file.file_name)
disposition = "inline"
elif file.category in DOCUMENT_CATEGORIES and is_allowed_document_file(
file.file_name
):
# Only document-category files (manuals, walkthroughs) are served inline
# so the in-page viewer can render them; a game/extra file that happens
# to end in .pdf/.md/.txt still downloads.
media_type = guess_media_file_type(file.file_name)
disposition = "inline"
elif is_allowed_media_file(file.file_name):
media_type = guess_media_file_type(file.file_name)
disposition = "inline"
else:
media_type = "application/octet-stream"
disposition = "attachment"
# Inline files are served under an explicit, trusted Content-Type; nosniff
# keeps the browser from sniffing them into anything script-capable (e.g. a
# Markdown manual into HTML).
headers = {"X-Content-Type-Options": "nosniff"} if disposition == "inline" else {}
# HTML documents are stored exactly as uploaded, so this CSP is what stops a
# crafted one running scripts or reaching the session origin.
if disposition == "inline" and is_html_document_file(file.file_name):
headers["Content-Security-Policy"] = "sandbox; default-src 'none'"
# Serve the file directly in development mode for emulatorjs
if DEV_MODE:
rom_path = fs_rom_handler.validate_path(file.full_path)
# Starlette sets Content-Length and honors Range natively — inline
# disposition lets <audio> seek via Range requests.
return FileResponse(
path=rom_path,
filename=file.file_name,
media_type=media_type,
content_disposition_type=disposition,
headers=headers,
)
# Otherwise proxy through nginx (which parses Range itself via X-Accel-Redirect)
return FileRedirectResponse(
download_path=Path(f"/library/{file.full_path}"),
disposition=disposition,
media_type=media_type,
headers=headers,
)
@protected_route(
router.delete,
"/{rom_id}/files/{file_id}",
[Scope.ROMS_WRITE],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def delete_rom_file(
request: Request,
rom_id: Annotated[int, PathVar(description="Rom internal id.", ge=1)],
file_id: Annotated[int, PathVar(description="Rom file internal id.", ge=1)],
) -> Response:
"""Delete a single file from a ROM."""
# Removing a game file destroys library content, so it needs the same
# DELETE grant the whole-ROM delete route requires. The sibling routes for
# manuals/soundtracks/screenshots settle for ROMS_WRITE because a category
# guard keeps them off the game files themselves.
assert_can(get_permissions(request), PermEntity.ROMS, PermAction.DELETE)
rom = db_rom_handler.get_rom_visibility_label(rom_id)
if not rom:
raise RomNotFoundInDatabaseException(rom_id)
assert_rom_visible(request, rom, not_found_detail="File not found")
rom_file = db_rom_handler.get_rom_file_by_id(file_id)
if not rom_file or rom_file.rom_id != rom.id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="File not found",
)
file_rel_path = rom_file.full_path
try:
await fs_rom_handler.remove_file(file_rel_path)
except FileNotFoundError:
log.warning(
f"ROM file {hl(file_rel_path)} not found on disk; "
f"removing DB row anyway"
)
except Exception as exc:
log.error(f"Error deleting ROM file {hl(file_rel_path)}", exc_info=exc)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="There was an error deleting the file",
) from exc
db_rom_handler.delete_rom_file(file_id)
log.info(
f"Deleted file {hl(rom_file.file_name)} from "
f"{hl(rom.name or 'ROM', color=BLUE)} [{hl(rom.fs_name)}]"
)
return Response()
def _assert_document_file(
rom_id: int, file_id: int, request: Request
) -> RomFileCategory:
"""Resolve a document-category file, enforcing parent-rom visibility."""
rom = db_rom_handler.get_rom_visibility(rom_id)
if not rom:
raise RomNotFoundInDatabaseException(rom_id)
assert_rom_visible(request, rom, not_found_detail="File not found")
rom_file = db_rom_handler.get_rom_file_by_id(file_id)
if (
not rom_file
or rom_file.rom_id != rom.id
or rom_file.category not in DOCUMENT_CATEGORIES
):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Document file not found",
)
return rom_file.category
@protected_route(
router.get,
"/{rom_id}/files/{file_id}/progress",
[Scope.ROMS_READ],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def get_rom_file_progress(
request: Request,
rom_id: Annotated[int, PathVar(description="Rom internal id.", ge=1)],
file_id: Annotated[int, PathVar(description="Rom file internal id.", ge=1)],
) -> RomFileUserSchema:
"""Get the current user's reading progress for a document file."""
_assert_document_file(rom_id, file_id, request)
state = db_rom_handler.get_rom_file_user(
rom_file_id=file_id, user_id=request.user.id
)
if state:
return RomFileUserSchema.model_validate(state)
# No stored progress yet: return a zeroed default so the client has a shape.
return RomFileUserSchema(
rom_file_id=file_id,
user_id=request.user.id,
progress=0.0,
last_page=None,
finished=False,
last_read_at=None,
)
@protected_route(
router.put,
"/{rom_id}/files/{file_id}/progress",
[Scope.ROMS_USER_WRITE],
responses={status.HTTP_404_NOT_FOUND: {}},
)
async def update_rom_file_progress(
request: Request,
rom_id: Annotated[int, PathVar(description="Rom internal id.", ge=1)],
file_id: Annotated[int, PathVar(description="Rom file internal id.", ge=1)],
body: Annotated[dict, Body()],
) -> RomFileUserSchema:
"""Upsert the current user's reading progress for a document file.
Self-service per-user state, so it takes ROMS_USER_WRITE rather than the
library-wide ROMS_WRITE, exactly as rom notes do.
"""
_assert_document_file(rom_id, file_id, request)
values: dict = {"last_read_at": datetime.now(timezone.utc)}
if "progress" in body:
try:
values["progress"] = min(1.0, max(0.0, float(body["progress"])))
except (TypeError, ValueError) as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="progress must be a number between 0 and 1",
) from exc
if "last_page" in body:
last_page = body["last_page"]
if last_page is not None:
try:
last_page = int(last_page)
except (TypeError, ValueError) as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="last_page must be an integer",
) from exc
# Bounded so an out-of-range value is a 400 rather than an integer
# column overflow at insert time.
if not 0 <= last_page <= MAX_LAST_PAGE:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"last_page must be between 0 and {MAX_LAST_PAGE}",
)
values["last_page"] = last_page
if "finished" in body:
values["finished"] = bool(body["finished"])
state = db_rom_handler.upsert_rom_file_user(
rom_file_id=file_id, user_id=request.user.id, values=values
)
return RomFileUserSchema.model_validate(state)