chore(mypy): require full annotations outside tests, type the setup responses (#4795)

This commit is contained in:
Sam Dornan
2026-09-26 15:31:00 -04:00
committed by GitHub
parent 71776206a1
commit 3750d6ff70
82 changed files with 476 additions and 311 deletions

View File

@@ -103,5 +103,5 @@ uv run pytest <path/file> # tests - affected files only, NEVER the whole
- Tests: pytest + pytest-asyncio, isolated per `pytest-xdist` worker (per-worker DBs); `fakeredis`; `pytest-recording` VCR cassettes mock external APIs; Hypothesis for property tests. Mirror the `backend/<area>/` layout under `backend/tests/`. First-time test DB setup: `docker exec -i romm-db-dev mariadb -uroot -p<pw> < backend/romm_test/setup.sql`.
- **Lint / format run through Trunk** (ruff, black, isort, bandit): `trunk fmt && trunk check`. CI enforces Trunk on every PR. Never bypass with `--no-verify`.
- **Type-check with mypy**, outside Trunk so it sees the project's packages: `uv run mypy --config-file ../.trunk/configs/mypy.ini .` from `backend/`. CI's `mypy.yml` requires zero errors.
- **Type-check with mypy**, outside Trunk so it sees the project's packages: `uv run mypy --config-file ../.trunk/configs/mypy.ini .` from `backend/`. CI's `mypy.yml` requires zero errors. Every function outside `tests/` needs full parameter and return annotations, and every `# type: ignore` names its error code.
- New/changed logic needs a test; new endpoints need endpoint tests.

View File

@@ -1,5 +1,6 @@
[mypy]
check_untyped_defs = True
disallow_untyped_defs = True
warn_unused_ignores = True
warn_redundant_casts = True
disable_error_code = import-untyped
@@ -7,6 +8,10 @@ enable_error_code = ignore-without-code
# INI configs take a regex here, not a TOML-style list.
exclude = (?x)(^|/)alembic/
# Test functions and fixtures stay unannotated; their bodies are still checked.
[mypy-tests.*,conftest]
disallow_untyped_defs = False
# Built from source only in the Docker image, so absent locally and in CI.
[mypy-sigil]
ignore_missing_imports = True

View File

@@ -6,7 +6,7 @@ import os
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Final, NotRequired, TypedDict
from typing import Any, Final, NotRequired, Self, TextIO, TypedDict
import pydash
import yaml
@@ -495,7 +495,7 @@ class Config:
STREAMING_ENABLED: bool
STREAMING_CONTAINERS: list[StreamingContainer]
def __init__(self, **entries):
def __init__(self, **entries: Any) -> None:
self.__dict__.update(entries)
def _raw_template(self, key: str, fallback: str) -> str:
@@ -555,14 +555,14 @@ class ConfigManager:
_config_file_writable: bool = False
_config_file_parse_error: str | None = None
def __new__(cls, *args, **kwargs):
def __new__(cls, *args: Any, **kwargs: Any) -> Self:
if cls._self is None:
cls._self = super().__new__(cls, *args, **kwargs)
return cls._self
# Tests require custom config path
def __init__(self, config_file: str = ROMM_USER_CONFIG_FILE):
def __init__(self, config_file: str = ROMM_USER_CONFIG_FILE) -> None:
self.config_file = config_file
try:
@@ -584,7 +584,7 @@ class ConfigManager:
self._parse_config()
self._validate_config()
def _safe_load_yaml(self, cf) -> dict:
def _safe_load_yaml(self, cf: TextIO) -> dict:
"""Load YAML, falling back to an empty config on syntax errors so the
app can still boot with defaults rather than crashing."""
try:
@@ -667,7 +667,7 @@ class ConfigManager:
query=query,
)
def _parse_config(self):
def _parse_config(self) -> None:
"""Parses each entry in the config.yml"""
self.config = Config(
@@ -988,7 +988,7 @@ class ConfigManager:
)
sys.exit(3)
def _validate_config(self):
def _validate_config(self) -> None:
"""Validates the config.yml file"""
self._check_retired_filesystem_keys()
@@ -1456,7 +1456,9 @@ class ConfigManager:
self.config.PLATFORMS_VERSIONS = platform_versions
self._update_config_file()
def add_exclusion(self, exclusion_type: ExclusionType, exclusion_value: str):
def add_exclusion(
self, exclusion_type: ExclusionType, exclusion_value: str
) -> None:
config_item = self.config.__getattribute__(exclusion_type)
if exclusion_value in config_item:
log.warning(
@@ -1468,7 +1470,9 @@ class ConfigManager:
self.config.__setattr__(exclusion_type, config_item)
self._update_config_file()
def remove_exclusion(self, exclusion_type: ExclusionType, exclusion_value: str):
def remove_exclusion(
self, exclusion_type: ExclusionType, exclusion_value: str
) -> None:
config_item = self.config.__getattribute__(exclusion_type)
try:

View File

@@ -94,7 +94,9 @@ def _raise_auth_error(request: Request) -> None:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
def _requires_scopes(scopes: list[Scope]):
def _requires_scopes(
scopes: list[Scope],
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""Scope guard mirroring starlette's `requires`, with a 401/403 split."""
def decorator(func: DecoratedCallable) -> DecoratedCallable:
@@ -113,7 +115,7 @@ def _requires_scopes(scopes: list[Scope]):
if is_async_callable(func):
@functools.wraps(func)
async def async_wrapper(*args, **kwargs) -> Any:
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
request = kwargs.get("request", args[idx] if idx < len(args) else None)
assert isinstance(request, Request)
if not has_required_scope(request, scopes):
@@ -123,7 +125,7 @@ def _requires_scopes(scopes: list[Scope]):
return async_wrapper # type: ignore[return-value]
@functools.wraps(func)
def sync_wrapper(*args, **kwargs) -> Any:
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
request = kwargs.get("request", args[idx] if idx < len(args) else None)
assert isinstance(request, Request)
if not has_required_scope(request, scopes):

View File

@@ -5,7 +5,7 @@ from urllib.parse import urlencode
from authlib.common.errors import AuthlibBaseError
from fastapi import BackgroundTasks, Body, Depends, HTTPException, Request, status
from fastapi.responses import RedirectResponse
from fastapi.security.http import HTTPBasic
from fastapi.security.http import HTTPBasic, HTTPBasicCredentials
from config import (
OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS,
@@ -117,7 +117,7 @@ def _record_password_reset_request(ip_address: str | None, user: User) -> None:
@router.post("/login")
def login(
request: Request,
credentials=Depends(HTTPBasic()), # noqa
credentials: HTTPBasicCredentials = Depends(HTTPBasic()), # noqa
) -> None:
"""Session login endpoint
@@ -208,6 +208,7 @@ async def token(
TokenResponse: TypedDict with the new generated token info
"""
user: User | None
# Support refreshing access tokens
if form_data.grant_type == "refresh_token":
token = form_data.refresh_token
@@ -326,7 +327,7 @@ async def token(
# OIDC login and callback endpoints
@router.get("/login/openid")
async def login_via_openid(request: Request):
async def login_via_openid(request: Request) -> RedirectResponse:
"""OIDC login endpoint
Args:
@@ -350,7 +351,7 @@ async def login_via_openid(request: Request):
@router.get("/oauth/openid")
async def auth_openid(request: Request):
async def auth_openid(request: Request) -> RedirectResponse:
"""OIDC callback endpoint
Args:

View File

@@ -245,7 +245,7 @@ def _resolve_firmware_content(request: Request, id: int) -> tuple[Firmware, Path
"/{id}/content/{file_name}",
[] if DISABLE_DOWNLOAD_ENDPOINT_AUTH else [Scope.FIRMWARE_READ],
)
def head_firmware_content(request: Request, id: int, file_name: str):
def head_firmware_content(request: Request, id: int, file_name: str) -> FileResponse:
"""Head firmware content endpoint
Args:
@@ -277,7 +277,7 @@ def get_firmware_content(
request: Request,
id: int,
file_name: str,
):
) -> FileResponse:
"""Download firmware endpoint
Args:

View File

@@ -33,7 +33,12 @@ from config import (
)
from config.config_manager import config_manager as cm
from decorators.auth import protected_route
from endpoints.responses.heartbeat import HeartbeatResponse
from endpoints.responses.heartbeat import (
HeartbeatResponse,
SetupExistingPlatform,
SetupLibraryResponse,
SetupPlatformsResponse,
)
from exceptions.fs_exceptions import PlatformAlreadyExistsException
from handler.auth.base_handler import reset_link_base_url
from handler.auth.constants import Scope
@@ -269,22 +274,18 @@ async def _probe_metadata_source(metadata_source: MetadataSource) -> bool:
"/setup/library",
[],
)
async def get_setup_library_info(request: Request):
async def get_setup_library_info(request: Request) -> SetupLibraryResponse:
"""Get library structure information for setup wizard.
Only accessible during initial setup (no admin users) or with authentication.
Returns:
- library_ready: whether the configured platforms folder exists on disk
- library_structure: the configured `filesystem.structure.default` template
- existing_platforms: list of objects with fs_slug and rom_count
- supported_platforms: list of all supported platforms with metadata
SetupLibraryResponse: The library folder state and the platforms to offer.
"""
# Check authentication - only allow public access if no admin users
# If admin users exist, this would need authentication (but won't be called during setup)
# If there are admin users already, enforce the USERS_WRITE scope.
if (
Scope.PLATFORMS_READ not in request.auth.scopes
and len(db_user_handler.get_admin_users()) > 0
@@ -316,7 +317,7 @@ async def get_setup_library_info(request: Request):
existing_platform_slugs = []
# Build existing platforms with rom counts
existing_platforms = []
existing_platforms: list[SetupExistingPlatform] = []
if library_ready and existing_platform_slugs:
for fs_slug in existing_platform_slugs:
rom_count = 0
@@ -368,7 +369,9 @@ async def get_setup_library_info(request: Request):
[],
status_code=status.HTTP_201_CREATED,
)
async def create_setup_platforms(request: Request, platform_slugs: list[str]):
async def create_setup_platforms(
request: Request, platform_slugs: list[str]
) -> SetupPlatformsResponse:
"""Create platform folders during setup wizard.
Only accessible during initial setup (no admin users) or with authentication.
@@ -377,12 +380,9 @@ async def create_setup_platforms(request: Request, platform_slugs: list[str]):
platform_slugs: List of platform fs_slugs to create
Returns:
- success: bool
- created_count: number of platforms created
- message: success or error message
SetupPlatformsResponse: How many platform folders were created.
"""
# If there are admin users already, enforce the USERS_WRITE scope.
if (
Scope.PLATFORMS_WRITE not in request.auth.scopes
and len(db_user_handler.get_admin_users()) > 0

View File

@@ -1,5 +1,7 @@
from typing import TypedDict
from .platform import PlatformSchema
class SystemDict(TypedDict):
VERSION: str
@@ -79,3 +81,23 @@ class HeartbeatResponse(TypedDict):
OIDC: OIDCDict
NOTIFICATIONS: NotificationsDict
TASKS: TasksDict
class SetupExistingPlatform(TypedDict):
fs_slug: str
rom_count: int
class SetupLibraryResponse(TypedDict):
# Whether the configured platforms folder exists on disk.
library_ready: bool
# The configured `filesystem.structure.default` template.
library_structure: str
existing_platforms: list[SetupExistingPlatform]
supported_platforms: list[PlatformSchema]
class SetupPlatformsResponse(TypedDict):
success: bool
created_count: int
message: str

View File

@@ -952,7 +952,7 @@ async def download_roms(
description="Name for the zip file (optional).",
),
] = None,
):
) -> Response:
"""Download a list of roms as a zip file."""
current_username = (
@@ -1312,7 +1312,7 @@ async def head_rom_content(
description="Comma-separated list of file ids to download for multi-part roms."
),
] = None,
):
) -> Response:
"""Retrieve head information for a rom file download."""
rom = db_rom_handler.get_rom(id)
@@ -1413,7 +1413,7 @@ async def get_rom_content(
"recorded as a player load rather than a download."
),
] = "download",
):
) -> Response:
"""Download a rom.
This endpoint serves the content of the requested rom, as:

View File

@@ -86,7 +86,7 @@ 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")],
):
) -> Response:
"""Download a rom file."""
current_username = (

View File

@@ -84,22 +84,11 @@ async def add_rom_manuals(
await fs_resource_handler.make_directory(manuals_path)
# Drop any prior manual stored under a different extension so the single
# primary manual stays unambiguous (the glob matches `{rom.id}.*`).
for allowed_ext in ALLOWED_MANUAL_EXTENSIONS:
if allowed_ext == ext:
continue
stale = fs_resource_handler.validate_path(
f"{manuals_path}/{rom.id}{allowed_ext}"
)
if stale.exists():
stale.unlink()
parser = StreamingFormDataParser(headers=request.headers)
parser.register("x-upload-platform", NullTarget())
parser.register(safe_field_name, FileTarget(str(file_location)))
def cleanup_partial_file():
def cleanup_partial_file() -> None:
if file_location.exists():
file_location.unlink()
@@ -118,6 +107,17 @@ async def add_rom_manuals(
detail="There was an error uploading the manual",
) from exc
# Drop a prior manual under another extension (the glob matches `{rom.id}.*`),
# only once the upload has landed so a failed one keeps the old manual.
for allowed_ext in ALLOWED_MANUAL_EXTENSIONS:
if allowed_ext == ext:
continue
stale = fs_resource_handler.validate_path(
f"{manuals_path}/{rom.id}{allowed_ext}"
)
if stale.exists():
stale.unlink()
# An uploaded manual and a scraped one share this path, so only the lock
# tells them apart.
db_rom_handler.update_rom(

View File

@@ -74,7 +74,7 @@ async def patch_rom(
description="A patch file uploaded from the client, applied without being stored in the library.",
),
] = None,
):
) -> FileResponse:
"""Apply a patch to a ROM file server-side and return the patched file.
The base ROM file must exist in the library. The patch is supplied either

