From 3750d6ff703d93ed0be24fe4c2a86fff968b95c4 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Sat, 26 Sep 2026 15:31:00 -0400 Subject: [PATCH] chore(mypy): require full annotations outside tests, type the setup responses (#4795) --- .claude/skills/backend-development/SKILL.md | 2 +- .trunk/configs/mypy.ini | 5 ++++ backend/config/config_manager.py | 22 ++++++++------ backend/decorators/auth.py | 8 +++-- backend/endpoints/auth.py | 9 +++--- backend/endpoints/firmware.py | 4 +-- backend/endpoints/heartbeat.py | 26 ++++++++-------- backend/endpoints/responses/heartbeat.py | 22 ++++++++++++++ backend/endpoints/roms/__init__.py | 6 ++-- backend/endpoints/roms/files.py | 2 +- backend/endpoints/roms/manual.py | 24 +++++++-------- backend/endpoints/roms/patch.py | 2 +- backend/endpoints/sockets/netplay.py | 29 ++++++++++-------- backend/endpoints/sockets/scan.py | 21 ++++++++----- backend/exceptions/config_exceptions.py | 2 +- backend/exceptions/endpoint_exceptions.py | 20 ++++++------- backend/exceptions/fs_exceptions.py | 22 +++++++------- backend/exceptions/task_exceptions.py | 4 +-- backend/handler/auth/base_handler.py | 25 +++++++++++----- backend/handler/auth/dependencies.py | 5 +++- .../auth/middleware/session_middleware.py | 3 +- backend/handler/auth/permissions.py | 26 +++++++--------- .../handler/database/audit_events_handler.py | 3 +- backend/handler/database/base_handler.py | 20 ++++++++++--- .../handler/database/collections_handler.py | 2 +- backend/handler/database/firmware_handler.py | 2 +- .../handler/database/notifications_handler.py | 3 +- backend/handler/database/roms_handler.py | 22 +++++++------- .../handler/database/screenshots_handler.py | 2 +- backend/handler/database/users_handler.py | 5 ++-- backend/handler/filesystem/assets_handler.py | 16 +++++----- backend/handler/filesystem/base_handler.py | 13 ++++---- .../handler/filesystem/firmware_handler.py | 6 ++-- .../handler/filesystem/platforms_handler.py | 2 +- .../handler/filesystem/resources_handler.py | 8 ++--- backend/handler/filesystem/roms_handler.py | 2 +- backend/handler/metadata/gamelist_handler.py | 8 ++--- backend/handler/metadata/igdb_handler.py | 2 +- backend/handler/metadata/playmatch_handler.py | 2 +- backend/handler/metadata/ra_handler.py | 9 +++--- backend/handler/netplay_handler.py | 6 ++-- backend/handler/scan_handler.py | 17 ++++++++--- backend/logger/formatter.py | 2 +- backend/models/collection.py | 2 +- backend/models/user.py | 4 +-- backend/sync_watcher.py | 8 +++-- .../tasks/manual/cleanup_missing_firmware.py | 4 +-- backend/tasks/manual/cleanup_missing_roms.py | 4 +-- backend/tasks/scheduled/__init__.py | 2 +- .../tasks/scheduled/build_recommendations.py | 2 +- backend/tasks/scheduled/cleanup_audit_log.py | 2 +- backend/tasks/scheduled/cleanup_netplay.py | 2 +- .../scheduled/cleanup_orphaned_resources.py | 4 +-- .../tasks/scheduled/cleanup_sync_sessions.py | 2 +- backend/tasks/scheduled/cleanup_upload_tmp.py | 2 +- backend/tasks/scheduled/cleanup_zip_cache.py | 2 +- .../tasks/scheduled/convert_images_to_webp.py | 6 ++-- .../scheduled/reap_streaming_sessions.py | 2 +- backend/tasks/scheduled/scan_library.py | 2 +- .../sync_retroachievements_progress.py | 2 +- .../scheduled/update_launchbox_metadata.py | 4 +-- .../tasks/scheduled/update_switch_titledb.py | 2 +- backend/tasks/sync_push_pull_task.py | 11 +++---- backend/tests/endpoints/roms/test_manual.py | 25 ++++++++++++++++ backend/tests/handler/auth/test_oidc.py | 1 + backend/tests/handler/metadata/conftest.py | 20 +++++++++++++ .../handler/metadata/test_launchbox_utils.py | 21 +------------ .../tests/handler/metadata/test_ra_handler.py | 14 +++++++++ backend/tools/generate_test_data.py | 21 ++++++++----- backend/tools/xml_diagnostics.py | 9 +++--- backend/utils/rvz_hasher.py | 12 +++++--- backend/utils/update_hltb_api_url.py | 2 +- backend/utils/zip_cache.py | 2 +- frontend/src/__generated__/index.ts | 3 ++ .../models/SetupExistingPlatform.ts | 9 ++++++ .../models/SetupLibraryResponse.ts | 13 ++++++++ .../models/SetupPlatformsResponse.ts | 10 +++++++ frontend/src/locales/check_i18n_sorted.py | 6 ++-- frontend/src/services/api/setup.ts | 28 +++++------------ .../v2/components/Auth/SetupStepPlatforms.vue | 26 ++++++++-------- frontend/src/v2/views/Auth/Setup.vue | 30 +++++++++---------- frontend/src/v2/views/Home.vue | 25 +++++++++------- 82 files changed, 476 insertions(+), 311 deletions(-) create mode 100644 frontend/src/__generated__/models/SetupExistingPlatform.ts create mode 100644 frontend/src/__generated__/models/SetupLibraryResponse.ts create mode 100644 frontend/src/__generated__/models/SetupPlatformsResponse.ts diff --git a/.claude/skills/backend-development/SKILL.md b/.claude/skills/backend-development/SKILL.md index 197148269..d68886bee 100644 --- a/.claude/skills/backend-development/SKILL.md +++ b/.claude/skills/backend-development/SKILL.md @@ -103,5 +103,5 @@ uv run pytest # 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//` layout under `backend/tests/`. First-time test DB setup: `docker exec -i romm-db-dev mariadb -uroot -p < 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. diff --git a/.trunk/configs/mypy.ini b/.trunk/configs/mypy.ini index 8974bf1d3..028c83cd8 100644 --- a/.trunk/configs/mypy.ini +++ b/.trunk/configs/mypy.ini @@ -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 diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index b32ff1b4f..fe0f34175 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -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: diff --git a/backend/decorators/auth.py b/backend/decorators/auth.py index bba980e66..fe6be0f69 100644 --- a/backend/decorators/auth.py +++ b/backend/decorators/auth.py @@ -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): diff --git a/backend/endpoints/auth.py b/backend/endpoints/auth.py index dce3ced8a..9f00cfe51 100644 --- a/backend/endpoints/auth.py +++ b/backend/endpoints/auth.py @@ -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: diff --git a/backend/endpoints/firmware.py b/backend/endpoints/firmware.py index c1296eefe..b28e60f86 100644 --- a/backend/endpoints/firmware.py +++ b/backend/endpoints/firmware.py @@ -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: diff --git a/backend/endpoints/heartbeat.py b/backend/endpoints/heartbeat.py index 663d1db39..6e23a2573 100644 --- a/backend/endpoints/heartbeat.py +++ b/backend/endpoints/heartbeat.py @@ -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 diff --git a/backend/endpoints/responses/heartbeat.py b/backend/endpoints/responses/heartbeat.py index 24684f3e7..8486f5c1c 100644 --- a/backend/endpoints/responses/heartbeat.py +++ b/backend/endpoints/responses/heartbeat.py @@ -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 diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index f52431de2..2e02e8df7 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -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: diff --git a/backend/endpoints/roms/files.py b/backend/endpoints/roms/files.py index 7be1c4f71..4e9dc7509 100644 --- a/backend/endpoints/roms/files.py +++ b/backend/endpoints/roms/files.py @@ -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 = ( diff --git a/backend/endpoints/roms/manual.py b/backend/endpoints/roms/manual.py index 9f487eca5..c6a417bfd 100644 --- a/backend/endpoints/roms/manual.py +++ b/backend/endpoints/roms/manual.py @@ -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( diff --git a/backend/endpoints/roms/patch.py b/backend/endpoints/roms/patch.py index a7157a07b..6c088fd8c 100644 --- a/backend/endpoints/roms/patch.py +++ b/backend/endpoints/roms/patch.py @@ -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 diff --git a/backend/endpoints/sockets/netplay.py b/backend/endpoints/sockets/netplay.py index 26ad383f8..06cbb0ea1 100644 --- a/backend/endpoints/sockets/netplay.py +++ b/backend/endpoints/sockets/netplay.py @@ -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) diff --git a/backend/endpoints/sockets/scan.py b/backend/endpoints/sockets/scan.py index b8a7afcfd..ea02be47d 100644 --- a/backend/endpoints/sockets/scan.py +++ b/backend/endpoints/sockets/scan.py @@ -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) diff --git a/backend/exceptions/config_exceptions.py b/backend/exceptions/config_exceptions.py index 33b6b6f76..7317718a6 100644 --- a/backend/exceptions/config_exceptions.py +++ b/backend/exceptions/config_exceptions.py @@ -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) diff --git a/backend/exceptions/endpoint_exceptions.py b/backend/exceptions/endpoint_exceptions.py index fa7125a90..eb115bcc2 100644 --- a/backend/exceptions/endpoint_exceptions.py +++ b/backend/exceptions/endpoint_exceptions.py @@ -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) diff --git a/backend/exceptions/fs_exceptions.py b/backend/exceptions/fs_exceptions.py index 47a9ad95e..a23935bdc 100644 --- a/backend/exceptions/fs_exceptions.py +++ b/backend/exceptions/fs_exceptions.py @@ -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 diff --git a/backend/exceptions/task_exceptions.py b/backend/exceptions/task_exceptions.py index 85b9b7f41..a12951073 100644 --- a/backend/exceptions/task_exceptions.py +++ b/backend/exceptions/task_exceptions.py @@ -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 diff --git a/backend/handler/auth/base_handler.py b/backend/handler/auth/base_handler.py index 7d9aa4772..ca7b35695 100644 --- a/backend/handler/auth/base_handler.py +++ b/backend/handler/auth/base_handler.py @@ -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 diff --git a/backend/handler/auth/dependencies.py b/backend/handler/auth/dependencies.py index 6eaa55801..25ef2eddb 100644 --- a/backend/handler/auth/dependencies.py +++ b/backend/handler/auth/dependencies.py @@ -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. diff --git a/backend/handler/auth/middleware/session_middleware.py b/backend/handler/auth/middleware/session_middleware.py index 032c104d7..f789139b5 100644 --- a/backend/handler/auth/middleware/session_middleware.py +++ b/backend/handler/auth/middleware/session_middleware.py @@ -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 {} diff --git a/backend/handler/auth/permissions.py b/backend/handler/auth/permissions.py index cbe9e2d63..7003afb00 100644 --- a/backend/handler/auth/permissions.py +++ b/backend/handler/auth/permissions.py @@ -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( diff --git a/backend/handler/database/audit_events_handler.py b/backend/handler/database/audit_events_handler.py index 9cc4de070..e305799b7 100644 --- a/backend/handler/database/audit_events_handler.py +++ b/backend/handler/database/audit_events_handler.py @@ -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 diff --git a/backend/handler/database/base_handler.py b/backend/handler/database/base_handler.py index ba1b19466..11bd37861 100644 --- a/backend/handler/database/base_handler.py +++ b/backend/handler/database/base_handler.py @@ -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--------") diff --git a/backend/handler/database/collections_handler.py b/backend/handler/database/collections_handler.py index e67b1ce38..c902658a0 100644 --- a/backend/handler/database/collections_handler.py +++ b/backend/handler/database/collections_handler.py @@ -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 diff --git a/backend/handler/database/firmware_handler.py b/backend/handler/database/firmware_handler.py index 3999886d0..01a1fa10e 100644 --- a/backend/handler/database/firmware_handler.py +++ b/backend/handler/database/firmware_handler.py @@ -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) diff --git a/backend/handler/database/notifications_handler.py b/backend/handler/database/notifications_handler.py index 64af6d091..0fabd4bf9 100644 --- a/backend/handler/database/notifications_handler.py +++ b/backend/handler/database/notifications_handler.py @@ -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( diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index b832caf66..bf26a74f2 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -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) diff --git a/backend/handler/database/screenshots_handler.py b/backend/handler/database/screenshots_handler.py index 799ddc444..ee104f502 100644 --- a/backend/handler/database/screenshots_handler.py +++ b/backend/handler/database/screenshots_handler.py @@ -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) diff --git a/backend/handler/database/users_handler.py b/backend/handler/database/users_handler.py index 015970a1e..b80d3fdbc 100644 --- a/backend/handler/database/users_handler.py +++ b/backend/handler/database/users_handler.py @@ -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) diff --git a/backend/handler/filesystem/assets_handler.py b/backend/handler/filesystem/assets_handler.py index 507637f5d..a2e74b773 100644 --- a/backend/handler/filesystem/assets_handler.py +++ b/backend/handler/filesystem/assets_handler.py @@ -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. diff --git a/backend/handler/filesystem/base_handler.py b/backend/handler/filesystem/base_handler.py index 47c6cec8c..c3eaa43c7 100644 --- a/backend/handler/filesystem/base_handler.py +++ b/backend/handler/filesystem/base_handler.py @@ -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. diff --git a/backend/handler/filesystem/firmware_handler.py b/backend/handler/filesystem/firmware_handler.py index b1970c943..dc74a2085 100644 --- a/backend/handler/filesystem/firmware_handler.py +++ b/backend/handler/filesystem/firmware_handler.py @@ -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)] diff --git a/backend/handler/filesystem/platforms_handler.py b/backend/handler/filesystem/platforms_handler.py index a138a32a5..d3cfc0a67 100644 --- a/backend/handler/filesystem/platforms_handler.py +++ b/backend/handler/filesystem/platforms_handler.py @@ -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 diff --git a/backend/handler/filesystem/resources_handler.py b/backend/handler/filesystem/resources_handler.py index 134a8e07a..20ec0a359 100644 --- a/backend/handler/filesystem/resources_handler.py +++ b/backend/handler/filesystem/resources_handler.py @@ -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 diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 061923e5e..e56181dc5 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -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) diff --git a/backend/handler/metadata/gamelist_handler.py b/backend/handler/metadata/gamelist_handler.py index 5b85f5cc8..c23d6c897 100644 --- a/backend/handler/metadata/gamelist_handler.py +++ b/backend/handler/metadata/gamelist_handler.py @@ -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() diff --git a/backend/handler/metadata/igdb_handler.py b/backend/handler/metadata/igdb_handler.py index 91155bdf7..511831d22 100644 --- a/backend/handler/metadata/igdb_handler.py +++ b/backend/handler/metadata/igdb_handler.py @@ -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, diff --git a/backend/handler/metadata/playmatch_handler.py b/backend/handler/metadata/playmatch_handler.py index 94820d6b5..2a2029c42 100644 --- a/backend/handler/metadata/playmatch_handler.py +++ b/backend/handler/metadata/playmatch_handler.py @@ -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" diff --git a/backend/handler/metadata/ra_handler.py b/backend/handler/metadata/ra_handler.py index 6fd43f20c..6729e3862 100644 --- a/backend/handler/metadata/ra_handler.py +++ b/backend/handler/metadata/ra_handler.py @@ -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 diff --git a/backend/handler/netplay_handler.py b/backend/handler/netplay_handler.py index 2db36d5a5..9d901c831 100644 --- a/backend/handler/netplay_handler.py +++ b/backend/handler/netplay_handler.py @@ -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) diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index d0e7b83a0..365906fba 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -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, diff --git a/backend/logger/formatter.py b/backend/logger/formatter.py index 074b55e26..44b2154e8 100644 --- a/backend/logger/formatter.py +++ b/backend/logger/formatter.py @@ -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. diff --git a/backend/models/collection.py b/backend/models/collection.py index 92698df21..be4033bb0 100644 --- a/backend/models/collection.py +++ b/backend/models/collection.py @@ -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"] diff --git a/backend/models/user.py b/backend/models/user.py index c48f91619..386089499 100644 --- a/backend/models/user.py +++ b/backend/models/user.py @@ -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( diff --git a/backend/sync_watcher.py b/backend/sync_watcher.py index b85657ef9..fd37c2136 100644 --- a/backend/sync_watcher.py +++ b/backend/sync_watcher.py @@ -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 diff --git a/backend/tasks/manual/cleanup_missing_firmware.py b/backend/tasks/manual/cleanup_missing_firmware.py index 7d3aaa677..3961592f3 100644 --- a/backend/tasks/manual/cleanup_missing_firmware.py +++ b/backend/tasks/manual/cleanup_missing_firmware.py @@ -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", diff --git a/backend/tasks/manual/cleanup_missing_roms.py b/backend/tasks/manual/cleanup_missing_roms.py index 7dabc7b29..ead9f6b75 100644 --- a/backend/tasks/manual/cleanup_missing_roms.py +++ b/backend/tasks/manual/cleanup_missing_roms.py @@ -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", diff --git a/backend/tasks/scheduled/__init__.py b/backend/tasks/scheduled/__init__.py index db0179a2f..d0f578d09 100644 --- a/backend/tasks/scheduled/__init__.py +++ b/backend/tasks/scheduled/__init__.py @@ -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) diff --git a/backend/tasks/scheduled/build_recommendations.py b/backend/tasks/scheduled/build_recommendations.py index eabdd1d6c..a8dac7efd 100644 --- a/backend/tasks/scheduled/build_recommendations.py +++ b/backend/tasks/scheduled/build_recommendations.py @@ -17,7 +17,7 @@ from . import UpdateStats class BuildRecommendationsTask(PeriodicTask): - def __init__(self): + def __init__(self) -> None: super().__init__( title="Build recommendations index", description=( diff --git a/backend/tasks/scheduled/cleanup_audit_log.py b/backend/tasks/scheduled/cleanup_audit_log.py index 58be30fab..e3a3c76d1 100644 --- a/backend/tasks/scheduled/cleanup_audit_log.py +++ b/backend/tasks/scheduled/cleanup_audit_log.py @@ -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", diff --git a/backend/tasks/scheduled/cleanup_netplay.py b/backend/tasks/scheduled/cleanup_netplay.py index cb1282e4e..46457ef3d 100644 --- a/backend/tasks/scheduled/cleanup_netplay.py +++ b/backend/tasks/scheduled/cleanup_netplay.py @@ -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", diff --git a/backend/tasks/scheduled/cleanup_orphaned_resources.py b/backend/tasks/scheduled/cleanup_orphaned_resources.py index 01eea16a0..fdd5ff324 100644 --- a/backend/tasks/scheduled/cleanup_orphaned_resources.py +++ b/backend/tasks/scheduled/cleanup_orphaned_resources.py @@ -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", diff --git a/backend/tasks/scheduled/cleanup_sync_sessions.py b/backend/tasks/scheduled/cleanup_sync_sessions.py index 7b3a5741a..219629537 100644 --- a/backend/tasks/scheduled/cleanup_sync_sessions.py +++ b/backend/tasks/scheduled/cleanup_sync_sessions.py @@ -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", diff --git a/backend/tasks/scheduled/cleanup_upload_tmp.py b/backend/tasks/scheduled/cleanup_upload_tmp.py index b6e5d8c1f..b1e9913ab 100644 --- a/backend/tasks/scheduled/cleanup_upload_tmp.py +++ b/backend/tasks/scheduled/cleanup_upload_tmp.py @@ -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", diff --git a/backend/tasks/scheduled/cleanup_zip_cache.py b/backend/tasks/scheduled/cleanup_zip_cache.py index 9636392b0..0dbdedb58 100644 --- a/backend/tasks/scheduled/cleanup_zip_cache.py +++ b/backend/tasks/scheduled/cleanup_zip_cache.py @@ -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", diff --git a/backend/tasks/scheduled/convert_images_to_webp.py b/backend/tasks/scheduled/convert_images_to_webp.py index e63091602..d934b9250 100644 --- a/backend/tasks/scheduled/convert_images_to_webp.py +++ b/backend/tasks/scheduled/convert_images_to_webp.py @@ -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", diff --git a/backend/tasks/scheduled/reap_streaming_sessions.py b/backend/tasks/scheduled/reap_streaming_sessions.py index 4a2ed211d..f4d04d434 100644 --- a/backend/tasks/scheduled/reap_streaming_sessions.py +++ b/backend/tasks/scheduled/reap_streaming_sessions.py @@ -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", diff --git a/backend/tasks/scheduled/scan_library.py b/backend/tasks/scheduled/scan_library.py index 8d163e82e..a83b8ba44 100644 --- a/backend/tasks/scheduled/scan_library.py +++ b/backend/tasks/scheduled/scan_library.py @@ -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", diff --git a/backend/tasks/scheduled/sync_retroachievements_progress.py b/backend/tasks/scheduled/sync_retroachievements_progress.py index cc073799b..4a1ca05d1 100644 --- a/backend/tasks/scheduled/sync_retroachievements_progress.py +++ b/backend/tasks/scheduled/sync_retroachievements_progress.py @@ -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, diff --git a/backend/tasks/scheduled/update_launchbox_metadata.py b/backend/tasks/scheduled/update_launchbox_metadata.py index 5ce17eec2..032f1ec63 100644 --- a/backend/tasks/scheduled/update_launchbox_metadata.py +++ b/backend/tasks/scheduled/update_launchbox_metadata.py @@ -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", diff --git a/backend/tasks/scheduled/update_switch_titledb.py b/backend/tasks/scheduled/update_switch_titledb.py index 5cda0c5f2..518373945 100644 --- a/backend/tasks/scheduled/update_switch_titledb.py +++ b/backend/tasks/scheduled/update_switch_titledb.py @@ -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", diff --git a/backend/tasks/sync_push_pull_task.py b/backend/tasks/sync_push_pull_task.py index f31a235d2..4efba0b4d 100644 --- a/backend/tasks/sync_push_pull_task.py +++ b/backend/tasks/sync_push_pull_task.py @@ -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.""" diff --git a/backend/tests/endpoints/roms/test_manual.py b/backend/tests/endpoints/roms/test_manual.py index 5932f2bc0..8432f00ca 100644 --- a/backend/tests/endpoints/roms/test_manual.py +++ b/backend/tests/endpoints/roms/test_manual.py @@ -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, diff --git a/backend/tests/handler/auth/test_oidc.py b/backend/tests/handler/auth/test_oidc.py index 146517e2a..4403adc15 100644 --- a/backend/tests/handler/auth/test_oidc.py +++ b/backend/tests/handler/auth/test_oidc.py @@ -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 diff --git a/backend/tests/handler/metadata/conftest.py b/backend/tests/handler/metadata/conftest.py index e1496aad8..adfa420c1 100644 --- a/backend/tests/handler/metadata/conftest.py +++ b/backend/tests/handler/metadata/conftest.py @@ -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() diff --git a/backend/tests/handler/metadata/test_launchbox_utils.py b/backend/tests/handler/metadata/test_launchbox_utils.py index 841c55888..a464413a0 100644 --- a/backend/tests/handler/metadata/test_launchbox_utils.py +++ b/backend/tests/handler/metadata/test_launchbox_utils.py @@ -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): diff --git a/backend/tests/handler/metadata/test_ra_handler.py b/backend/tests/handler/metadata/test_ra_handler.py index bb1f695b9..6d23c81f0 100644 --- a/backend/tests/handler/metadata/test_ra_handler.py +++ b/backend/tests/handler/metadata/test_ra_handler.py @@ -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.""" diff --git a/backend/tools/generate_test_data.py b/backend/tools/generate_test_data.py index 7305266cb..33515d18c 100644 --- a/backend/tools/generate_test_data.py +++ b/backend/tools/generate_test_data.py @@ -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 diff --git a/backend/tools/xml_diagnostics.py b/backend/tools/xml_diagnostics.py index 28e4b272a..64427ffc3 100644 --- a/backend/tools/xml_diagnostics.py +++ b/backend/tools/xml_diagnostics.py @@ -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 diff --git a/backend/utils/rvz_hasher.py b/backend/utils/rvz_hasher.py index 593920edf..b9cda1e60 100644 --- a/backend/utils/rvz_hasher.py +++ b/backend/utils/rvz_hasher.py @@ -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") diff --git a/backend/utils/update_hltb_api_url.py b/backend/utils/update_hltb_api_url.py index 17892ba08..5cb80b95e 100644 --- a/backend/utils/update_hltb_api_url.py +++ b/backend/utils/update_hltb_api_url.py @@ -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...") diff --git a/backend/utils/zip_cache.py b/backend/utils/zip_cache.py index 5ac31f2db..a44e0d1be 100644 --- a/backend/utils/zip_cache.py +++ b/backend/utils/zip_cache.py @@ -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] diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 08c80a3c5..312d52d38 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -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'; diff --git a/frontend/src/__generated__/models/SetupExistingPlatform.ts b/frontend/src/__generated__/models/SetupExistingPlatform.ts new file mode 100644 index 000000000..20cdc3cc5 --- /dev/null +++ b/frontend/src/__generated__/models/SetupExistingPlatform.ts @@ -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; +}; + diff --git a/frontend/src/__generated__/models/SetupLibraryResponse.ts b/frontend/src/__generated__/models/SetupLibraryResponse.ts new file mode 100644 index 000000000..198b18100 --- /dev/null +++ b/frontend/src/__generated__/models/SetupLibraryResponse.ts @@ -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; + supported_platforms: Array; +}; + diff --git a/frontend/src/__generated__/models/SetupPlatformsResponse.ts b/frontend/src/__generated__/models/SetupPlatformsResponse.ts new file mode 100644 index 000000000..ff5d58373 --- /dev/null +++ b/frontend/src/__generated__/models/SetupPlatformsResponse.ts @@ -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; +}; + diff --git a/frontend/src/locales/check_i18n_sorted.py b/frontend/src/locales/check_i18n_sorted.py index 3b8514630..1d2932da6 100644 --- a/frontend/src/locales/check_i18n_sorted.py +++ b/frontend/src/locales/check_i18n_sorted.py @@ -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", diff --git a/frontend/src/services/api/setup.ts b/frontend/src/services/api/setup.ts index d41a235b1..bdbf719ef 100644 --- a/frontend/src/services/api/setup.ts +++ b/frontend/src/services/api/setup.ts @@ -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("/setup/library"); + return await api.get("/setup/library"); }, async createPlatforms(platformSlugs: string[]) { - return await api.post( + return await api.post( "/setup/platforms", platformSlugs, ); diff --git a/frontend/src/v2/components/Auth/SetupStepPlatforms.vue b/frontend/src/v2/components/Auth/SetupStepPlatforms.vue index ced3c6a8a..2bdd3249b 100644 --- a/frontend/src/v2/components/Auth/SetupStepPlatforms.vue +++ b/frontend/src/v2/components/Auth/SetupStepPlatforms.vue @@ -1,18 +1,18 @@