View File

@@ -76,7 +76,7 @@ async def _playable_rom_id(sid: str, game_id: Any) -> int | None:
try:
rom_id = int(game_id)
except (TypeError, ValueError):
except TypeError, ValueError:
return None
rom = db_rom_handler.get_rom_visibility(rom_id)
@@ -126,7 +126,9 @@ def _player_info(
)
async def _enter_room(sid: str, session_id: str, player_id: str, room: NetplayRoom):
async def _enter_room(
sid: str, session_id: str, player_id: str, room: NetplayRoom
) -> None:
await netplay_socket_handler.socket_server.enter_room(sid, _socket_room(session_id))
await _save_session(
sid, {ROOM_SESSION_KEY: session_id, PLAYER_SESSION_KEY: player_id}
@@ -137,7 +139,7 @@ async def _enter_room(sid: str, session_id: str, player_id: str, room: NetplayRo
@netplay_socket_handler.socket_server.on("open-room")
async def open_room(sid: str, data: RoomData):
async def open_room(sid: str, data: RoomData) -> str | None:
extra_data = data["extra"]
session_id = extra_data.get("sessionid")
@@ -173,10 +175,13 @@ async def open_room(sid: str, data: RoomData):
)
await netplay_handler.set(session_id, new_room)
await _enter_room(sid, session_id, player_id, new_room)
return None
@netplay_socket_handler.socket_server.on("join-room")
async def join_room(sid: str, data: RoomData):
async def join_room(
sid: str, data: RoomData
) -> str | tuple[None, dict[str, NetplayPlayerInfo]]:
extra_data = data["extra"]
session_id = extra_data.get("sessionid")
@@ -224,7 +229,7 @@ async def _is_room_peer(sid: str, target: str) -> bool:
return sid in peers and target in peers
async def _handle_leave(sid: str, session_id: str, player_id: str):
async def _handle_leave(sid: str, session_id: str, player_id: str) -> None:
current_room = await netplay_handler.get(session_id)
if not current_room:
return
@@ -262,7 +267,7 @@ async def leave_room(sid: str) -> None:
@netplay_socket_handler.socket_server.on("webrtc-signal")
async def webrtc_signal(sid: str, data: WebRTCSignalData):
async def webrtc_signal(sid: str, data: WebRTCSignalData) -> None:
target = data.get("target")
# Signals relay only between peers of one room, so a client cannot inject an
# offer or answer into a session it never joined.
@@ -284,17 +289,17 @@ async def webrtc_signal(sid: str, data: WebRTCSignalData):
@netplay_socket_handler.socket_server.on("webrtc-signal-error")
async def webrtc_signal_error(_sid: str, _error: str, _data: Any):
async def webrtc_signal_error(_sid: str, _error: str, _data: Any) -> None:
pass
@netplay_socket_handler.socket_server.on("disconnect")
async def disconnect(sid: str):
async def disconnect(sid: str) -> None:
await netplay_socket_handler.unbind_from_login_session(sid)
await leave_room(sid)
async def _broadcast_to_room(sid: str, event: str, data: Any):
async def _broadcast_to_room(sid: str, event: str, data: Any) -> None:
session_id = (await netplay_socket_handler.get_session(sid)).get(ROOM_SESSION_KEY)
if session_id:
await netplay_socket_handler.socket_server.emit(
@@ -303,15 +308,15 @@ async def _broadcast_to_room(sid: str, event: str, data: Any):
@netplay_socket_handler.socket_server.on("data-message")
async def data_message(sid: str, data: Any):
async def data_message(sid: str, data: Any) -> None:
await _broadcast_to_room(sid, "data-message", data)
@netplay_socket_handler.socket_server.on("snapshot")
async def snapshot(sid: str, data: Any):
async def snapshot(sid: str, data: Any) -> None:
await _broadcast_to_room(sid, "snapshot", data)
@netplay_socket_handler.socket_server.on("input")
async def input(sid: str, data: Any):
async def input(sid: str, data: Any) -> None:
await _broadcast_to_room(sid, "input", data)

View File

@@ -199,7 +199,7 @@ class ScanStats:
updated_roms: int = 0
new_files: int = 0
def __post_init__(self):
def __post_init__(self) -> None:
# Lock for thread-safe updates
self._lock = asyncio.Lock()
self._unpublished = False
@@ -225,7 +225,9 @@ class ScanStats:
update_job_meta({"scan_stats": stats})
await socket_manager.emit("scan:update_stats", stats)
async def update(self, socket_manager: socketio.AsyncRedisManager, **kwargs):
async def update(
self, socket_manager: socketio.AsyncRedisManager, **kwargs: int
) -> None:
async with self._lock:
for key, value in kwargs.items():
if hasattr(self, key):
@@ -235,7 +237,9 @@ class ScanStats:
# to report as they happen.
await self._publish(socket_manager, force=True)
async def increment(self, socket_manager: socketio.AsyncRedisManager, **kwargs):
async def increment(
self, socket_manager: socketio.AsyncRedisManager, **kwargs: int
) -> None:
async with self._lock:
for key, value in kwargs.items():
if hasattr(self, key):
@@ -1343,7 +1347,7 @@ async def scan_platforms(
total_roms=total_roms,
)
async def stop_scan():
async def stop_scan() -> None:
log.info(f"{emoji.EMOJI_STOP_SIGN} Scan stopped manually")
await finish("scan:done", scan_stats.to_dict(), stopped=True)
redis_client.delete(STOP_SCAN_FLAG)
@@ -1509,7 +1513,7 @@ async def authorize_scan(sid: str) -> User | None:
@socket_handler.socket_server.on("scan")
async def scan_handler(sid: str, options: dict[str, Any]):
async def scan_handler(sid: str, options: dict[str, Any]) -> None:
"""Scan socket endpoint
Args:
@@ -1545,7 +1549,7 @@ async def scan_handler(sid: str, options: dict[str, Any]):
launchbox_remote_enabled = bool(options.get("launchbox_remote_enabled", True))
if DEV_MODE:
return await scan_platforms(
await scan_platforms(
platform_ids=platform_ids,
metadata_sources=metadata_sources,
scan_type=scan_type,
@@ -1554,8 +1558,9 @@ async def scan_handler(sid: str, options: dict[str, Any]):
platform_fs_slugs=platform_fs_slugs,
started_by_user_id=user.id,
)
return
return scan_queue.enqueue(
scan_queue.enqueue(
scan_platforms,
# A scan of named roms resolves its work from the database and is done
# in seconds, so it goes ahead of any library scan already waiting.
@@ -1575,7 +1580,7 @@ async def scan_handler(sid: str, options: dict[str, Any]):
@socket_handler.socket_server.on("scan:stop")
async def stop_scan_handler(sid: str):
async def stop_scan_handler(sid: str) -> None:
"""Stop scan socket endpoint"""
user = await authorize_scan(sid)

View File

@@ -1,5 +1,5 @@
class ConfigNotWritableException(Exception):
def __init__(self):
def __init__(self) -> None:
self.message = "Config file is not writable. Check config.yml permissions"
super().__init__(self.message)

View File

@@ -4,7 +4,7 @@ from logger.logger import log
class PlatformNotFoundInDatabaseException(Exception):
def __init__(self, id):
def __init__(self, id: int) -> None:
self.message = f"Platform with id '{id}' not found"
super().__init__(self.message)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=self.message)
@@ -14,7 +14,7 @@ class PlatformNotFoundInDatabaseException(Exception):
class RomNotFoundInDatabaseException(Exception):
def __init__(self, id):
def __init__(self, id: int) -> None:
self.message = f"Rom with id '{id}' not found"
super().__init__(self.message)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=self.message)
@@ -24,7 +24,7 @@ class RomNotFoundInDatabaseException(Exception):
class CollectionNotFoundInDatabaseException(Exception):
def __init__(self, id):
def __init__(self, id: int | str) -> None:
self.message = f"Collection with id '{id}' not found"
super().__init__(self.message)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=self.message)
@@ -34,7 +34,7 @@ class CollectionNotFoundInDatabaseException(Exception):
class CollectionPermissionError(Exception):
def __init__(self, id):
def __init__(self, id: int) -> None:
self.message = f"Permission denied for collection with id '{id}'"
super().__init__(self.message)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=self.message)
@@ -44,7 +44,7 @@ class CollectionPermissionError(Exception):
class CollectionAlreadyExistsException(Exception):
def __init__(self, name):
def __init__(self, name: str) -> None:
self.message = f"Collection with name '{name}' already exists"
super().__init__(self.message)
log.critical(self.message)
@@ -57,7 +57,7 @@ class CollectionAlreadyExistsException(Exception):
class MusicPlaylistNotFoundException(Exception):
def __init__(self, id):
def __init__(self, id: int) -> None:
self.message = f"Playlist with id '{id}' not found"
super().__init__(self.message)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=self.message)
@@ -67,7 +67,7 @@ class MusicPlaylistNotFoundException(Exception):
class MusicPlaylistPermissionError(Exception):
def __init__(self, id):
def __init__(self, id: int) -> None:
self.message = f"Permission denied for playlist with id '{id}'"
super().__init__(self.message)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=self.message)
@@ -77,7 +77,7 @@ class MusicPlaylistPermissionError(Exception):
class MusicPlaylistAlreadyExistsException(Exception):
def __init__(self, name):
def __init__(self, name: str | None) -> None:
self.message = f"Playlist with name '{name}' already exists"
super().__init__(self.message)
raise HTTPException(
@@ -89,14 +89,14 @@ class MusicPlaylistAlreadyExistsException(Exception):
class RomNotFoundInRetroAchievementsException(Exception):
def __init__(self, id):
def __init__(self, id: int) -> None:
self.message = f"Rom with id '{id}' does not exist on RetroAchievements"
super().__init__(self.message)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=self.message)
class SGDBInvalidAPIKeyException(Exception):
def __init__(self):
def __init__(self) -> None:
self.message = "Invalid SGDB API key"
super().__init__(self.message)
log.critical(self.message)

View File

@@ -5,7 +5,7 @@ FOLDER_STRUCT_MSG = "Check RomM folder structure here: https://docs.romm.app/lat
class FolderStructureNotMatchException(Exception):
def __init__(self):
def __init__(self) -> None:
self.message = f"Platforms not found. {FOLDER_STRUCT_MSG }"
super().__init__(self.message)
@@ -14,45 +14,45 @@ class FolderStructureNotMatchException(Exception):
class PlatformNotFoundException(Exception):
def __init__(self, platform: str):
def __init__(self, platform: str) -> None:
self.message = f"Platform {platform} not found"
super().__init__(self.message)
def __repr__(self):
def __repr__(self) -> str:
return self.message
class PlatformAlreadyExistsException(Exception):
def __init__(self, fs_slug: str):
def __init__(self, fs_slug: str) -> None:
self.message = f"Platform {fs_slug} already exists"
super().__init__(self.message)
def __repr__(self):
def __repr__(self) -> str:
return self.message
class RomsNotFoundException(Exception):
def __init__(self, platform: str):
def __init__(self, platform: str) -> None:
self.message = f"ROMs not found for platform {hl(platform, color=BLUE)}. {FOLDER_STRUCT_MSG }"
super().__init__(self.message)
def __repr__(self):
def __repr__(self) -> str:
return self.message
class RomAlreadyExistsException(Exception):
def __init__(self, rom_name: str):
def __init__(self, rom_name: str) -> None:
self.message = f"Can't rename: {hl(rom_name)} already exists"
super().__init__(self.message)
def __repr__(self):
def __repr__(self) -> str:
return self.message
class FirmwareNotFoundException(Exception):
def __init__(self, platform: str):
def __init__(self, platform: str) -> None:
self.message = f"Firmware not found for platform {hl(platform, color=BLUE)}. {FOLDER_STRUCT_MSG }"
super().__init__(self.message)
def __repr__(self):
def __repr__(self) -> str:
return self.message

View File

@@ -1,7 +1,7 @@
class TaskNotFoundException(Exception):
def __init__(self, name: str):
def __init__(self, name: str) -> None:
self.message = f"No task is registered under the name '{name}'"
super().__init__(self.message)
def __repr__(self):
def __repr__(self) -> str:
return self.message

View File

@@ -12,6 +12,7 @@ from passlib.context import CryptContext
from redis.exceptions import RedisError
from starlette.requests import HTTPConnection
import models.user
from config import (
EMAIL_ENABLED,
INVITE_TOKEN_EXPIRY_SECONDS,
@@ -36,6 +37,8 @@ from logger.formatter import highlight as hl
from logger.logger import log
from utils.urls import get_public_base_url
type UserWithClaims = tuple[models.user.User, dict[str, Any]]
oct_key = OctKey.import_key(ROMM_AUTH_SECRET_KEY)
# Anyone who knows a username can ask for its reset link, so its inbox gets at
@@ -109,7 +112,7 @@ class AuthHandler:
def hash_client_token(raw: str) -> str:
return hashlib.sha256(raw.encode()).hexdigest()
def verify_password(self, plain_password, hashed_password):
def verify_password(self, plain_password: str, hashed_password: str | None) -> bool:
try:
return self.pwd_context.verify(plain_password, hashed_password)
except ValueError:
@@ -117,10 +120,12 @@ class AuthHandler:
# and passlib raises on one it cannot identify.
return False
def get_password_hash(self, password):
def get_password_hash(self, password: str) -> str:
return self.pwd_context.hash(password)
def authenticate_user(self, username: str, password: str):
def authenticate_user(
self, username: str, password: str
) -> models.user.User | None:
from handler.database import db_user_handler
user = db_user_handler.get_user_by_username(username)
@@ -132,7 +137,9 @@ class AuthHandler:
return user
async def get_current_active_user_from_session(self, conn: HTTPConnection):
async def get_current_active_user_from_session(
self, conn: HTTPConnection
) -> models.user.User | None:
from handler.database import db_user_handler
issuer = conn.session.get("iss")
@@ -461,7 +468,7 @@ class OAuthHandler:
return token
async def consume_refresh_token(self, token: str):
async def consume_refresh_token(self, token: str) -> UserWithClaims:
from handler.database import db_user_handler
try:
@@ -496,7 +503,9 @@ class OAuthHandler:
return user, payload.claims
async def get_current_active_user_from_bearer_token(self, token: str):
async def get_current_active_user_from_bearer_token(
self, token: str
) -> UserWithClaims | tuple[None, None]:
from handler.database import db_user_handler
try:
@@ -527,7 +536,9 @@ class OAuthHandler:
class OpenIDHandler:
async def get_current_active_user_from_openid_token(self, token: Any):
async def get_current_active_user_from_openid_token(
self, token: Any
) -> UserWithClaims | tuple[None, None]:
from handler.audit_handler import SYSTEM_ACTOR, AuditActor, AuditTarget, record
from handler.database import db_user_handler
from models.audit_event import AuditAction

View File

@@ -15,6 +15,7 @@ Typical use inside a handler::
from __future__ import annotations
from collections.abc import Callable
from typing import TYPE_CHECKING
from fastapi import HTTPException, Request, status
@@ -76,7 +77,9 @@ def assert_can(
)
def require_permission(entity: PermEntity, action: PermAction):
def require_permission(
entity: PermEntity, action: PermAction
) -> Callable[[Request], ResolvedPermissions]:
"""FastAPI dependency factory for library-wide gating of a route.
Returns the resolved permissions so the handler can reuse them.

View File

@@ -1,5 +1,6 @@
import time
from collections import namedtuple
from typing import Any
from joserfc import jwt
from joserfc.errors import BadSignatureError
@@ -60,7 +61,7 @@ class SessionMiddleware:
if https_only: # Secure flag can be used with HTTPS only
self.security_flags += "; secure"
def _validate_jwt_payload(self, jwt_payload: jwt.Token):
def _validate_jwt_payload(self, jwt_payload: jwt.Token) -> dict[str, Any]:
if not isinstance(jwt_payload.claims, dict):
return {}

View File

@@ -13,6 +13,8 @@ from __future__ import annotations
from dataclasses import dataclass
from sqlalchemy.orm import Session
from config import KIOSK_MODE
from decorators.database import begin_session
from handler.auth.constants import FULL_SCOPES, READ_SCOPES, Scope
@@ -65,7 +67,7 @@ class ResolvedPermissions:
)
def _effective_group_id(user: User, *, session) -> int | None:
def _effective_group_id(user: User, *, session: Session) -> int | None:
"""The group a non-admin user follows: their own, else the server default.
Used by both the grant map and the hidden-entity lookup so a user with no
@@ -81,7 +83,7 @@ def _effective_group_id(user: User, *, session) -> int | None:
def _resolve_grant_map(
user: User, *, session
user: User, *, session: Session
) -> dict[tuple[PermEntity, PermAction], bool]:
"""Effective ``(entity, action) -> own_only`` map for a non-admin user."""
@@ -108,11 +110,7 @@ def _resolve_grant_map(
return base
def resolve_permissions(
user: User,
*,
session=None,
) -> ResolvedPermissions:
def resolve_permissions(user: User) -> ResolvedPermissions:
# Admins bypass everything -- no DB access needed.
if user.role == Role.ADMIN:
return ResolvedPermissions(
@@ -122,14 +120,14 @@ def resolve_permissions(
hidden_platform_ids=frozenset(),
hidden_rom_ids=frozenset(),
)
return _resolve_non_admin(user, session=session)
return _resolve_non_admin(user)
@begin_session
def _resolve_non_admin(
user: User,
*,
session=None,
session: Session = None, # type: ignore[assignment]
) -> ResolvedPermissions:
from handler.database import db_permission_handler
@@ -162,11 +160,7 @@ def _resolve_non_admin(
)
def compute_oauth_scopes(
user: User,
*,
session=None,
) -> list[Scope]:
def compute_oauth_scopes(user: User) -> list[Scope]:
"""Project a user's effective grants onto the coarse legacy ``Scope`` set.
Admins get the full set; the anonymous ``KIOSK_MODE`` visitor is capped to
@@ -177,14 +171,14 @@ def compute_oauth_scopes(
# FULL_SCOPES order (same as the non-admin path) to avoid token churn.
if user.role == Role.ADMIN:
return order_scopes(FULL_SCOPES)
return _compute_non_admin_scopes(user, session=session)
return _compute_non_admin_scopes(user)
@begin_session
def _compute_non_admin_scopes(
user: User,
*,
session=None,
session: Session = None, # type: ignore[assignment]
) -> list[Scope]:
grant_map = _resolve_grant_map(user, session=session)
scopes = set(

View File

@@ -4,6 +4,7 @@ from datetime import datetime
from sqlalchemy import ColumnElement, Select, String, cast, delete, func, or_, select
from sqlalchemy.orm import Session, joinedload
from sqlalchemy.orm.interfaces import LoaderOption
from decorators.database import begin_session
from models.audit_event import AuditCategory, AuditEvent, actions_in
@@ -15,7 +16,7 @@ from utils.database import LIKE_ESCAPE_CHAR, escape_like
from .base_handler import DBBaseHandler, affected_rows
def _with_actor():
def _with_actor() -> LoaderOption:
# Name and avatar only, the rest of a user row is large JSON.
return joinedload(AuditEvent.actor).load_only(
User.id, User.username, User.avatar_path, User.updated_at

View File

@@ -2,7 +2,7 @@ import logging
import time
from typing import Any, cast
from sqlalchemy import CursorResult, Result, create_engine, event
from sqlalchemy import Connection, CursorResult, Result, create_engine, event
from sqlalchemy.orm import sessionmaker
from config import DB_POOL_RECYCLE_SECONDS, DEV_SQL_ECHO
@@ -26,15 +26,27 @@ if DEV_SQL_ECHO:
@event.listens_for(sync_engine, "before_cursor_execute")
def before_cursor_execute(
conn, cursor, statement, parameters, context, executemany
):
conn: Connection,
cursor: Any,
statement: str,
parameters: Any,
context: Any,
executemany: bool,
) -> None:
context._query_start_time = time.time()
print("--------START--------")
print(f"SQL: {statement}")
print(f"Parameters: {parameters}")
@event.listens_for(sync_engine, "after_cursor_execute")
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
def after_cursor_execute(
conn: Connection,
cursor: Any,
statement: str,
parameters: Any,
context: Any,
executemany: bool,
) -> None:
total_time = time.time() - context._query_start_time
print(f"Execution time: {total_time:.4f} seconds")
print("--------END--------")

View File

@@ -652,7 +652,7 @@ class DBCollectionsHandler(DBBaseHandler):
rom_ids: Sequence[int],
membership_only: bool = False,
session: Session = None, # type: ignore[assignment]
):
) -> None:
"""Refresh the collections a handful of changed ROMs touch.
Editing one ROM rarely moves any collection, and asking whether given

View File

@@ -90,7 +90,7 @@ class DBFirmwareHandler(DBBaseHandler):
platform_id: int,
file_name: str,
session: Session = None, # type: ignore[assignment]
):
) -> Firmware | None:
return session.scalar(
select(Firmware)
.filter_by(platform_id=platform_id, file_name=file_name)

View File

@@ -3,6 +3,7 @@ from datetime import datetime, timezone
from sqlalchemy import delete, func, select, update
from sqlalchemy.orm import Session, joinedload
from sqlalchemy.orm.interfaces import LoaderOption
from decorators.database import begin_session
from models.notification import MAX_NOTIFICATIONS_PER_USER, Notification
@@ -11,7 +12,7 @@ from models.user import User
from .base_handler import DBBaseHandler, affected_rows
def _with_actor():
def _with_actor() -> LoaderOption:
# Name and avatar only, the rest of a user row is large JSON. Built per query,
# as touching `User` columns at import configures the mappers too early.
return joinedload(Notification.actor).load_only(

View File

@@ -419,7 +419,7 @@ def _create_metadata_id_case(
prefix: str,
id_column: ColumnElement,
platform_id_column: ColumnElement,
):
) -> ColumnElement:
return case(
(
id_column.isnot(None),
@@ -962,7 +962,7 @@ class DBRomsHandler(DBBaseHandler):
).all()
)
def filter_by_platform_id(self, query: Select, platform_id: int):
def filter_by_platform_id(self, query: Select, platform_id: int) -> Select:
return query.filter(Rom.platform_id == platform_id)
def _filter_by_platform_ids(
@@ -970,7 +970,7 @@ class DBRomsHandler(DBBaseHandler):
) -> Select:
return query.filter(Rom.platform_id.in_(platform_ids))
def _filter_by_collection_id(self, query: Select, collection_id: int):
def _filter_by_collection_id(self, query: Select, collection_id: int) -> Select:
# `collections_roms` is keyed on (collection_id, rom_id), so membership
# is an indexed subquery rather than a list of ids fetched into Python.
return query.filter(
@@ -983,7 +983,7 @@ class DBRomsHandler(DBBaseHandler):
def _filter_by_virtual_collection_id(
self, query: Select, virtual_collection_id: str
):
) -> Select:
from . import db_collection_handler
return query.filter(
@@ -1000,7 +1000,7 @@ class DBRomsHandler(DBBaseHandler):
session: Session,
smart_collection_id: int,
user_id: int | None,
):
) -> Select:
from . import db_collection_handler
smart_collection = db_collection_handler.get_smart_collection(
@@ -1128,7 +1128,7 @@ class DBRomsHandler(DBBaseHandler):
select(RomFile.rom_id.label("id")).where(or_(*file_predicates)),
]
def _filter_by_search_term(self, query: Select, search_term: str):
def _filter_by_search_term(self, query: Select, search_term: str) -> Select:
terms = [term.strip() for term in search_term.split("|")]
terms = [term for term in terms if term]
if not terms:
@@ -1293,7 +1293,7 @@ class DBRomsHandler(DBBaseHandler):
values: Sequence[str],
match_all: bool = False,
match_none: bool = False,
):
) -> Select:
if not values:
return query
@@ -1841,7 +1841,7 @@ class DBRomsHandler(DBBaseHandler):
*,
session: Session,
include_related: bool = True,
**kwargs,
**kwargs: Any,
) -> RomSelect:
"""The filtered, ordered query `get_roms_scalar` and `get_rom_ids` both run."""
order_by = kwargs.get("order_by", "")
@@ -1878,7 +1878,7 @@ class DBRomsHandler(DBBaseHandler):
self,
*,
session: Session = None, # type: ignore[assignment]
**kwargs,
**kwargs: Any,
) -> Sequence[Rom]:
query = self._scoped_roms_query(session=session, **kwargs)
return session.scalars(query).all()
@@ -1888,7 +1888,7 @@ class DBRomsHandler(DBBaseHandler):
self,
*,
session: Session = None, # type: ignore[assignment]
**kwargs,
**kwargs: Any,
) -> list[int]:
"""Every matching rom id, in query order."""
query = self._scoped_roms_query(
@@ -3401,7 +3401,7 @@ class DBRomsHandler(DBBaseHandler):
user_id: int,
rom_id: int,
session: Session = None, # type: ignore[assignment]
**fields,
**fields: Any,
) -> dict | None:
note = session.scalar(
select(RomNote)

View File

@@ -92,7 +92,7 @@ class DBScreenshotsHandler(DBBaseHandler):
@begin_session
def get_screenshot_by_id(
self,
id,
id: int,
session: Session = None, # type: ignore[assignment]
) -> Screenshot | None:
return session.get(Screenshot, id)

View File

@@ -1,6 +1,7 @@
from collections.abc import Sequence
from typing import Any
from sqlalchemy import and_, delete, func, not_, select, update
from sqlalchemy import Result, and_, delete, func, not_, select, update
from sqlalchemy.orm import QueryableAttribute, Session, load_only
from sqlalchemy.sql import Delete, Select, Update
@@ -115,7 +116,7 @@ class DBUsersHandler(DBBaseHandler):
self,
id: int,
session: Session = None, # type: ignore[assignment]
):
) -> Result[Any]:
return session.execute(
delete(User)
.where(User.id == id)

View File

@@ -124,11 +124,11 @@ class FSAssetsHandler(FSHandler):
def __init__(self) -> None:
super().__init__(base_path=ASSETS_BASE_PATH)
def user_folder_path(self, user: User):
def user_folder_path(self, user: User) -> str:
return os.path.join("users", user.fs_safe_folder_name)
# /users/557365723a31/profile
def build_avatar_path(self, user: User):
def build_avatar_path(self, user: User) -> str:
return os.path.join(self.user_folder_path(user), "profile")
def _build_asset_file_path(
@@ -138,7 +138,7 @@ class FSAssetsHandler(FSHandler):
platform_fs_slug: str,
rom_id: int,
emulator: str | None = None,
):
) -> str:
user_folder_path = self.user_folder_path(user)
assets_path = os.path.join(
user_folder_path, folder, platform_fs_slug, str(rom_id)
@@ -154,7 +154,7 @@ class FSAssetsHandler(FSHandler):
platform_fs_slug: str,
rom_id: int,
emulator: str | None = None,
):
) -> str:
return self._build_asset_file_path(
user, "saves", platform_fs_slug, rom_id, emulator
)
@@ -166,7 +166,7 @@ class FSAssetsHandler(FSHandler):
platform_fs_slug: str,
rom_id: int,
emulator: str | None = None,
):
) -> str:
return self._build_asset_file_path(
user, "states", platform_fs_slug, rom_id, emulator
)
@@ -178,13 +178,15 @@ class FSAssetsHandler(FSHandler):
platform_fs_slug: str,
rom_id: int,
emulator: str | None = None,
):
) -> str:
return self._build_asset_file_path(
user, "screenshots", platform_fs_slug, rom_id, emulator
)
# /users/557365723a31/memory_cards/pcsx2/{card_id}
def build_memory_cards_file_path(self, user: User, emulator: str, card_id: int):
def build_memory_cards_file_path(
self, user: User, emulator: str, card_id: int
) -> str:
# Not scoped by rom/platform: a memory card is per (user, emulator) and
# holds every game's saves. Versions share the folder, distinguished by
# their timestamped file names.

View File

@@ -5,7 +5,7 @@ import os
import re
import shutil
import tempfile
from collections.abc import Callable, Iterable, Sequence
from collections.abc import AsyncIterator, Callable, Iterable, Sequence
from contextlib import asynccontextmanager
from enum import Enum
from io import BytesIO
@@ -13,6 +13,7 @@ from pathlib import Path
from tempfile import SpooledTemporaryFile
from typing import BinaryIO, Final
from anyio import AsyncFile
from anyio import Path as AnyioPath
from anyio import open_file
from starlette.datastructures import UploadFile
@@ -370,7 +371,7 @@ class Asset(Enum):
class FSHandler:
def __init__(self, base_path: str):
def __init__(self, base_path: str) -> None:
self.base_path = Path(base_path).resolve()
self._locks: dict[str, asyncio.Lock] = {}
self._lock_mutex = asyncio.Lock()
@@ -474,7 +475,7 @@ class FSHandler:
return await self._compute_file_hash(file_path)
@asynccontextmanager
async def _atomic_write(self, target_path: Path):
async def _atomic_write(self, target_path: Path) -> AsyncIterator[Path]:
"""Context manager for atomic file writing.
Creates the temp file in the same directory as the target so the
@@ -659,7 +660,9 @@ class FSHandler:
raise ValueError("Unsupported file type for writing")
@asynccontextmanager
async def write_file_streamed(self, path: str, filename: str):
async def write_file_streamed(
self, path: str, filename: str
) -> AsyncIterator[AsyncFile[bytes]]:
"""
Write file to filesystem using a streamed approach.
@@ -727,7 +730,7 @@ class FSHandler:
async with await open_file(full_path, "rb") as f:
return await f.read()
async def stream_file(self, file_path: str):
async def stream_file(self, file_path: str) -> AsyncFile[bytes]:
"""
Stream file from filesystem.

View File

@@ -16,7 +16,7 @@ class FSFirmwareHandler(FSHandler):
def get_firmware_fs_structure(self, fs_slug: str) -> str:
return cm.get_config().firmware_structure.firmware_dir(fs_slug)
async def get_firmware(self, platform_fs_slug: str):
async def get_firmware(self, platform_fs_slug: str) -> list[str]:
"""Gets all filesystem firmware for a platform
Args:
@@ -28,9 +28,7 @@ class FSFirmwareHandler(FSHandler):
try:
fs_firmware_files = await self.list_files(path=firmware_path)
except FileNotFoundError as e:
raise FirmwareNotFoundException(
f"Firmware not found for platform {platform_fs_slug}"
) from e
raise FirmwareNotFoundException(platform_fs_slug) from e
return [f for f in self.exclude_single_files(fs_firmware_files)]

View File

@@ -13,7 +13,7 @@ class FSPlatformsHandler(FSHandler):
def __init__(self) -> None:
super().__init__(base_path=LIBRARY_BASE_PATH)
def _exclude_platforms(self, platforms: list):
def _exclude_platforms(self, platforms: list[str]) -> list[str]:
cnfg = cm.get_config()
return [
platform

View File

@@ -376,7 +376,7 @@ class FSResourcesHandler(FSHandler):
return path_cover_s, path_cover_l
async def remove_cover(self, entity: Rom | Collection | None):
async def remove_cover(self, entity: Rom | Collection | None) -> dict[str, str]:
if not entity:
return {"path_cover_s": "", "path_cover_l": ""}
@@ -515,7 +515,7 @@ class FSResourcesHandler(FSHandler):
full_path = self.validate_path(f"{rom.fs_resources_path}/screenshots")
return {path.stem for path in full_path.glob("*.jpg")}
def _get_screenshot_path(self, rom: Rom, idx: str):
def _get_screenshot_path(self, rom: Rom, idx: str) -> str:
"""Returns rom cover filesystem path adapted to frontend folder structure
Args:
@@ -568,7 +568,7 @@ class FSResourcesHandler(FSHandler):
for ext in ALLOWED_MANUAL_EXTENSIONS
)
async def _store_manual(self, rom: Rom, url_manual: str):
async def _store_manual(self, rom: Rom, url_manual: str) -> None:
manual_path = f"{rom.fs_resources_path}/manual"
await self.make_directory(manual_path)
@@ -665,7 +665,7 @@ class FSResourcesHandler(FSHandler):
await self._store_manual(rom, url_manual)
return self._get_manual_path(rom)
async def remove_manual(self, rom: Rom):
async def remove_manual(self, rom: Rom) -> None:
await self.remove_directory(f"{rom.fs_resources_path}/manual")
# Retroachievements

View File

@@ -1002,7 +1002,7 @@ class FSRomsHandler(FSHandler):
sha1_h = hashlib.sha1(usedforsecurity=False)
accumulate = rom_md5_h is not None and rom_sha1_h is not None
def update_hashes(chunk: bytes | bytearray):
def update_hashes(chunk: bytes | bytearray) -> None:
nonlocal crc_c, rom_crc_c
md5_h.update(chunk)

View File

@@ -346,11 +346,11 @@ def populate_rom_specific_paths(
class GamelistHandler(MetadataHandler):
"""Handler for ES-DE gamelist.xml metadata source"""
def __init__(self):
def __init__(self) -> None:
# Cache for storing parsed gamelist data by platform ID
self._gamelist_cache = {}
self._gamelist_cache: dict[int, dict[str, GamelistRom]] = {}
async def populate_cache(self, platform: Platform):
async def populate_cache(self, platform: Platform) -> None:
if not self.is_enabled():
return
@@ -362,7 +362,7 @@ class GamelistHandler(MetadataHandler):
# Parse the gamelist file
self._parse_gamelist_xml(gamelist_file_path, platform)
def clear_cache(self):
def clear_cache(self) -> None:
"""Clear the gamelist cache"""
self._gamelist_cache.clear()

View File

@@ -988,7 +988,7 @@ class IGDBHandler(MetadataHandler):
class TwitchAuth(MetadataHandler):
def __init__(self):
def __init__(self) -> None:
self.BASE_URL = "https://id.twitch.tv/oauth2/token"
self.params = {
"client_id": IGDB_CLIENT_ID,

View File

@@ -123,7 +123,7 @@ class PlaymatchHandler(MetadataHandler):
Handler for [Playmatch](https://github.com/RetroRealm/playmatch), a service for matching ROMs by Hashes.
"""
def __init__(self):
def __init__(self) -> None:
self.base_url = PLAYMATCH_API_URL
self.identify_url = f"{self.base_url}/identify/ids"
self.healthcheck_url = f"{self.base_url}/health"

View File

@@ -2,7 +2,7 @@ import json
import os
import re
import time
from datetime import datetime
from datetime import datetime, timezone
from typing import NotRequired, TypedDict, cast
import pydash
@@ -87,15 +87,16 @@ class RAUserProgression(TypedDict):
def extract_metadata_from_rom_details(
rom: Rom, rom_details: RAGameExtendedDetails
) -> RAMetadata:
def parse_release_timestamp():
def parse_release_timestamp() -> int | None:
release_date_str = rom_details.get("Released")
if not release_date_str:
return None
try:
# Extract date part (assuming format: "YYYY-MM-DD [additional info]")
# Extract date part (assuming format: "YYYY-MM-DD [additional info]"),
# pinned to UTC midnight so the host's offset never shifts the day.
parsed_date = datetime.strptime(release_date_str.split()[0], "%Y-%m-%d")
return int(parsed_date.timestamp())
return int(parsed_date.replace(tzinfo=timezone.utc).timestamp())
except AttributeError, ValueError, IndexError:
return None

View File

@@ -25,7 +25,7 @@ class NetplayRoom(TypedDict):
class NetplayHandler:
"""A class to handle netplay rooms in Redis."""
def __init__(self):
def __init__(self) -> None:
self.hash_name = "netplay:rooms"
async def get(self, room_id: str) -> NetplayRoom | None:
@@ -33,11 +33,11 @@ class NetplayHandler:
room = await async_cache.hget(self.hash_name, room_id)
return json.loads(room) if room else None
async def set(self, room_id: str, room_data: NetplayRoom):
async def set(self, room_id: str, room_data: NetplayRoom) -> int:
"""Set a room in Redis."""
return await async_cache.hset(self.hash_name, room_id, json.dumps(room_data))
async def delete(self, room_ids: list[str]):
async def delete(self, room_ids: list[str]) -> int:
"""Delete a room from Redis."""
return await async_cache.hdel(self.hash_name, *room_ids)

View File

@@ -1,7 +1,7 @@
import asyncio
import enum
import functools
from typing import Any
from typing import Any, NotRequired, TypedDict
import pydash
import socketio
@@ -223,7 +223,7 @@ def build_hashless_fs_rom(fs_name: str, fs_path: str, *, flat: bool) -> FSRom:
return build_empty_fs_rom(fs_name, fs_path, flat=flat)
def get_main_platform_igdb_id(platform: Platform):
def get_main_platform_igdb_id(platform: Platform) -> int | None:
cnfg = cm.get_config()
main_platform_slug = cnfg.PLATFORMS_VERSIONS.get(platform.fs_slug.lower())
@@ -1817,11 +1817,20 @@ async def download_rom_resources(
await fs_resource_handler.store_ra_badge(badge_url, badge_path)
async def _scan_asset(file_name: str, asset_path: str, should_hash: bool = False):
class ScannedAsset(TypedDict):
file_path: str
file_name: str
file_size_bytes: int
content_hash: NotRequired[str | None]
async def _scan_asset(
file_name: str, asset_path: str, should_hash: bool = False
) -> ScannedAsset:
file_path = f"{asset_path}/{file_name}"
file_size = await fs_asset_handler.get_file_size(file_path)
result = {
result: ScannedAsset = {
"file_path": asset_path,
"file_name": file_name,
"file_size_bytes": file_size,

View File

@@ -159,7 +159,7 @@ class Formatter(logging.Formatter):
return redact_sensitive(output)
def highlight(msg: str = "", color=YELLOW) -> str:
def highlight(msg: str = "", color: str = YELLOW) -> str:
"""
Highlights the message to send to the fancylog.

View File

@@ -162,7 +162,7 @@ class VirtualCollection(BaseModel):
return base64.urlsafe_b64encode(data.encode()).decode()
@classmethod
def from_id(cls, id_: str):
def from_id(cls, id_: str) -> tuple[str, str]:
data = json.loads(base64.urlsafe_b64decode(id_).decode())
return data["name"], data["type"]

View File

@@ -157,11 +157,11 @@ class User(BaseModel, SimpleUser):
return compute_oauth_scopes(self)
@property
def fs_safe_folder_name(self):
def fs_safe_folder_name(self) -> str:
# Uses the ID to avoid issues with username changes
return f"User:{self.id}".encode().hex()
def set_last_active(self):
def set_last_active(self) -> None:
from handler.database import db_user_handler
db_user_handler.update_user(

View File

@@ -32,7 +32,7 @@ from handler.filesystem import fs_asset_handler, get_fs_sync_handler
from handler.sync.comparison import compare_save_state
from logger.formatter import highlight as hl
from logger.logger import log
from models.device import SyncMode
from models.device import Device, SyncMode
from models.sync_session import SyncSessionStatus
from utils import get_version
@@ -205,7 +205,11 @@ def _process_device_incoming(
def _process_incoming_file(
device, session_id: int, platform_slug: str, filename: str, full_path: str
device: Device,
session_id: int,
platform_slug: str,
filename: str,
full_path: str,
) -> None:
"""Process a single incoming file from a device's sync folder."""
from endpoints.sockets.sync import emit_sync_conflict

View File

@@ -17,7 +17,7 @@ class CleanupMissingFirmwareStats:
firmware_deleted: int = 0
errors: int = 0
def update(self, **kwargs) -> None:
def update(self, **kwargs: object) -> None:
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)
@@ -29,7 +29,7 @@ class CleanupMissingFirmwareStats:
class CleanupMissingFirmwareTask(Task):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Cleanup missing firmware",
description="Delete all firmware flagged as missing from the filesystem from the database",

View File

@@ -18,7 +18,7 @@ class CleanupMissingRomsStats:
roms_deleted: int = 0
errors: int = 0
def update(self, **kwargs) -> None:
def update(self, **kwargs: object) -> None:
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)
@@ -30,7 +30,7 @@ class CleanupMissingRomsStats:
class CleanupMissingRomsTask(Task):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Cleanup missing ROMs",
description="Delete all ROMs flagged as missing from the filesystem from the database",

View File

@@ -10,7 +10,7 @@ class UpdateStats:
processed: int = 0
total: int = 0
def update(self, **kwargs) -> None:
def update(self, **kwargs: int) -> None:
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)

View File

@@ -17,7 +17,7 @@ from . import UpdateStats
class BuildRecommendationsTask(PeriodicTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Build recommendations index",
description=(

View File

@@ -11,7 +11,7 @@ DELETE_BATCH_SIZE: Final = 5000
class CleanupAuditLogTask(PeriodicTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Scheduled audit log cleanup",
description=f"Removes audit log events older than {AUDIT_LOG_RETENTION_DAYS} days",

View File

@@ -4,7 +4,7 @@ from tasks.tasks import PeriodicTask, TaskType
class CleanupNetplayTask(PeriodicTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Scheduled netplay cleanup",
description="Cleans up empty netplay rooms",

View File

@@ -55,7 +55,7 @@ class CleanupStats:
removed_fs_platforms: int = 0
removed_fs_roms: int = 0
def update(self, **kwargs) -> None:
def update(self, **kwargs: int) -> None:
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)
@@ -74,7 +74,7 @@ class CleanupStats:
class CleanupOrphanedResourcesTask(PeriodicTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Cleanup orphaned resources",
description="Clean up orphaned resources in the ROMs directory",

View File

@@ -10,7 +10,7 @@ STALE_AFTER_HOURS = 24
class CleanupSyncSessionsTask(PeriodicTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Scheduled sync session cleanup",
description="Fails sync sessions no client ever completed",

View File

@@ -7,7 +7,7 @@ from tasks.tasks import PeriodicTask, TaskType
class CleanupUploadTmpTask(PeriodicTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Scheduled upload tmp cleanup",
description="Cleans up orphaned chunked-upload temp directories",

View File

@@ -4,7 +4,7 @@ from utils.zip_cache import cleanup_stale_zips
class CleanupZipCacheTask(PeriodicTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Scheduled ZIP cache cleanup",
description="Removes stale cached ZIP files based on tiered TTL",

View File

@@ -42,7 +42,7 @@ class ImageConverter:
"YCbCr": "RGB", # YCbCr to RGB
}
def __init__(self, quality: int = 90):
def __init__(self, quality: int = 90) -> None:
self.quality = quality
def _convert_image_mode(self, img: Image.Image) -> Image.Image:
@@ -108,7 +108,7 @@ class ConversionStats:
errors: int = 0
total: int = 0
def update(self, **kwargs) -> None:
def update(self, **kwargs: int) -> None:
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)
@@ -126,7 +126,7 @@ class ConversionStats:
class ConvertImagesToWebPTask(PeriodicTask):
"""Task to convert existing images to WebP format."""
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Convert images to WebP",
description="Convert existing image files (PNG, JPG, BMP, TIFF, GIF) to WebP format for better performance",

View File

@@ -40,7 +40,7 @@ async def _reap(
class ReapStreamingSessionsTask(PeriodicTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Scheduled streaming session reaper",
description="Stops streaming sessions whose player stopped sending heartbeats",

View File

@@ -28,7 +28,7 @@ from tasks.tasks import PeriodicTask, TaskType
class ScanLibraryTask(PeriodicTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Scheduled rescan",
description="Rescans the entire library",

View File

@@ -86,7 +86,7 @@ def _sync_rom_user_statuses(user: User, user_progression: RAUserProgression) ->
class SyncRetroAchievementsProgressTask(PeriodicTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Scheduled RetroAchievements progress sync",
task_type=TaskType.UPDATE,

View File

@@ -50,7 +50,7 @@ LAUNCHBOX_TASK_TIMEOUT: Final[int] = max(TASK_TIMEOUT, 30 * 60)
class BatchedCacheWriter:
"""Queues cache writes on a pipeline, flushing every `batch_size` entries."""
def __init__(self, pipe: Pipeline, batch_size: int | None = None):
def __init__(self, pipe: Pipeline, batch_size: int | None = None) -> None:
self._pipe = pipe
self._batch_size = batch_size or CACHE_WRITE_BATCH_SIZE
self._queued = 0
@@ -101,7 +101,7 @@ def _iter_elements(source: Any) -> Iterator[Any]:
class UpdateLaunchboxMetadataTask(RemoteFilePullTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Scheduled LaunchBox metadata update",
description="Updates the LaunchBox metadata store",

View File

@@ -30,7 +30,7 @@ SWITCH_TITLEDB_STORE: Final = VersionedCacheStore(
class UpdateSwitchTitleDBTask(RemoteFilePullTask):
def __init__(self):
def __init__(self) -> None:
super().__init__(
title="Scheduled Switch TitleDB update",
description="Updates the Nintendo Switch TitleDB file",

View File

@@ -8,6 +8,7 @@ import os
from datetime import datetime, timezone
from typing import Any
import asyncssh
from anyio import Path as AnyioPath
from anyio import open_file
@@ -22,7 +23,7 @@ from handler.database import (
)
from handler.filesystem import fs_asset_handler
from handler.sync.comparison import compare_save_state
from handler.sync.ssh_handler import get_ssh_sync_handler
from handler.sync.ssh_handler import RemoteSaveInfo, get_ssh_sync_handler
from logger.formatter import highlight as hl
from logger.logger import log
from models.device import Device, SyncMode
@@ -217,8 +218,8 @@ async def _sync_device(device: Device, session_id: int | None = None) -> dict:
async def _process_remote_save(
device: Device,
conn,
remote_save,
conn: asyncssh.SSHClientConnection,
remote_save: RemoteSaveInfo,
session_id: int,
) -> str:
"""Process a single remote save file. Returns action taken."""
@@ -356,8 +357,8 @@ async def _process_remote_save(
async def _push_missing_saves(
device: Device,
conn,
remote_saves,
conn: asyncssh.SSHClientConnection,
remote_saves: list[RemoteSaveInfo],
save_directories: list[dict],
) -> int:
"""Push server saves that are missing from the device."""

View File

@@ -132,6 +132,31 @@ def test_upload_manual_to_resources_drops_stale_other_extension(
assert not (manual_fs_resources / f"{rom.id}.pdf").exists()
def test_upload_manual_to_resources_failure_keeps_other_extension(
client: TestClient,
access_token: str,
rom: Rom,
manual_fs_resources: Path,
mocker: MockerFixture,
):
(manual_fs_resources / f"{rom.id}.pdf").write_bytes(PDF_BYTES)
mocker.patch.object(
manual_endpoint.StreamingFormDataParser,
"data_received",
side_effect=RuntimeError("stream broke"),
)
response = client.post(
f"/api/roms/{rom.id}/manuals",
headers={**_auth(access_token), "x-upload-filename": "README.md"},
files={"README.md": ("README.md", MD_BYTES, "text/markdown")},
)
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
assert (manual_fs_resources / f"{rom.id}.pdf").read_bytes() == PDF_BYTES
assert not (manual_fs_resources / f"{rom.id}.md").exists()
def test_upload_manual_to_resources_rom_not_found(
client: TestClient,
access_token: str,

View File

@@ -601,6 +601,7 @@ async def test_oidc_valid_no_edit_user_role_if_claim_not_in_userinfo(
# The user's existing ADMIN role should be preserved
mock_edit_user.assert_not_called()
assert user is not None
assert user.role == Role.ADMIN

View File

@@ -1,3 +1,7 @@
import os
import time
from collections.abc import Iterator
from contextlib import contextmanager
from unittest.mock import AsyncMock
from utils.cache import VersionedCacheStore
@@ -11,3 +15,19 @@ def schema_stamp_get(*stores: VersionedCacheStore) -> AsyncMock:
return stamps.get(key)
return AsyncMock(side_effect=get)
@contextmanager
def local_timezone(name: str) -> Iterator[None]:
"""Pin the process timezone that a naive datetime.timestamp() reads."""
previous = os.environ.get("TZ")
os.environ["TZ"] = name
time.tzset()
try:
yield
finally:
if previous is None:
os.environ.pop("TZ", None)
else:
os.environ["TZ"] = previous
time.tzset()

View File

@@ -1,13 +1,10 @@
"""Property-based tests for the LaunchBox metadata parsing helpers."""
import os
import time
from collections.abc import Iterator
from contextlib import contextmanager
from datetime import datetime
from hypothesis import assume, given
from hypothesis import strategies as st
from tests.handler.metadata.conftest import local_timezone
from handler.metadata.launchbox_handler.utils import (
dedupe_words,
@@ -19,22 +16,6 @@ from handler.metadata.launchbox_handler.utils import (
LB_INVALID_CHARS = set("\\/|<>\"?*:'")
@contextmanager
def local_timezone(name: str) -> Iterator[None]:
"""Pin the process timezone that a naive datetime.timestamp() reads."""
previous = os.environ.get("TZ")
os.environ["TZ"] = name
time.tzset()
try:
yield
finally:
if previous is None:
os.environ.pop("TZ", None)
else:
os.environ["TZ"] = previous
time.tzset()
class TestParseList:
@given(st.text() | st.none())
def test_elements_are_stripped_and_non_empty(self, value):

View File

@@ -1,11 +1,15 @@
"""Tests for the RetroAchievements metadata handler."""
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import cast
from unittest.mock import AsyncMock, MagicMock
import pytest
from tests.handler.metadata.conftest import local_timezone
from adapters.services.retroachievements_types import RAGameExtendedDetails
from handler.metadata import ra_handler
from handler.metadata.ra_handler import RA_PLATFORM_LIST, RAHandler
from utils.platform_slugs import UniversalPlatformSlug as UPS
@@ -28,6 +32,16 @@ def test_platform_list_uses_ups_keys():
assert isinstance(key, UPS)
def test_release_date_is_utc_midnight_whatever_the_host_timezone():
# CI runs in UTC, so a naive timestamp only shows its drift under another zone.
details = cast(RAGameExtendedDetails, {"Released": "1991-08-23 00:00:00"})
with local_timezone("Asia/Tokyo"):
metadata = ra_handler.extract_metadata_from_rom_details(MagicMock(), details)
expected = datetime(1991, 8, 23, tzinfo=timezone.utc).timestamp()
assert metadata["first_release_date"] == int(expected)
class TestSearchRom:
"""The hash index must only map hashes of games that actually have a set."""

View File

@@ -29,13 +29,16 @@ from typing import Any
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from PIL import Image # noqa: E402
from sqlalchemy import Connection, insert # noqa: E402
from sqlalchemy.engine.interfaces import DBAPIConnection # noqa: E402
from sqlalchemy.pool import ConnectionPoolEntry # noqa: E402
from adapters.services.igdb import IGDB_PLATFORM_LIST # noqa: E402
from config import RESOURCES_BASE_PATH # noqa: E402
from handler.metadata.moby_handler import MOBYGAMES_PLATFORM_LIST # noqa: E402
from handler.metadata.ss_handler import SCREENSAVER_PLATFORM_LIST # noqa: E402
from models.assets import Save, Screenshot, State # noqa: E402
from models.base import compute_file_name_parts # noqa: E402
from models.base import BaseModel, compute_file_name_parts # noqa: E402
from models.client_token import ClientToken # noqa: E402
from models.collection import ( # noqa: E402
Collection,
@@ -417,7 +420,7 @@ def slugify(value: str) -> str:
class Ids:
"""Hands out monotonically increasing integer primary keys per table."""
def __init__(self, start: dict[str, int]):
def __init__(self, start: dict[str, int]) -> None:
self._next = dict(start)
def take(self, table: str, count: int = 1) -> int:
@@ -706,7 +709,12 @@ def rand_past(rng: random.Random, now: datetime, max_days: int = 730) -> datetim
return now - timedelta(days=rng.randint(0, max_days), seconds=rng.randint(0, 86400))
def bulk_insert(conn, model, rows: list[dict[str, Any]], chunk: int = 1000) -> None:
def bulk_insert(
conn: Connection,
model: type[BaseModel],
rows: list[dict[str, Any]],
chunk: int = 1000,
) -> None:
"""Insert rows as multi-VALUES statements.
Not `executemany`: MariaDB Connector/Python's bulk path silently drops all
@@ -716,9 +724,8 @@ def bulk_insert(conn, model, rows: list[dict[str, Any]], chunk: int = 1000) -> N
"""
if not rows:
return
table = model.__table__
for i in range(0, len(rows), chunk):
conn.execute(table.insert().values(rows[i : i + chunk]))
conn.execute(insert(model).values(rows[i : i + chunk]))
def main() -> int:
@@ -825,7 +832,7 @@ def main() -> int:
# Pin every connection to UTC so the random historical timestamps we
# generate never land in a local DST gap that TIMESTAMP columns reject.
@event.listens_for(sync_engine, "connect")
def _session_utc(dbapi_conn, _record): # noqa: ANN001
def _session_utc(dbapi_conn: DBAPIConnection, _record: ConnectionPoolEntry) -> None:
cur = dbapi_conn.cursor()
try:
try:
@@ -1589,7 +1596,7 @@ def main() -> int:
return 0
def _wipe(conn) -> None:
def _wipe(conn: Connection) -> None:
"""Delete all rows from the tables this script populates (FK-safe order)."""
from sqlalchemy import text

View File

@@ -12,21 +12,22 @@ Run from the backend directory:
import sys
from xml.sax.handler import ContentHandler # nosec
from xml.sax.xmlreader import Locator # nosec
from defusedxml import ElementTree as ET
from defusedxml.sax import make_parser
class DiagnosticHandler(ContentHandler):
def __init__(self):
def __init__(self) -> None:
super().__init__()
self.line_number = 0
self.column_number = 0
def setDocumentLocator(self, locator):
def setDocumentLocator(self, locator: Locator) -> None:
self.locator = locator
def characters(self, content):
def characters(self, content: str) -> None:
# Check for invalid XML characters
for char in content:
if ord(char) >= 0xFFFE or (ord(char) <= 0x1F and char not in "\n\r\t"):
@@ -35,7 +36,7 @@ class DiagnosticHandler(ContentHandler):
)
def diagnose_xml(filename):
def diagnose_xml(filename: str) -> None:
print(f"Analyzing {filename}...")
# First, try to read the file in chunks to find encoding issues

View File

@@ -26,7 +26,7 @@ import io
import lzma
import os
import struct
from typing import BinaryIO
from typing import TYPE_CHECKING, BinaryIO
import zstandard
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
@@ -35,6 +35,10 @@ from logger.formatter import LIGHTMAGENTA
from logger.formatter import highlight as hl
from logger.logger import log
if TYPE_CHECKING:
# CPython's private OpenSSL hash type, which hashlib.md5() is typed as.
from _hashlib import HASH
# Container extensions RAHasher can't read but which we can hash natively. The
# real container is still detected by magic; the extension only gates whether
# we attempt native hashing before falling back to RAHasher.
@@ -681,7 +685,7 @@ def _be32(data: bytes, offset: int = 0) -> int:
return struct.unpack_from(">I", data, offset)[0]
def _hash_chunked(md5, reader: _RvzReader, offset: int, size: int) -> None:
def _hash_chunked(md5: HASH, reader: _RvzReader, offset: int, size: int) -> None:
"""Feed [offset, offset+size) to the hash in bounded chunks."""
pos = offset
remaining = size
@@ -693,7 +697,7 @@ def _hash_chunked(md5, reader: _RvzReader, offset: int, size: int) -> None:
def _hash_nintendo_disc_partition(
md5, reader: _RvzReader, part_offset: int, wii_shift: int
md5: HASH, reader: _RvzReader, part_offset: int, wii_shift: int
) -> None:
"""Mirror of rcheevos rc_hash_nintendo_disc_partition."""
body, trailer = struct.unpack(
@@ -752,7 +756,7 @@ def calculate_gamecube_ra_hash(file_path: str) -> str:
reader.close()
def _hash_wii_disc(md5, reader: _RvzReader) -> None:
def _hash_wii_disc(md5: HASH, reader: _RvzReader) -> None:
"""Mirror of rcheevos rc_hash_wii_disc for encrypted retail discs."""
if reader.read_at(0x61, 1) != b"\x00":
raise RvzHashError("decrypted Wii disc images are not supported")

View File

@@ -157,7 +157,7 @@ def discover_hltb_endpoint(base_url: str = HLTB_BASE_URL) -> str | None:
return None
def main():
def main() -> None:
"""Main function to discover and update the HLTB API URL."""
print("Starting HLTB API URL discovery...")

View File

@@ -143,7 +143,7 @@ def ensure_zipfile_writable() -> None:
pass
@functools.wraps(current)
def _get_compressor(compress_type, compresslevel=None):
def _get_compressor(compress_type: int, compresslevel: int | None = None) -> object:
return current(compress_type)
_get_compressor._romm_compresslevel_safe = True # type: ignore[attr-defined]

View File

@@ -254,6 +254,9 @@ export type { SearchCoverSchema } from './models/SearchCoverSchema';
export type { SearchRomSchema } from './models/SearchRomSchema';
export type { SessionStatusSchema } from './models/SessionStatusSchema';
export type { SessionTerminationSchema } from './models/SessionTerminationSchema';
export type { SetupExistingPlatform } from './models/SetupExistingPlatform';
export type { SetupLibraryResponse } from './models/SetupLibraryResponse';
export type { SetupPlatformsResponse } from './models/SetupPlatformsResponse';
export type { SiblingRomSchema } from './models/SiblingRomSchema';
export type { SimilarityReasonSchema } from './models/SimilarityReasonSchema';
export type { SimilarRomSchema } from './models/SimilarRomSchema';

View File

@@ -0,0 +1,9 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type SetupExistingPlatform = {
fs_slug: string;
rom_count: number;
};

View File

@@ -0,0 +1,13 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { PlatformSchema } from './PlatformSchema';
import type { SetupExistingPlatform } from './SetupExistingPlatform';
export type SetupLibraryResponse = {
library_ready: boolean;
library_structure: string;
existing_platforms: Array<SetupExistingPlatform>;
supported_platforms: Array<PlatformSchema>;
};

View File

@@ -0,0 +1,10 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type SetupPlatformsResponse = {
success: boolean;
created_count: number;
message: string;
};

View File

@@ -14,7 +14,7 @@ import sys
locales_dir = os.path.dirname(os.path.abspath(__file__))
def sort_recursive(value):
def sort_recursive(value: object) -> object:
"""Return a copy with every dict's keys sorted alphabetically."""
if isinstance(value, dict):
return {key: sort_recursive(value[key]) for key in sorted(value)}
@@ -23,12 +23,12 @@ def sort_recursive(value):
return value
def dump(data):
def dump(data: object) -> str:
# Match Prettier's formatting: 2-space indent, unicode preserved, trailing newline.
return json.dumps(data, indent=2, ensure_ascii=False) + "\n"
def main():
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--fix",

View File

@@ -1,31 +1,19 @@
import type {
SetupLibraryResponse,
SetupPlatformsResponse,
} from "@/__generated__";
import api from "@/services/api";
import type { Platform } from "@/stores/platforms";
export interface ExistingPlatform {
fs_slug: string;
rom_count: number;
}
export interface SetupLibraryInfo {
library_ready: boolean;
library_structure: string;
existing_platforms: ExistingPlatform[];
supported_platforms: Platform[];
}
export interface CreatePlatformsResponse {
success: boolean;
created_count: number;
message: string;
}
/** @deprecated Import `SetupLibraryResponse` from `@/__generated__`. */
export type SetupLibraryInfo = SetupLibraryResponse;
export default {
async getLibraryInfo() {
return await api.get<SetupLibraryInfo>("/setup/library");
return await api.get<SetupLibraryResponse>("/setup/library");
},
async createPlatforms(platformSlugs: string[]) {
return await api.post<CreatePlatformsResponse>(
return await api.post<SetupPlatformsResponse>(
"/setup/platforms",
platformSlugs,
);

View File

@@ -1,18 +1,18 @@
<script setup lang="ts">
// SetupStepPlatforms — Step 1 of the setup wizard.
// SetupStepPlatforms: Step 1 of the setup wizard.
//
// Layout:
// 1. Structure banner — what folder layout is in use or will be created.
// 2. Detected platforms — read-only, always rendered (folders that
// 1. Structure banner: what folder layout is in use or will be created.
// 2. Detected platforms: read-only, always rendered (folders that
// already exist on disk). Bundled with any unidentified folders so
// the user knows nothing of theirs got lost.
// 3. Supported platforms — every platform RomM knows about, grouped
// 3. Supported platforms: every platform RomM knows about, grouped
// by manufacturer. Groups are CLOSED by default and their bodies
// are gated with v-if (not v-show), so first-render is tiny —
// otherwise the catalogue's ~300 entries blow up DOM cost.
// 4. Search — when non-empty, replaces the grouped browse with a flat,
// are gated with v-if (not v-show), so first-render is tiny.
// Otherwise the catalogue's ~300 entries blow up DOM cost.
// 4. Search: when non-empty, replaces the grouped browse with a flat,
// capped result list across every supported platform.
// 5. Summary line — restates how many new folders the wizard will
// 5. Summary line: restates how many new folders the wizard will
// create under which pattern, so the directory creation effect
// is never a surprise.
import {
@@ -28,14 +28,14 @@ import {
import type { SliderBtnGroupItem } from "@v2/lib";
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import type { SetupLibraryInfo } from "@/services/api/setup";
import type { SetupLibraryResponse } from "@/__generated__";
import type { Platform } from "@/stores/platforms";
import PlatformIcon from "@/v2/components/shared/PlatformIcon.vue";
defineOptions({ inheritAttrs: false });
interface Props {
libraryInfo: SetupLibraryInfo;
libraryInfo: SetupLibraryResponse;
selectedNewPlatforms: string[];
}
@@ -59,7 +59,7 @@ const SEARCH_LIMIT = 80;
//
// "Detected" = on disk. We split into identified (matches a supported
// platform → we have a nice display name + icon) and unidentified
// (a folder that doesn't match — likely a typo or an unsupported
// (a folder that doesn't match, likely a typo or an unsupported
// platform). Both get shown in the same section so nothing slips
// through the cracks.
@@ -161,7 +161,7 @@ const filteredDetectedPlatforms = computed(() => {
// ── Supported (selectable) platforms ───────────────────────────────
//
// Filter out anything already on disk — those are shown in the detected
// Filter out anything already on disk, since those are shown in the detected
// section. We never present the same fs_slug twice.
const supportedAvailable = computed<Platform[]>(() =>
@@ -851,7 +851,7 @@ html[data-bp~="sm-and-down"] .r-setup-platforms__pane-scroll {
gap: var(--r-space-1);
}
/* Inside the manufacturer-group collapsible — rows go edge-to-edge,
/* Inside the manufacturer-group collapsible, rows go edge-to-edge,
no outer inset. Each row strips its card chrome (border, radius,
background) and switches to a top-border separator so the body of
the collapsible reads as a flat list rather than a stack of small

View File

@@ -1,6 +1,6 @@
^
<script setup lang="ts">
// Setup — three-step first-run wizard. Orchestrates library info loading,
// Setup: three-step first-run wizard. Orchestrates library info loading,
// platform selection, admin user creation, and metadata source review.
// The wizard owns all wizard-level state (current step, selection set,
// admin form, async flight); the per-step components are pure UI that
@@ -9,10 +9,10 @@ import { RBtn, RIcon, RImg, RSpinner, RSteps } from "@v2/lib";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import type { SetupLibraryResponse } from "@/__generated__";
import { refetchCSRFToken } from "@/services/api";
import identityApi from "@/services/api/identity";
import setupApi from "@/services/api/setup";
import type { SetupLibraryInfo } from "@/services/api/setup";
import userApi from "@/services/api/user";
import storeAuth from "@/stores/auth";
import storeHeartbeat from "@/stores/heartbeat";
@@ -32,26 +32,26 @@ const TOTAL_STEPS = 3;
const step = ref<1 | 2 | 3>(1);
// Direction of the last step change, used to pick the slide transition.
// "forward" — slide left out, slide in from the right.
// "back" — slide right out, slide in from the left.
// "forward": slide left out, slide in from the right.
// "back": slide right out, slide in from the left.
const stepDirection = ref<"forward" | "back">("forward");
// Step 1 — library + platforms
const EMPTY_LIBRARY_INFO: SetupLibraryInfo = {
// Step 1: library + platforms
const EMPTY_LIBRARY_INFO: SetupLibraryResponse = {
library_ready: false,
library_structure: "",
existing_platforms: [],
supported_platforms: [],
};
const libraryInfo = ref<SetupLibraryInfo>({ ...EMPTY_LIBRARY_INFO });
const libraryInfo = ref<SetupLibraryResponse>({ ...EMPTY_LIBRARY_INFO });
// Starts true so the first paint shows the spinner, not an empty flash.
const loadingLibrary = ref(true);
// Non-null when the library probe failed — the step 1 body swaps to an inline
// Non-null when the library probe failed, so the step 1 body swaps to an inline
// error with a retry instead of silently showing an empty platform list.
const libraryError = ref<string | null>(null);
const selectedNewPlatforms = ref<string[]>([]);
// Step 2 — admin user
// Step 2: admin user
const adminUser = ref<AdminUserDraft>({
username: "",
email: "",
@@ -60,7 +60,7 @@ const adminUser = ref<AdminUserDraft>({
});
const adminFormValid = ref(false);
// Step 3 — metadata (purely informational)
// Step 3: metadata (purely informational)
// Final submission
const submitting = ref(false);
@@ -146,7 +146,7 @@ async function finishWizard() {
// If the user picked an avatar, we need to be authenticated to PUT
// it on the just-created account. Log in with the chosen credentials
// then upload — failures here are non-fatal (the account still
// then upload. Failures here are non-fatal (the account still
// exists; user can set the avatar later from profile settings).
if (adminUser.value.avatar) {
try {
@@ -255,8 +255,8 @@ onMounted(loadLibraryInfo);
<SetupStepPlatforms
v-if="step === 1"
key="step-1"
:library-info="libraryInfo"
v-model:selected-new-platforms="selectedNewPlatforms"
:library-info="libraryInfo"
/>
<SetupStepAdmin
v-else-if="step === 2"
@@ -403,7 +403,7 @@ onMounted(loadLibraryInfo);
flex: 1 1 auto;
}
/* Step transitions — slide horizontally based on direction. The fade
/* Step transitions slide horizontally based on direction. The fade
keeps the overlap clean during the brief out-in handoff. */
.r-v2-setup-step-forward-enter-active,
.r-v2-setup-step-back-enter-active {
@@ -439,7 +439,7 @@ onMounted(loadLibraryInfo);
/* Small tablets (sm): the fixed-height card keeps header + footer pinned and
the BODY scrolls, instead of the desktop fixed-pane model where each list
scrolled in its own box. (xs overrides this below — the whole card flows
scrolled in its own box. (xs overrides this below: the whole card flows
and the auth stage scrolls.) */
html[data-bp~="sm-and-down"] .r-v2-setup__body {
/* Body clips; each step scrolls its own content region internally (the
@@ -448,7 +448,7 @@ html[data-bp~="sm-and-down"] .r-v2-setup__body {
}
/* Phones: the card fills the auth stage via a definite flex cross-size
(align-self: stretch — NOT height:100%, whose percentage collapses on a
(align-self: stretch, NOT height:100%, whose percentage collapses on a
reactive re-layout). Header + footer stay pinned; the step's lists region
scrolls internally, like desktop. */
html[data-bp~="xs"] .r-v2-setup {

View File

@@ -1,5 +1,5 @@
<script setup lang="ts">
// Home dashboard — composed of primitives + feature components. Each
// Home dashboard, composed of primitives + feature components. Each
// section is a CardRow with its own tile type in the default slot.
//
// Gamepad / keyboard arrow navigation: the root is registered with
@@ -12,7 +12,10 @@ import { useEventListener, useIntervalFn } from "@vueuse/core";
import { storeToRefs } from "pinia";
import { computed, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type { RecommendedRomSchema } from "@/__generated__";
import type {
RecommendedRomSchema,
SetupLibraryResponse,
} from "@/__generated__";
import { useUISettings } from "@/composables/useUISettings";
import { ROUTES } from "@/plugins/router";
import romApi, {
@@ -20,7 +23,7 @@ import romApi, {
RECENT_ROMS_LIMIT,
RECOMMENDED_ROMS_LIMIT,
} from "@/services/api/rom";
import setupApi, { type SetupLibraryInfo } from "@/services/api/setup";
import setupApi from "@/services/api/setup";
import storeCollections from "@/stores/collections";
import storePlatforms from "@/stores/platforms";
import storeRoms, { type SimpleRom } from "@/stores/roms";
@@ -216,12 +219,12 @@ const phase = useLoadingPhase(
() => !hasContent.value,
);
// Filesystem snapshot for the empty state — shows the user what RomM
// Filesystem snapshot for the empty state. Shows the user what RomM
// can already see on disk so the "run a scan" CTA isn't a leap of
// faith. Fetched lazily the first time the empty state appears; the
// endpoint requires PLATFORMS_READ scope so we fail silently for
// users without it (the chips just stay hidden).
const libraryInfo = ref<SetupLibraryInfo | null>(null);
const libraryInfo = ref<SetupLibraryResponse | null>(null);
const fetchingLibraryInfo = ref(false);
const detectedPlatformCount = computed(
@@ -252,7 +255,7 @@ watch(phase, (value) => {
if (value === "empty") void loadLibraryInfo();
});
// Favorite ROMs — derived from the Favorites collection's rom_ids.
// Favorite ROMs, derived from the Favorites collection's rom_ids.
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- false positive: used in <template>; @typescript-eslint+projectService doesn't see Vue templates
const favoriteRoms = computed<SimpleRom[]>(() => {
const favIds = favoriteCollection.value?.rom_ids ?? [];
@@ -279,7 +282,7 @@ function collectionCovers(c: {
<template>
<div ref="gridRoot" class="r-v2-home">
<!-- Empty library state — shown when nothing has been ingested
<!-- Empty library state, shown when nothing has been ingested
yet. Hides every section underneath so the user lands on a
decision (upload vs scan), not on a row of skeletons. -->
<section v-if="phase === 'empty'" class="r-v2-home-empty r-v2-asset-fade">
@@ -294,7 +297,7 @@ function collectionCovers(c: {
</h2>
<p class="r-v2-home-empty__hint">{{ t("home.empty-hint") }}</p>
<!-- Filesystem snapshot — only rendered once /setup/library
<!-- Filesystem snapshot, only rendered once /setup/library
has resolved. Mirrors the chip pair from setup wizard
step 1 so the user sees the same "RomM detected this on
disk" telemetry from both entry points. -->
@@ -372,7 +375,7 @@ function collectionCovers(c: {
</section>
<template v-else-if="phase !== 'idle'">
<!-- Widget bar — random pick, library snapshot, future RA widgets.
<!-- Widget bar: random pick, library snapshot, future RA widgets.
Hidden when the master toggle is off; the bar itself also
drops out when every individual widget is disabled. -->
<WidgetBar v-if="showHomeWidgets" />
@@ -670,7 +673,7 @@ function collectionCovers(c: {
Two-step layout: hero (icon + headline + hint) on top, then a
two-pane "how do you want to add games" panel split by a vertical
divider. Each pane is a router-link so the whole panel is the hit
target — no nested buttons. */
target (no nested buttons). */
.r-v2-home-empty {
display: flex;
flex-direction: column;
@@ -747,7 +750,7 @@ html[data-bp~="sm-and-down"] .r-v2-home-empty__divider {
}
/* Each choice is a router-link rendered as a card. The "feel" is
close to a primary CTA — brand-tinted halo on hover, the trailing
close to a primary CTA: brand-tinted halo on hover, the trailing
chevron in the CTA line nudges right so the click target reads
actionable without needing a separate <RBtn>. */
.r-v2-home-empty__choice {