feat(steam): import a user's Steam library

Users can link a Steam account (SteamID64, profile link or custom URL name)
and sync the games it owns. The sync links each owned game to the rom that
already stands for it on win, linux or mac, matched by Steam app id, and
gives the rest a store-only rom on win (created with its folder when the
library has none). Store-only roms have no file: `roms.storefront` marks
them and, like physical games, keeps them out of the missing-file sync,
the missing cleanup, the feeds and the exporters. Store-only roms that no
source has matched yet are queued for a rom-id scan after each sync.

- STEAM_API_KEY enables it; the heartbeat reports STEAM_LIBRARY_ENABLED.
- PUT/DELETE /api/users/{id}/steam link and unlink an account,
  POST /api/users/{id}/steam/sync queues the sync for one user.
- sync_steam_libraries syncs every linked user on a schedule
  (ENABLE_SCHEDULED_STEAM_LIBRARY_SYNC, SCHEDULED_STEAM_LIBRARY_SYNC_CRON).
- steam_library_entries holds each user's owned games with playtime and
  last played time; migration 0155 adds it, the user columns and
  roms.storefront.
- A rom-id scan no longer marks a physical or store-only rom missing.
- New store_only rom filter, part of HAS_FILE_ON_DISK_FILTERS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XGA3D2oZ1hq3QUdnubMNXh
This commit is contained in:
Sam Dornan
2026-10-26 20:03:49 +00:00
committed by Claude
parent 552ac3a393
commit 9ee2e95bc9
44 changed files with 1756 additions and 24 deletions

View File

@@ -71,3 +71,48 @@ class SteamAppDetails(TypedDict):
class SteamAppDetailsEnvelope(TypedDict):
success: bool
data: NotRequired[SteamAppDetails]
class SteamVanityResult(TypedDict):
# 1 when the name resolved, 42 when no profile uses it.
success: int
steamid: NotRequired[str]
message: NotRequired[str]
class SteamVanityResponse(TypedDict):
response: SteamVanityResult
class SteamPlayerSummary(TypedDict):
steamid: str
personaname: str
profileurl: str
avatarfull: NotRequired[str]
# 3 is public; anything else hides the owned-games list.
communityvisibilitystate: int
class SteamPlayerSummariesResult(TypedDict):
players: list[SteamPlayerSummary]
class SteamPlayerSummariesResponse(TypedDict):
response: SteamPlayerSummariesResult
class SteamOwnedGame(TypedDict):
appid: int
name: NotRequired[str]
playtime_forever: int
rtime_last_played: NotRequired[int]
class SteamOwnedGamesResult(TypedDict):
# Both are missing when the profile's game details are private.
game_count: NotRequired[int]
games: NotRequired[list[SteamOwnedGame]]
class SteamOwnedGamesResponse(TypedDict):
response: SteamOwnedGamesResult

View File

@@ -0,0 +1,102 @@
from typing import Final
import aiohttp
import yarl
from aiohttp.client import ClientTimeout
from adapters.services.provider_http import send_with_retries
from adapters.services.response_validation import parse_response
from adapters.services.steam_types import (
SteamOwnedGame,
SteamOwnedGamesResponse,
SteamPlayerSummariesResponse,
SteamPlayerSummary,
SteamVanityResponse,
)
from logger.logger import log
from utils import get_version
from utils.context import ctx_aiohttp_session
STEAM_WEB_API_URL: Final[str] = "https://api.steampowered.com"
STEAM_VANITY_RESOLVED: Final[int] = 1
STEAM_PROFILE_PUBLIC: Final[int] = 3
class SteamWebAPIError(Exception):
"""The Steam Web API refused a request or could not be reached."""
class SteamWebAPIService:
"""Client for the keyed Steam Web API, which reads a player's account."""
def __init__(self, api_key: str, base_url: str | None = None) -> None:
self.api_key = api_key
self.url = yarl.URL(base_url or STEAM_WEB_API_URL)
async def _request[T](
self, path: str, tp: type[T], params: dict[str, str], request_timeout: int = 60
) -> T:
aiohttp_session = ctx_aiohttp_session.get()
url = self.url.joinpath(path).with_query({**params, "key": self.api_key})
async def send() -> T | None:
# The query carries the API key, so only the path is logged.
log.debug("Steam Web API request: %s", path)
res = await aiohttp_session.get(
url,
headers={"user-agent": f"RomM/{get_version()}"},
timeout=ClientTimeout(total=request_timeout),
)
res.raise_for_status()
return parse_response(tp, await res.read(), source=f"Steam {path}")
try:
response = await send_with_retries(send, provider="Steam", url=path)
except TimeoutError as exc:
raise SteamWebAPIError("Steam did not answer in time") from exc
except aiohttp.ClientResponseError as exc:
if exc.status in (401, 403):
raise SteamWebAPIError("Steam rejected the API key") from exc
raise SteamWebAPIError(f"Steam answered with HTTP {exc.status}") from exc
if response is None:
raise SteamWebAPIError("Steam sent a reply that could not be read")
return response
async def resolve_vanity_url(self, vanity_name: str) -> str | None:
"""The SteamID64 behind a custom profile URL name, or None if unused."""
response = await self._request(
"ISteamUser/ResolveVanityURL/v1/",
SteamVanityResponse,
{"vanityurl": vanity_name},
)
result = response.get("response", {})
if result.get("success") != STEAM_VANITY_RESOLVED:
return None
return result.get("steamid")
async def get_player_summary(self, steam_id: str) -> SteamPlayerSummary | None:
"""The public profile of a SteamID64, or None if no account has it."""
response = await self._request(
"ISteamUser/GetPlayerSummaries/v2/",
SteamPlayerSummariesResponse,
{"steamids": steam_id},
)
players = response.get("response", {}).get("players", [])
return players[0] if players else None
async def get_owned_games(self, steam_id: str) -> list[SteamOwnedGame] | None:
"""Every game the account owns, or None when its game details are private."""
response = await self._request(
"IPlayerService/GetOwnedGames/v1/",
SteamOwnedGamesResponse,
{
"steamid": steam_id,
"include_appinfo": "1",
"include_played_free_games": "1",
},
)
result = response.get("response", {})
if "game_count" not in result:
return None
return result.get("games", [])

View File

@@ -0,0 +1,81 @@
"""Add Steam library import: linked accounts, store-only roms, owned games
`storefront` is declared in `utils.roms_columns`, which adds it in one copy of
`roms` alongside any other catalog column the table lacks.
Revision ID: 0155_steam_library
Revises: 0154_ownerless_own_only
Create Date: 2026-10-26 00:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
from utils.database import column_names
from utils.roms_columns import ensure_roms_columns
# revision identifiers, used by Alembic.
revision = "0155_steam_library"
down_revision = "0154_ownerless_own_only"
branch_labels = None
depends_on = None
def upgrade() -> None:
connection = op.get_bind()
ensure_roms_columns(connection)
user_columns = column_names(connection, "users")
with op.batch_alter_table("users", schema=None) as batch_op:
if "steam_id" not in user_columns:
batch_op.add_column(sa.Column("steam_id", sa.String(length=20)))
if "steam_persona_name" not in user_columns:
batch_op.add_column(sa.Column("steam_persona_name", sa.String(length=255)))
op.create_table(
"steam_library_entries",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("rom_id", sa.Integer(), nullable=False),
sa.Column("steam_app_id", sa.Integer(), nullable=False),
sa.Column("playtime_minutes", sa.Integer(), nullable=False),
sa.Column("last_played_at", sa.TIMESTAMP(timezone=True), nullable=True),
sa.Column(
"created_at",
sa.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column(
"updated_at",
sa.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.ForeignKeyConstraint(["rom_id"], ["roms.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint(
"user_id", "steam_app_id", name="unique_steam_library_entry"
),
if_not_exists=True,
)
op.create_index(
"ix_steam_library_entries_rom_id",
"steam_library_entries",
["rom_id"],
unique=False,
if_not_exists=True,
)
def downgrade() -> None:
op.drop_table("steam_library_entries", if_exists=True)
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.drop_column("steam_persona_name", if_exists=True)
batch_op.drop_column("steam_id", if_exists=True)
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.drop_column("storefront", if_exists=True)

View File

@@ -181,6 +181,8 @@ CSDB_API_ENABLED: Final[bool] = safe_str_to_bool(_get_env("CSDB_API_ENABLED"))
# STEAM
STEAM_API_ENABLED: Final[bool] = safe_str_to_bool(_get_env("STEAM_API_ENABLED"))
# Steam Web API key, for importing users' Steam libraries.
STEAM_API_KEY: Final[str | None] = _get_env("STEAM_API_KEY")
# UPC LOOKUP (barcode -> title, used when adding physical games by UPC)
UPC_LOOKUP_ENABLED: Final[bool] = safe_str_to_bool(
@@ -358,6 +360,13 @@ SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON: Final[str] = _get_env(
"SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON",
"0 4 * * *", # At 4:00 AM every day
)
ENABLE_SCHEDULED_STEAM_LIBRARY_SYNC: Final[bool] = safe_str_to_bool(
_get_env("ENABLE_SCHEDULED_STEAM_LIBRARY_SYNC")
)
SCHEDULED_STEAM_LIBRARY_SYNC_CRON: Final[str] = _get_env(
"SCHEDULED_STEAM_LIBRARY_SYNC_CRON",
"30 4 * * *", # At 4:30 AM every day
)
# On by default: the similarity index is what both the "Similar games" section
# and the personalised feed read, so leaving it off silently empties them.
ENABLE_SCHEDULED_BUILD_RECOMMENDATIONS: Final[bool] = safe_str_to_bool(

View File

@@ -33,6 +33,7 @@ from config import (
SCHEDULED_RESCAN_CRON,
SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON,
SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON,
STEAM_API_KEY,
YOUTUBE_BASE_URL,
)
from config.config_manager import config_manager as cm
@@ -161,6 +162,7 @@ async def heartbeat() -> HeartbeatResponse:
"POUET_API_ENABLED": pouet_enabled,
"CSDB_API_ENABLED": csdb_enabled,
"STEAM_API_ENABLED": steam_enabled,
"STEAM_LIBRARY_ENABLED": bool(STEAM_API_KEY),
"LIBRETRO_API_ENABLED": libretro_enabled,
},
"FILESYSTEM": {

View File

@@ -27,6 +27,7 @@ class MetadataSourcesDict(TypedDict):
POUET_API_ENABLED: bool
CSDB_API_ENABLED: bool
STEAM_API_ENABLED: bool
STEAM_LIBRARY_ENABLED: bool
LIBRETRO_API_ENABLED: bool

View File

@@ -34,6 +34,8 @@ class UserSchema(BaseModel):
last_active: UTCDatetime | None
ra_username: str | None = None
ra_progression: RAProgression | None = None
steam_id: str | None = None
steam_persona_name: str | None = None
ui_settings: dict[str, Any] | None = None
current_device_id: str | None = None

View File

@@ -440,6 +440,7 @@ class RomSchema(BaseModel):
updated_at: UTCDatetime
missing_from_fs: bool
is_physical: bool
storefront: str | None
has_file_on_disk: bool
upc: str | None
has_notes: bool

View File

@@ -885,7 +885,9 @@ async def _scan_selected_roms(
async with scan_semaphore:
# A library scan learns this from splitting the platform folder into
# files and directories; with no listing to consult, ask the path.
is_flat = await fs_rom_handler.file_exists(rom.full_path)
is_flat = rom.never_has_file or await fs_rom_handler.file_exists(
rom.full_path
)
if not is_flat and not await fs_rom_handler.directory_exists(rom.full_path):
# A library scan never reaches an entry whose file is gone, since
# it walks the filesystem. Reaching one here must not resurrect
@@ -1554,7 +1556,7 @@ class ScanPayload(BaseModel):
}
def _enqueue_scan(payload: ScanPayload, started_by_user_id: int) -> Job:
def _enqueue_scan(payload: ScanPayload, started_by_user_id: int | None) -> Job:
"""Check the scan can run, then queue it, listing the workers once for both."""
workers = Worker.all(connection=redis_client)
if not has_live_worker(scan_queue, workers):
@@ -1584,8 +1586,8 @@ def _enqueue_scan(payload: ScanPayload, started_by_user_id: int) -> Job:
)
async def queue_scan(payload: ScanPayload, *, started_by_user_id: int) -> Job:
"""Queue a scan a user asked for on the scan worker.
async def queue_scan(payload: ScanPayload, *, started_by_user_id: int | None) -> Job:
"""Queue a scan on the scan worker, for a user or, with None, for a task.
Raises:
NoScanWorkerException: No worker listens on the scan queue.

View File

@@ -118,7 +118,7 @@ def _fill_cleanup_stats(stats: Mapping[str, Any] | None) -> CleanupStats | None:
return cast(CleanupStats, legacy)
def _build_task_execution_response(
def build_task_execution_response(
job: Job, task_key: str | None, task_name: str
) -> TaskExecutionResponse:
"""Describe a job that was just queued."""
@@ -391,7 +391,7 @@ async def run_single_task(
{"job_id": job.id, "kwargs": task_kwargs or {}},
)
return _build_task_execution_response(job, task_name, task_instance.title)
return build_task_execution_response(job, task_name, task_instance.title)
SCAN_PAYLOAD = Body(default_factory=ScanPayload)
@@ -424,4 +424,4 @@ async def start_scan(
except ScanInFlightException as e:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) from e
return _build_task_execution_response(job, None, job.meta["task_name"])
return build_task_execution_response(job, None, job.meta["task_name"])

View File

@@ -7,10 +7,13 @@ from fastapi import Path as PathVar
from fastapi import Request, status
from fastapi.responses import FileResponse
from config import STEAM_API_KEY
from decorators.auth import protected_route
from endpoints.forms.identity import UserForm
from endpoints.permissions import emit_permissions_changed
from endpoints.responses import TaskExecutionResponse
from endpoints.responses.identity import InviteLinkSchema, UserSchema
from endpoints.tasks import build_task_execution_response
from exceptions.database_exceptions import LastAdminError
from handler.audit_handler import (
AuditActor,
@@ -26,6 +29,7 @@ from handler.auth.dependencies import assert_admin_for_admin
from handler.database import (
db_client_token_handler,
db_device_handler,
db_steam_library_handler,
db_user_handler,
)
from handler.device_install import device_install_handler
@@ -38,10 +42,12 @@ from handler.metadata import meta_ra_handler
from handler.metadata.ra_handler import RAUserProgression
from handler.notification_handler import notify
from handler.socket_handler import close_client_token_sockets
from handler.steam_library_handler import SteamLibraryError, resolve_steam_profile
from logger.logger import log
from models.audit_event import AuditAction
from models.notification import NotificationKind, NotificationLevel
from models.user import Role, User
from models.user import TEXT_FIELD_LENGTH, Role, User
from tasks.registry import SYNC_STEAM_LIBRARIES_TASK, enqueue_task
from utils.router import APIRouter
from utils.validation import (
ValidationError,
@@ -737,3 +743,114 @@ async def refresh_retro_achievements(
},
)
return None
def _get_steam_user(request: Request, id: int) -> User:
"""The user whose Steam account is changed, if the caller may manage them."""
user = db_user_handler.get_user(id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="User not found"
)
_assert_can_manage_user(request, user)
return user
@protected_route(
router.put,
"/{id}/steam",
[Scope.ME_WRITE],
summary="Link a Steam account",
responses={
status.HTTP_400_BAD_REQUEST: {},
status.HTTP_403_FORBIDDEN: {},
status.HTTP_404_NOT_FOUND: {},
},
)
async def link_steam_account(
request: Request,
id: Annotated[int, PathVar(description="User internal id.", ge=1)],
profile: Annotated[
str,
Body(
description="SteamID64, Steam profile link, or custom profile URL name.",
embed=True,
max_length=TEXT_FIELD_LENGTH,
),
],
) -> UserSchema:
"""Link the Steam account whose games are imported for a user."""
user = _get_steam_user(request, id)
try:
summary = await resolve_steam_profile(profile)
except SteamLibraryError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
) from exc
# The library came from the previous account, so it no longer applies.
if user.steam_id and user.steam_id != summary["steamid"]:
db_steam_library_handler.delete_entries(user.id)
db_user_handler.update_user(
user.id,
{"steam_id": summary["steamid"], "steam_persona_name": summary["personaname"]},
)
return UserSchema.model_validate(db_user_handler.get_user(user.id))
@protected_route(
router.delete,
"/{id}/steam",
[Scope.ME_WRITE],
summary="Unlink a Steam account",
responses={status.HTTP_403_FORBIDDEN: {}, status.HTTP_404_NOT_FOUND: {}},
)
async def unlink_steam_account(
request: Request,
id: Annotated[int, PathVar(description="User internal id.", ge=1)],
) -> UserSchema:
"""Unlink a user's Steam account and forget which games it owns."""
user = _get_steam_user(request, id)
db_steam_library_handler.delete_entries(user.id)
db_user_handler.update_user(user.id, {"steam_id": None, "steam_persona_name": None})
return UserSchema.model_validate(db_user_handler.get_user(user.id))
@protected_route(
router.post,
"/{id}/steam/sync",
[Scope.ME_WRITE],
summary="Sync a Steam library",
status_code=status.HTTP_202_ACCEPTED,
responses={
status.HTTP_400_BAD_REQUEST: {},
status.HTTP_403_FORBIDDEN: {},
status.HTTP_404_NOT_FOUND: {},
},
)
async def sync_steam_account(
request: Request,
id: Annotated[int, PathVar(description="User internal id.", ge=1)],
) -> TaskExecutionResponse:
"""Queue an import of the games a user's linked Steam account owns."""
user = _get_steam_user(request, id)
if not STEAM_API_KEY:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Set STEAM_API_KEY to import Steam libraries",
)
if not user.steam_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Link a Steam account first",
)
job = enqueue_task(
SYNC_STEAM_LIBRARIES_TASK,
task_kwargs={"user_id": user.id},
run_by_user_id=request.user.id,
)
return build_task_execution_response(
job, SYNC_STEAM_LIBRARIES_TASK, job.meta["task_name"]
)

View File

@@ -19,6 +19,7 @@ from .saves_handler import DBSavesHandler
from .screenshots_handler import DBScreenshotsHandler
from .states_handler import DBStatesHandler
from .stats_handler import DBStatsHandler
from .steam_library_handler import DBSteamLibraryHandler
from .sync_sessions_handler import DBSyncSessionsHandler
from .users_handler import DBUsersHandler
@@ -42,6 +43,7 @@ db_rom_handler = DBRomsHandler()
db_save_handler = DBSavesHandler()
db_screenshot_handler = DBScreenshotsHandler()
db_state_handler = DBStatesHandler()
db_steam_library_handler = DBSteamLibraryHandler()
db_stats_handler = DBStatsHandler()
db_sync_session_handler = DBSyncSessionsHandler()
db_user_handler = DBUsersHandler()

View File

@@ -172,6 +172,10 @@ class RomFilterParams(BaseModel):
bool | None,
Field(description="Whether the rom is a physical copy with no file."),
] = None
store_only: Annotated[
bool | None,
Field(description="Whether the rom is a store-only game with no file."),
] = None
has_ra: Annotated[
bool | None,
Field(description="Whether the rom has RetroAchievements data."),

View File

@@ -95,6 +95,7 @@ from models.rom import (
compute_name_sort_key,
compute_search_titles,
fold_search_title,
rom_without_file,
)
from utils import get_version
from utils.age_ratings import MIN_AGE_SOURCE_COLUMNS, compute_min_age
@@ -1408,10 +1409,10 @@ class DBRomsHandler(DBBaseHandler):
# though, and this filter backs the Missing tab's whole-library scan.
if not value:
return query.filter(Rom.missing_from_fs == false())
# Physical games are never "missing"; exclude them so a stray flag can
# A game without a file is never "missing"; exclude it so a stray flag can
# never make one eligible for the missing-roms cleanup that hard-deletes.
return query.filter(
and_(Rom.missing_from_fs == true(), Rom.is_physical.is_(False))
and_(Rom.missing_from_fs == true(), not_(rom_without_file()))
)
def _filter_by_verified[S: Select[*tuple[Any, ...]]](
@@ -1679,6 +1680,13 @@ class DBRomsHandler(DBBaseHandler):
if filters.physical is not None:
query = query.filter(Rom.is_physical.is_(filters.physical))
if filters.store_only is not None:
query = query.filter(
Rom.storefront.is_not(None)
if filters.store_only
else Rom.storefront.is_(None)
)
if filters.verified is not None:
query = self._filter_by_verified(query, value=filters.verified)
@@ -2484,12 +2492,12 @@ class DBRomsHandler(DBBaseHandler):
changes, so a re-scan of an unchanged platform issues no updates.
"""
keep_set = set(fs_roms_to_keep)
# Physical games have no file on disk, so they must never be flagged missing.
# Games without a file on disk must never be flagged missing.
rows = session.execute(
select(Rom.id, Rom.fs_path, Rom.fs_name, Rom.missing_from_fs).where(
and_(
Rom.platform_id == platform_id,
Rom.is_physical.is_(False),
not_(rom_without_file()),
)
)
).all()
@@ -2519,7 +2527,7 @@ class DBRomsHandler(DBBaseHandler):
and_(
Rom.platform_id == platform_id,
Rom.missing_from_fs.is_(True),
Rom.is_physical.is_(False),
not_(rom_without_file()),
)
)
.order_by(Rom.fs_name.asc())

View File

@@ -0,0 +1,130 @@
from collections.abc import Sequence
from sqlalchemy import delete, select
from sqlalchemy.orm import Session
from decorators.database import INJECTED_SESSION, begin_session
from models.platform import Platform
from models.rom import Rom
from models.steam_library import SteamLibraryEntry
from utils.database import is_non_blank
from .base_handler import DBBaseHandler, affected_rows
# Keeps each IN list well under every database's bound-parameter limit.
STEAM_ID_CHUNK_SIZE = 1000
class DBSteamLibraryHandler(DBBaseHandler):
@begin_session
def get_rom_ids_by_steam_app_id(
self,
platform_slugs: Sequence[str],
steam_app_ids: Sequence[int],
session: Session = INJECTED_SESSION,
) -> dict[int, int]:
"""The rom that stands for each Steam app on the given platforms.
A rom with a file wins over a store-only one, then the oldest row.
"""
rows: list[tuple[int | None, int, str | None]] = []
ids = list(steam_app_ids)
for start in range(0, len(ids), STEAM_ID_CHUNK_SIZE):
rows.extend(
(app_id, rom_id, storefront)
for app_id, rom_id, storefront in session.execute(
select(Rom.steam_id, Rom.id, Rom.storefront)
.join(Platform, Platform.id == Rom.platform_id)
.where(
Platform.slug.in_(platform_slugs),
Rom.steam_id.in_(ids[start : start + STEAM_ID_CHUNK_SIZE]),
)
).all()
)
rom_ids: dict[int, int] = {}
for app_id, rom_id, _ in sorted(
rows, key=lambda row: (row[2] is not None, row[1])
):
if app_id is not None:
rom_ids.setdefault(app_id, rom_id)
return rom_ids
@begin_session
def get_unmatched_store_only_rom_ids(
self, rom_ids: Sequence[int], session: Session = INJECTED_SESSION
) -> list[int]:
"""The store-only roms among `rom_ids` that no metadata source matched yet."""
# Their Steam id is set at creation, so the cover a match fills in tells instead.
ids = list(rom_ids)
unmatched: list[int] = []
for start in range(0, len(ids), STEAM_ID_CHUNK_SIZE):
unmatched.extend(
session.scalars(
select(Rom.id).where(
Rom.id.in_(ids[start : start + STEAM_ID_CHUNK_SIZE]),
Rom.storefront.is_not(None),
~is_non_blank(Rom.url_cover),
)
).all()
)
return unmatched
@begin_session
def get_entries(
self, user_id: int, session: Session = INJECTED_SESSION
) -> Sequence[SteamLibraryEntry]:
return session.scalars(
select(SteamLibraryEntry).where(SteamLibraryEntry.user_id == user_id)
).all()
@begin_session
def replace_entries(
self,
user_id: int,
entries: Sequence[SteamLibraryEntry],
session: Session = INJECTED_SESSION,
) -> int:
"""Make `entries` the user's whole Steam library.
Returns:
How many entries were removed because the game is no longer owned.
"""
existing = {
entry.steam_app_id: entry
for entry in session.scalars(
select(SteamLibraryEntry).where(SteamLibraryEntry.user_id == user_id)
).all()
}
owned = {entry.steam_app_id for entry in entries}
dropped = [app_id for app_id in existing if app_id not in owned]
for start in range(0, len(dropped), STEAM_ID_CHUNK_SIZE):
session.execute(
delete(SteamLibraryEntry).where(
SteamLibraryEntry.user_id == user_id,
SteamLibraryEntry.steam_app_id.in_(
dropped[start : start + STEAM_ID_CHUNK_SIZE]
),
)
)
for entry in entries:
current = existing.get(entry.steam_app_id)
if current is None:
entry.user_id = user_id
session.add(entry)
continue
current.rom_id = entry.rom_id
current.playtime_minutes = entry.playtime_minutes
current.last_played_at = entry.last_played_at
return len(dropped)
@begin_session
def delete_entries(self, user_id: int, session: Session = INJECTED_SESSION) -> int:
return affected_rows(
session.execute(
delete(SteamLibraryEntry).where(SteamLibraryEntry.user_id == user_id)
)
)

View File

@@ -21,6 +21,7 @@ class DBUsersHandler(DBBaseHandler):
emails: Sequence[str] = (),
roles: Sequence[Role] = (),
has_ra_username: bool | None = None,
has_steam_id: bool | None = None,
) -> QueryT:
if usernames:
query = query.filter(
@@ -37,6 +38,10 @@ class DBUsersHandler(DBBaseHandler):
if not has_ra_username:
predicate = not_(predicate)
query = query.filter(predicate)
if has_steam_id is not None:
query = query.filter(
User.steam_id.isnot(None) if has_steam_id else User.steam_id.is_(None)
)
return query
@begin_session
@@ -131,6 +136,7 @@ class DBUsersHandler(DBBaseHandler):
emails: Sequence[str] = (),
roles: Sequence[Role] = (),
has_ra_username: bool | None = None,
has_steam_id: bool | None = None,
only_fields: Sequence[QueryableAttribute[Any]] | None = None,
session: Session = INJECTED_SESSION,
) -> Sequence[User]:
@@ -140,6 +146,7 @@ class DBUsersHandler(DBBaseHandler):
emails=emails,
roles=roles,
has_ra_username=has_ra_username,
has_steam_id=has_steam_id,
)
if only_fields:

View File

@@ -618,6 +618,7 @@ async def scan_rom(
"fs_size_bytes": rom.fs_size_bytes,
"is_physical": rom.is_physical,
"upc": rom.upc,
"storefront": rom.storefront,
}
file_attrs = fs_rom_file_attrs(fs_rom)

View File

@@ -0,0 +1,214 @@
"""Linking a user's Steam account and importing the games it owns."""
import re
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Final
from sqlalchemy.exc import IntegrityError
from adapters.services.steam_types import SteamOwnedGame, SteamPlayerSummary
from adapters.services.steam_web_api import SteamWebAPIError, SteamWebAPIService
from config import STEAM_API_KEY
from exceptions.fs_exceptions import PlatformAlreadyExistsException
from handler.database import (
db_platform_handler,
db_rom_handler,
db_steam_library_handler,
)
from handler.filesystem import fs_platform_handler, fs_rom_handler
from handler.metadata.steam_handler import STEAM_PLATFORMS
from handler.scan_handler import scan_platform
from logger.logger import log
from models.platform import Platform
from models.rom import Rom, RomStorefront
from models.steam_library import SteamLibraryEntry
from models.user import User
from utils.filesystem import sanitize_filename
from utils.platform_slugs import UniversalPlatformSlug as UPS
# Store-only games sit in a folder no scan lists, like physical games do.
STEAM_FS_SUBDIR: Final = ".steam"
STEAM_LIBRARY_PLATFORM: Final = UPS.WIN
STEAM_ID64_RE: Final = re.compile(r"^7656119\d{10}$")
STEAM_VANITY_RE: Final = re.compile(r"^[A-Za-z0-9_-]{2,32}$")
STEAM_PROFILE_URL_RE: Final = re.compile(
r"^(?:https?://)?(?:www\.)?steamcommunity\.com/(profiles|id)/([^/?#]+)/?(?:[?#].*)?$",
re.IGNORECASE,
)
class SteamLibraryError(Exception):
"""A Steam account can't be linked or synced, worded for the user."""
@dataclass
class SteamSyncResult:
owned: int = 0
linked: int = 0
created: int = 0
removed: int = 0
# Store-only roms no metadata source matched yet, new ones included.
unmatched_rom_ids: list[int] = field(default_factory=list)
def steam_web_api() -> SteamWebAPIService:
if not STEAM_API_KEY:
raise SteamLibraryError("Set STEAM_API_KEY to import Steam libraries")
return SteamWebAPIService(STEAM_API_KEY)
def parse_steam_profile(profile: str) -> tuple[str | None, str | None]:
"""Split what a user typed into a SteamID64 or a custom URL name.
Returns:
`(steam_id, None)` or `(None, vanity_name)`.
Raises:
SteamLibraryError: The text is neither.
"""
text = profile.strip()
url = STEAM_PROFILE_URL_RE.match(text)
if url:
kind, value = url.group(1).lower(), url.group(2)
if kind == "profiles" and STEAM_ID64_RE.match(value):
return value, None
if kind == "id" and STEAM_VANITY_RE.match(value):
return None, value
elif STEAM_ID64_RE.match(text):
return text, None
elif STEAM_VANITY_RE.match(text):
return None, text
raise SteamLibraryError(
f"{text!r} isn't a SteamID64, a Steam profile link or a custom URL name"
)
async def resolve_steam_profile(profile: str) -> SteamPlayerSummary:
"""Find the Steam account a SteamID64, profile link or custom URL name names."""
steam_id, vanity_name = parse_steam_profile(profile)
api = steam_web_api()
try:
if vanity_name is not None:
steam_id = await api.resolve_vanity_url(vanity_name)
if steam_id is None:
raise SteamLibraryError(
f"No Steam profile uses the custom URL {vanity_name!r}"
)
summary = await api.get_player_summary(steam_id)
except SteamWebAPIError as exc:
raise SteamLibraryError(str(exc)) from exc
if summary is None:
raise SteamLibraryError(f"No Steam account has the ID {steam_id}")
return summary
async def steam_library_platform() -> Platform:
"""The platform store-only Steam games go on, creating its folder if needed."""
platform = db_platform_handler.get_platform_by_slug(STEAM_LIBRARY_PLATFORM)
if platform is not None:
return platform
fs_slug = STEAM_LIBRARY_PLATFORM.value
try:
await fs_platform_handler.add_platform(fs_slug=fs_slug)
except PlatformAlreadyExistsException:
pass
except OSError as exc:
raise SteamLibraryError(
f"Could not create the {fs_slug!r} platform folder for Steam games"
) from exc
return db_platform_handler.add_platform(await scan_platform(fs_slug, [fs_slug]))
def _store_only_rom(platform: Platform, game: SteamOwnedGame) -> Rom:
app_id = game["appid"]
name = game.get("name") or f"Steam app {app_id}"
return Rom(
platform_id=platform.id,
# The tag lets the Steam provider match by id, as it does for files.
fs_name=sanitize_filename(f"{name} (steam-{app_id})"),
fs_path=(
f"{fs_rom_handler.get_roms_fs_structure(platform.fs_slug)}"
f"/{STEAM_FS_SUBDIR}"
),
fs_size_bytes=0,
name=name,
steam_id=app_id,
storefront=RomStorefront.STEAM,
url_cover="",
url_manual="",
url_screenshots=[],
)
def _last_played(game: SteamOwnedGame) -> datetime | None:
# Steam sends 0 for a game never played.
timestamp = game.get("rtime_last_played") or 0
return datetime.fromtimestamp(timestamp, timezone.utc) if timestamp else None
async def sync_steam_library(user: User) -> SteamSyncResult:
"""Make the user's Steam library entries match what their account owns.
Owned games already in the library are linked to their rom; the rest get a
store-only rom. Store-only roms still unmatched are listed for a metadata
scan, since a library scan never reaches a game without a file.
Raises:
SteamLibraryError: The account isn't linked, or Steam can't list its games.
"""
if not user.steam_id:
raise SteamLibraryError(f"{user.username} has no linked Steam account")
try:
games = await steam_web_api().get_owned_games(user.steam_id)
except SteamWebAPIError as exc:
raise SteamLibraryError(str(exc)) from exc
if games is None:
raise SteamLibraryError(
"Steam keeps this account's games private. Set the profile's "
"Game details to Public in Steam's privacy settings"
)
platform = await steam_library_platform()
rom_ids = db_steam_library_handler.get_rom_ids_by_steam_app_id(
[slug.value for slug in STEAM_PLATFORMS],
[game["appid"] for game in games],
)
result = SteamSyncResult(owned=len(games), linked=len(rom_ids))
entries: list[SteamLibraryEntry] = []
for game in games:
app_id = game["appid"]
if app_id not in rom_ids:
try:
rom = db_rom_handler.add_rom(_store_only_rom(platform, game))
except IntegrityError:
log.warning(
f"Skipping Steam app {app_id}: another game already uses its name"
)
continue
rom_ids[app_id] = rom.id
result.created += 1
entries.append(
SteamLibraryEntry(
rom_id=rom_ids[app_id],
steam_app_id=app_id,
playtime_minutes=game.get("playtime_forever", 0),
last_played_at=_last_played(game),
)
)
result.removed = db_steam_library_handler.replace_entries(user.id, entries)
result.unmatched_rom_ids = (
db_steam_library_handler.get_unmatched_store_only_rom_ids(
[entry.rom_id for entry in entries]
)
)
return result

View File

@@ -197,6 +197,10 @@ if TYPE_CHECKING:
from models.user import User
class RomStorefront(enum.StrEnum):
STEAM = "steam"
class RomFileCategory(enum.StrEnum):
GAME = "game"
DLC = "dlc"
@@ -1043,6 +1047,8 @@ class Rom(BaseModel):
# same metadata as digital ROMs but must never be flagged missing or cleaned up.
is_physical: Mapped[bool] = mapped_column(default=False, nullable=False)
upc: Mapped[str | None] = mapped_column(String(length=64), default=None)
# Set on a game imported from a store library with no file behind it.
storefront: Mapped[str | None] = mapped_column(String(length=32), default=None)
platform_id: Mapped[int] = mapped_column(
ForeignKey("platforms.id", ondelete="CASCADE")
@@ -1241,16 +1247,21 @@ class Rom(BaseModel):
getattr(self, column.key) for column in METADATA_SOURCE_COLUMNS.values()
)
@property
def never_has_file(self) -> bool:
"""Whether this row stands for a game with no file at all."""
return self.is_physical or self.storefront is not None
@property
def has_file_on_disk(self) -> bool:
"""Whether a readable file backs this rom.
False for two different reasons that every file-dependent surface
(download, playback, the ES-DE and Pegasus exporters, the device feeds)
needs to treat alike: a physical game never had a file, and a missing
one no longer does.
needs to treat alike: a physical or store-only game never had a file,
and a missing one no longer does.
"""
return not self.is_physical and not self.missing_from_fs
return not self.never_has_file and not self.missing_from_fs
def has_m3u_file(self) -> bool:
"""
@@ -1374,6 +1385,11 @@ Rom.is_easyrpg_game = column_property(
)
def rom_without_file() -> ColumnElement[bool]:
"""Matches rows that never had a file: physical games and store-only ones."""
return or_(Rom.is_physical.is_(True), Rom.storefront.is_not(None))
def apply_file_stats(rom: Rom, files: Sequence[RomFile]) -> None:
"""Fill the deferred file-stat columns from an already-loaded file list."""
set_committed_value(
@@ -1458,6 +1474,7 @@ def _refresh_min_age(_mapper: Any, _connection: Any, rom: Rom) -> None:
class HasFileOnDiskFilters(TypedDict):
physical: bool
store_only: bool
missing: bool
@@ -1465,6 +1482,7 @@ class HasFileOnDiskFilters(TypedDict):
# want the file-less ones dropped by the database rather than after loading.
HAS_FILE_ON_DISK_FILTERS: Final[HasFileOnDiskFilters] = {
"physical": False,
"store_only": False,
"missing": False,
}

View File

@@ -0,0 +1,27 @@
from __future__ import annotations
from datetime import datetime
from sqlalchemy import TIMESTAMP, ForeignKey, Index, Integer, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from models.base import BaseModel
class SteamLibraryEntry(BaseModel):
"""A game a user owns on Steam, linked to the rom that represents it."""
__tablename__ = "steam_library_entries"
__table_args__ = (
UniqueConstraint("user_id", "steam_app_id", name="unique_steam_library_entry"),
Index("ix_steam_library_entries_rom_id", "rom_id"),
)
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
rom_id: Mapped[int] = mapped_column(ForeignKey("roms.id", ondelete="CASCADE"))
steam_app_id: Mapped[int] = mapped_column(Integer())
playtime_minutes: Mapped[int] = mapped_column(Integer(), default=0)
last_played_at: Mapped[datetime | None] = mapped_column(
TIMESTAMP(timezone=True), default=None
)

View File

@@ -101,6 +101,11 @@ class User(BaseModel, SimpleUser):
ra_progression: Mapped[dict[str, Any] | None] = mapped_column(
CustomJSON(), default=dict
)
# A SteamID64 overflows JavaScript's safe integers, so it is kept as text.
steam_id: Mapped[str | None] = mapped_column(String(length=20), default=None)
steam_persona_name: Mapped[str | None] = mapped_column(
String(length=TEXT_FIELD_LENGTH), default=None
)
ui_settings: Mapped[dict[str, Any] | None] = mapped_column(
CustomJSON(), default=dict
)

View File

@@ -18,6 +18,7 @@ from config import (
ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP,
ENABLE_SCHEDULED_RESCAN,
ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC,
ENABLE_SCHEDULED_STEAM_LIBRARY_SYNC,
ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA,
ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB,
ENABLE_SYNC_FOLDER_WATCHER,
@@ -34,6 +35,7 @@ from config import (
SCHEDULED_CONVERT_IMAGES_TO_WEBP_CRON,
SCHEDULED_RESCAN_CRON,
SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON,
SCHEDULED_STEAM_LIBRARY_SYNC_CRON,
SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON,
SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON,
SYNC_PUSH_PULL_CRON,
@@ -204,6 +206,17 @@ SYNC_RETROACHIEVEMENTS_PROGRESS_SPEC: Final = TaskSpec(
cron_string=SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON,
)
# Also queued for a single user when they sync their linked Steam account.
SYNC_STEAM_LIBRARIES_TASK: Final = "sync_steam_libraries"
SYNC_STEAM_LIBRARIES_SPEC: Final = TaskSpec(
implementation="tasks.scheduled.sync_steam_libraries.sync_steam_libraries_task",
title="Scheduled Steam library sync",
description="Imports the games each linked Steam account owns",
task_type=TaskType.UPDATE,
enabled=ENABLE_SCHEDULED_STEAM_LIBRARY_SYNC,
cron_string=SCHEDULED_STEAM_LIBRARY_SYNC_CRON,
)
SYNC_PUSH_PULL_SPEC: Final = TaskSpec(
implementation="tasks.sync_push_pull_task.sync_push_pull_task",
title="Push-Pull Sync",
@@ -288,6 +301,7 @@ SCHEDULED_TASKS: Final[dict[str, TaskSpec]] = {
"cleanup_sync_sessions": CLEANUP_SYNC_SESSIONS_SPEC,
"cleanup_audit_log": CLEANUP_AUDIT_LOG_SPEC,
"sync_retroachievements_progress": SYNC_RETROACHIEVEMENTS_PROGRESS_SPEC,
SYNC_STEAM_LIBRARIES_TASK: SYNC_STEAM_LIBRARIES_SPEC,
"sync_push_pull": SYNC_PUSH_PULL_SPEC,
}

View File

@@ -0,0 +1,76 @@
from typing import Any
from config import STEAM_API_KEY
from endpoints.sockets.scan import ScanPayload, queue_scan
from exceptions.socket_exceptions import NoScanWorkerException
from handler.database import db_user_handler
from handler.steam_library_handler import SteamLibraryError, sync_steam_library
from logger.logger import log
from models.user import User
from tasks.registry import SYNC_STEAM_LIBRARIES_SPEC
from tasks.tasks import PeriodicTask
from utils.context import initialize_context
from . import UpdateStats
async def _scan_unmatched_roms(rom_ids: list[int], user_id: int | None) -> None:
try:
await queue_scan(ScanPayload(roms_ids=rom_ids), started_by_user_id=user_id)
except NoScanWorkerException:
log.warning(
f"No scan worker is running, so {len(rom_ids)} Steam games wait for "
"the next sync to get their metadata"
)
class SyncSteamLibrariesTask(PeriodicTask):
def __init__(self) -> None:
super().__init__(SYNC_STEAM_LIBRARIES_SPEC)
@initialize_context()
async def run(self, user_id: int | None = None) -> dict[str, Any]:
"""Sync one user's Steam library, or every linked user's.
Raises:
SteamLibraryError: The one user asked for can't be synced.
"""
update_stats = UpdateStats()
if not STEAM_API_KEY:
log.warning("STEAM_API_KEY is not set, skipping Steam library sync")
return update_stats.to_dict()
users: list[User]
if user_id is None:
users = list(db_user_handler.get_users(has_steam_id=True))
else:
user = db_user_handler.get_user(user_id)
users = [user] if user is not None else []
update_stats.update(processed=0, total=len(users))
unmatched_rom_ids: list[int] = []
for processed, user in enumerate(users, start=1):
try:
result = await sync_steam_library(user)
except SteamLibraryError as e:
# A sync someone asked for reports its failure to them.
if user_id is not None:
raise
log.error(f"Steam library sync failed for {user.username}: {e}")
else:
log.info(
f"Synced {user.username}'s Steam library: {result.owned} owned, "
f"{result.linked} already in the library, {result.created} "
f"added, {result.removed} no longer owned"
)
unmatched_rom_ids.extend(result.unmatched_rom_ids)
update_stats.update(processed=processed)
if unmatched_rom_ids:
await _scan_unmatched_roms(sorted(set(unmatched_rom_ids)), user_id)
return update_stats.to_dict()
sync_steam_libraries_task = SyncSteamLibrariesTask()

View File

@@ -0,0 +1,128 @@
import json
from unittest.mock import AsyncMock, MagicMock, patch
import aiohttp
import pytest
from adapters.services.steam_web_api import SteamWebAPIError, SteamWebAPIService
STEAM_ID = "76561197960287930"
def _response(json_body: object) -> MagicMock:
response = MagicMock()
response.raise_for_status = MagicMock()
response.read = AsyncMock(return_value=json.dumps(json_body).encode())
return response
def _error(status_code: int) -> aiohttp.ClientResponseError:
return aiohttp.ClientResponseError(
request_info=MagicMock(), history=(), status=status_code
)
@pytest.fixture(autouse=True)
def no_backoff_sleep():
with patch("adapters.services.provider_http.asyncio.sleep", new_callable=AsyncMock):
yield
@pytest.fixture
def session():
mock_session = AsyncMock()
with patch("adapters.services.steam_web_api.ctx_aiohttp_session") as mock_ctx:
mock_ctx.get.return_value = mock_session
yield mock_session
def _service() -> SteamWebAPIService:
return SteamWebAPIService("secret-key")
async def test_sends_the_key_and_parameters(session):
session.get.return_value = _response(
{"response": {"success": 1, "steamid": STEAM_ID}}
)
await _service().resolve_vanity_url("gabe")
url = session.get.await_args.args[0]
assert url.path == "/ISteamUser/ResolveVanityURL/v1/"
assert url.query["key"] == "secret-key"
assert url.query["vanityurl"] == "gabe"
async def test_resolves_a_custom_name(session):
session.get.return_value = _response(
{"response": {"success": 1, "steamid": STEAM_ID}}
)
assert await _service().resolve_vanity_url("gabe") == STEAM_ID
async def test_an_unused_custom_name_resolves_to_nothing(session):
session.get.return_value = _response(
{"response": {"success": 42, "message": "No match"}}
)
assert await _service().resolve_vanity_url("nobody") is None
async def test_returns_the_player_summary(session):
player = {
"steamid": STEAM_ID,
"personaname": "Gabe",
"profileurl": "https://steamcommunity.com/id/gabe/",
"communityvisibilitystate": 3,
}
session.get.return_value = _response({"response": {"players": [player]}})
assert await _service().get_player_summary(STEAM_ID) == player
async def test_an_unknown_account_has_no_summary(session):
session.get.return_value = _response({"response": {"players": []}})
assert await _service().get_player_summary(STEAM_ID) is None
async def test_lists_owned_games(session):
games = [{"appid": 220, "name": "Half-Life 2", "playtime_forever": 90}]
session.get.return_value = _response(
{"response": {"game_count": 1, "games": games}}
)
assert await _service().get_owned_games(STEAM_ID) == games
url = session.get.await_args.args[0]
assert url.query["include_appinfo"] == "1"
assert url.query["include_played_free_games"] == "1"
async def test_an_account_owning_nothing_lists_no_games(session):
session.get.return_value = _response({"response": {"game_count": 0}})
assert await _service().get_owned_games(STEAM_ID) == []
async def test_a_private_library_lists_nothing_at_all(session):
session.get.return_value = _response({"response": {}})
assert await _service().get_owned_games(STEAM_ID) is None
@pytest.mark.parametrize("status_code", [401, 403])
async def test_a_rejected_key_is_an_error(session, status_code: int):
response = _response({})
response.raise_for_status.side_effect = _error(status_code)
session.get.return_value = response
with pytest.raises(SteamWebAPIError, match="API key"):
await _service().get_owned_games(STEAM_ID)
async def test_a_timeout_on_every_attempt_is_an_error(session):
session.get.side_effect = TimeoutError
with pytest.raises(SteamWebAPIError, match="in time"):
await _service().get_owned_games(STEAM_ID)

View File

@@ -2064,6 +2064,39 @@ class TestScanSelectedRoms:
identify.assert_not_called()
db_rom.update_rom.assert_called_once_with(rom.id, {"missing_from_fs": True})
@pytest.mark.parametrize(
"fileless", [{"is_physical": True}, {"storefront": "steam"}]
)
async def test_a_rom_without_a_file_by_design_is_scanned(
self, mocker, platform, rom, fileless
):
for key, value in fileless.items():
setattr(rom, key, value)
mocker.patch.object(
scan_module, "redis_client", Mock(get=Mock(return_value=None))
)
file_exists = mocker.patch.object(fs_rom_handler, "file_exists", AsyncMock())
db_rom = mocker.patch.object(scan_module, "db_rom_handler")
identify = mocker.patch.object(
scan_module, "_identify_rom", side_effect=AsyncMock()
)
await _scan_selected_roms(
platform=platform,
roms=[rom],
scan_type=ScanType.COMPLETE,
roms_ids=[rom.id],
metadata_sources=[],
launchbox_remote_enabled=False,
socket_manager=AsyncMock(),
scan_stats=AsyncMock(),
scanned_rom_ids=set(),
)
file_exists.assert_not_called()
db_rom.update_rom.assert_not_called()
identify.assert_called_once()
async def test_a_multi_file_rom_is_reported_as_not_flat(
self, mocker, platform, rom
):

View File

@@ -0,0 +1,197 @@
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import status
from fastapi.testclient import TestClient
from rq.job import JobStatus
from tests.factories import make_platform, make_rom
from handler.database import db_steam_library_handler, db_user_handler
from handler.steam_library_handler import SteamLibraryError
from models.steam_library import SteamLibraryEntry
from models.user import User
from tasks.registry import SYNC_STEAM_LIBRARIES_TASK
STEAM_ID = "76561197960287930"
OTHER_STEAM_ID = "76561197960287931"
def _bearer(token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
def _summary(steam_id: str = STEAM_ID, name: str = "Gabe") -> dict[str, object]:
return {
"steamid": steam_id,
"personaname": name,
"profileurl": f"https://steamcommunity.com/profiles/{steam_id}/",
"communityvisibilitystate": 3,
}
def _own_one_game(user: User) -> None:
rom = make_rom(make_platform("win"), "Half-Life 2", steam_id=220)
db_steam_library_handler.replace_entries(
user.id,
[SteamLibraryEntry(rom_id=rom.id, steam_app_id=220, playtime_minutes=5)],
)
@pytest.fixture
def resolve_profile():
with patch(
"endpoints.user.resolve_steam_profile", new_callable=AsyncMock
) as resolve:
resolve.return_value = _summary()
yield resolve
def test_links_the_resolved_account(
client: TestClient, access_token: str, admin_user: User, resolve_profile
):
response = client.put(
f"/api/users/{admin_user.id}/steam",
json={"profile": "https://steamcommunity.com/id/gabe"},
headers=_bearer(access_token),
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["steam_id"] == STEAM_ID
assert response.json()["steam_persona_name"] == "Gabe"
resolve_profile.assert_awaited_once_with("https://steamcommunity.com/id/gabe")
def test_a_profile_steam_cannot_resolve_is_a_bad_request(
client: TestClient, access_token: str, admin_user: User, resolve_profile
):
resolve_profile.side_effect = SteamLibraryError("No Steam profile uses it")
response = client.put(
f"/api/users/{admin_user.id}/steam",
json={"profile": "nobody"},
headers=_bearer(access_token),
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["detail"] == "No Steam profile uses it"
user = db_user_handler.get_user(admin_user.id)
assert user is not None and user.steam_id is None
def test_linking_another_account_forgets_the_old_library(
client: TestClient, access_token: str, admin_user: User, resolve_profile
):
db_user_handler.update_user(admin_user.id, {"steam_id": STEAM_ID})
_own_one_game(admin_user)
resolve_profile.return_value = _summary(OTHER_STEAM_ID)
client.put(
f"/api/users/{admin_user.id}/steam",
json={"profile": OTHER_STEAM_ID},
headers=_bearer(access_token),
)
assert db_steam_library_handler.get_entries(admin_user.id) == []
def test_relinking_the_same_account_keeps_the_library(
client: TestClient, access_token: str, admin_user: User, resolve_profile
):
db_user_handler.update_user(admin_user.id, {"steam_id": STEAM_ID})
_own_one_game(admin_user)
client.put(
f"/api/users/{admin_user.id}/steam",
json={"profile": STEAM_ID},
headers=_bearer(access_token),
)
assert len(db_steam_library_handler.get_entries(admin_user.id)) == 1
def test_a_user_cannot_link_someone_elses_account(
client: TestClient, viewer_access_token: str, admin_user: User, resolve_profile
):
response = client.put(
f"/api/users/{admin_user.id}/steam",
json={"profile": STEAM_ID},
headers=_bearer(viewer_access_token),
)
assert response.status_code == status.HTTP_403_FORBIDDEN
resolve_profile.assert_not_awaited()
def test_unlinking_clears_the_account_and_its_library(
client: TestClient, access_token: str, admin_user: User
):
db_user_handler.update_user(
admin_user.id, {"steam_id": STEAM_ID, "steam_persona_name": "Gabe"}
)
_own_one_game(admin_user)
response = client.delete(
f"/api/users/{admin_user.id}/steam", headers=_bearer(access_token)
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["steam_id"] is None
assert response.json()["steam_persona_name"] is None
assert db_steam_library_handler.get_entries(admin_user.id) == []
def _job() -> SimpleNamespace:
return SimpleNamespace(
id="job-1",
meta={"task_name": "Scheduled Steam library sync"},
created_at=None,
enqueued_at=None,
get_status=lambda refresh: JobStatus.QUEUED,
)
@patch("endpoints.user.STEAM_API_KEY", "key")
def test_sync_queues_the_task_for_that_user(
client: TestClient, access_token: str, admin_user: User
):
db_user_handler.update_user(admin_user.id, {"steam_id": STEAM_ID})
with patch("endpoints.user.enqueue_task", return_value=_job()) as enqueue:
response = client.post(
f"/api/users/{admin_user.id}/steam/sync", headers=_bearer(access_token)
)
assert response.status_code == status.HTTP_202_ACCEPTED
assert response.json()["task_id"] == "job-1"
enqueue.assert_called_once_with(
SYNC_STEAM_LIBRARIES_TASK,
task_kwargs={"user_id": admin_user.id},
run_by_user_id=admin_user.id,
)
@patch("endpoints.user.STEAM_API_KEY", "key")
def test_sync_needs_a_linked_account(
client: TestClient, access_token: str, admin_user: User
):
enqueue = MagicMock()
with patch("endpoints.user.enqueue_task", enqueue):
response = client.post(
f"/api/users/{admin_user.id}/steam/sync", headers=_bearer(access_token)
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
enqueue.assert_not_called()
@patch("endpoints.user.STEAM_API_KEY", None)
def test_sync_needs_an_api_key(client: TestClient, access_token: str, admin_user: User):
db_user_handler.update_user(admin_user.id, {"steam_id": STEAM_ID})
response = client.post(
f"/api/users/{admin_user.id}/steam/sync", headers=_bearer(access_token)
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "STEAM_API_KEY" in response.json()["detail"]

View File

@@ -1,5 +1,6 @@
from datetime import datetime, timezone
from types import SimpleNamespace
from typing import Any
from unittest.mock import patch
import pytest
@@ -25,7 +26,7 @@ from handler.database import (
from handler.database.base_handler import sync_session
from models.assets import Save, Screenshot, State
from models.platform import Platform
from models.rom import Rom
from models.rom import HAS_FILE_ON_DISK_FILTERS, Rom
from models.user import Role, User
@@ -44,19 +45,36 @@ def test_platforms():
assert len(platforms) == 1
def _add_physical_rom(platform: Platform, name: str = "Physical Game") -> Rom:
FILELESS_KINDS = pytest.mark.parametrize(
"fileless",
[
{"is_physical": True, "fs_path": ".physical"},
{"storefront": "steam", "fs_path": ".steam"},
],
ids=["physical", "store_only"],
)
def _add_physical_rom(
platform: Platform,
name: str = "Physical Game",
fileless: dict[str, Any] | None = None,
) -> Rom:
kind = fileless or {"is_physical": True, "fs_path": ".physical"}
return make_rom(
platform,
name,
fs_extension="",
fs_path=f"{platform.slug}/roms/.physical",
fs_size_bytes=0,
is_physical=True,
**(kind | {"fs_path": f"{platform.slug}/roms/{kind['fs_path']}"}),
)
def test_mark_missing_roms_skips_physical(rom: Rom, platform: Platform):
physical = _add_physical_rom(platform)
@FILELESS_KINDS
def test_mark_missing_roms_skips_physical(
rom: Rom, platform: Platform, fileless: dict[str, Any]
):
physical = _add_physical_rom(platform, fileless=fileless)
# An empty keep-list would normally flag every rom on the platform as missing.
still_missing = db_rom_handler.mark_missing_roms(platform.id, [])
@@ -70,8 +88,11 @@ def test_mark_missing_roms_skips_physical(rom: Rom, platform: Platform):
assert refreshed.missing_from_fs is False
def test_get_roms_scalar_missing_excludes_physical(platform: Platform):
physical = _add_physical_rom(platform)
@FILELESS_KINDS
def test_get_roms_scalar_missing_excludes_physical(
platform: Platform, fileless: dict[str, Any]
):
physical = _add_physical_rom(platform, fileless=fileless)
# Even if a physical rom is erroneously flagged, it must not be returned as
# missing (the cleanup task hard-deletes whatever this query returns).
db_rom_handler.update_rom(physical.id, {"missing_from_fs": True})
@@ -1313,3 +1334,33 @@ def test_get_rom_filters_includes_tags(rom: Rom, platform: Platform):
filters = db_rom_handler.get_rom_filters()
assert filters["tags"] == ["Beta", "Demo", "Proto"]
def test_get_users_filters_by_a_linked_steam_account(
admin_user: User, viewer_user: User
):
db_user_handler.update_user(admin_user.id, {"steam_id": "76561197960287930"})
linked = db_user_handler.get_users(has_steam_id=True)
unlinked = db_user_handler.get_users(has_steam_id=False)
assert [user.id for user in linked] == [admin_user.id]
assert viewer_user.id in {user.id for user in unlinked}
assert admin_user.id not in {user.id for user in unlinked}
@FILELESS_KINDS
def test_has_file_on_disk_filters_drop_roms_without_a_file(
rom: Rom, platform: Platform, fileless: dict[str, Any]
):
without_file = _add_physical_rom(platform, fileless=fileless)
ids = {
r.id
for r in db_rom_handler.get_roms_scalar(
platform_ids=[platform.id], **HAS_FILE_ON_DISK_FILTERS
)
}
assert rom.id in ids
assert without_file.id not in ids

View File

@@ -0,0 +1,276 @@
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from tests.factories import make_platform, make_rom
from adapters.services.steam_types import SteamOwnedGame
from adapters.services.steam_web_api import SteamWebAPIError
from handler.database import (
db_platform_handler,
db_rom_handler,
db_steam_library_handler,
db_user_handler,
)
from handler.steam_library_handler import (
STEAM_FS_SUBDIR,
SteamLibraryError,
parse_steam_profile,
resolve_steam_profile,
steam_library_platform,
steam_web_api,
sync_steam_library,
)
from models.platform import Platform
from models.rom import RomStorefront
from models.user import User
STEAM_ID = "76561197960287930"
@pytest.mark.parametrize(
"profile, expected",
[
(STEAM_ID, (STEAM_ID, None)),
(f" {STEAM_ID} ", (STEAM_ID, None)),
(f"https://steamcommunity.com/profiles/{STEAM_ID}/", (STEAM_ID, None)),
(f"steamcommunity.com/profiles/{STEAM_ID}", (STEAM_ID, None)),
("https://steamcommunity.com/id/gabelogannewell/", (None, "gabelogannewell")),
("https://STEAMCOMMUNITY.com/id/gabe?l=english", (None, "gabe")),
("gabelogannewell", (None, "gabelogannewell")),
],
)
def test_parses_ids_links_and_custom_names(
profile: str, expected: tuple[str | None, str | None]
):
assert parse_steam_profile(profile) == expected
@pytest.mark.parametrize(
"profile",
[
"",
"not a profile!",
"https://example.com/id/gabe",
"https://steamcommunity.com/profiles/gabe",
],
)
def test_rejects_anything_else(profile: str):
with pytest.raises(SteamLibraryError):
parse_steam_profile(profile)
@pytest.fixture
def steam_api():
api = MagicMock()
api.resolve_vanity_url = AsyncMock(return_value=STEAM_ID)
api.get_player_summary = AsyncMock(
return_value={"steamid": STEAM_ID, "personaname": "Gabe"}
)
api.get_owned_games = AsyncMock(return_value=[])
with patch("handler.steam_library_handler.steam_web_api", return_value=api):
yield api
async def test_resolves_a_custom_name_to_its_account(steam_api: MagicMock):
summary = await resolve_steam_profile("gabe")
assert summary["steamid"] == STEAM_ID
steam_api.resolve_vanity_url.assert_awaited_once_with("gabe")
steam_api.get_player_summary.assert_awaited_once_with(STEAM_ID)
async def test_an_unused_custom_name_is_an_error(steam_api: MagicMock):
steam_api.resolve_vanity_url.return_value = None
with pytest.raises(SteamLibraryError, match="custom URL 'gabe'"):
await resolve_steam_profile("gabe")
async def test_an_unknown_id_is_an_error(steam_api: MagicMock):
steam_api.get_player_summary.return_value = None
with pytest.raises(SteamLibraryError, match=STEAM_ID):
await resolve_steam_profile(STEAM_ID)
async def test_a_steam_failure_is_reported_as_a_library_error(steam_api: MagicMock):
steam_api.get_player_summary.side_effect = SteamWebAPIError("Steam rejected it")
with pytest.raises(SteamLibraryError, match="Steam rejected it"):
await resolve_steam_profile(STEAM_ID)
@patch("handler.steam_library_handler.STEAM_API_KEY", None)
def test_needs_an_api_key():
with pytest.raises(SteamLibraryError, match="STEAM_API_KEY"):
steam_web_api()
@pytest.fixture
def steam_user(admin_user: User) -> User:
db_user_handler.update_user(admin_user.id, {"steam_id": STEAM_ID})
user = db_user_handler.get_user(admin_user.id)
assert user is not None
return user
@pytest.fixture
def win() -> Platform:
return make_platform("win")
def _game(
app_id: int, name: str, playtime: int = 0, last_played: int = 0
) -> SteamOwnedGame:
return {
"appid": app_id,
"name": name,
"playtime_forever": playtime,
"rtime_last_played": last_played,
}
async def test_creates_store_only_roms_for_games_not_in_the_library(
steam_api: MagicMock, steam_user: User, win: Platform
):
steam_api.get_owned_games.return_value = [
_game(220, "Half-Life 2", playtime=90, last_played=1_700_000_000)
]
result = await sync_steam_library(steam_user)
assert (result.owned, result.linked, result.created, result.removed) == (1, 0, 1, 0)
[entry] = db_steam_library_handler.get_entries(steam_user.id)
rom = db_rom_handler.get_rom(entry.rom_id)
assert rom is not None
assert rom.platform_id == win.id
assert rom.name == "Half-Life 2"
assert rom.steam_id == 220
assert rom.storefront == RomStorefront.STEAM
assert rom.fs_name == "Half-Life 2 (steam-220)"
assert rom.fs_path.endswith(f"/{STEAM_FS_SUBDIR}")
assert not rom.has_file_on_disk
assert entry.playtime_minutes == 90
assert entry.last_played_at is not None
assert entry.last_played_at.replace(tzinfo=None) == datetime.fromtimestamp(
1_700_000_000, timezone.utc
).replace(tzinfo=None)
assert result.unmatched_rom_ids == [rom.id]
async def test_links_a_rom_already_in_the_library(
steam_api: MagicMock, steam_user: User, win: Platform
):
owned_copy = make_rom(win, "Portal", steam_id=400)
steam_api.get_owned_games.return_value = [_game(400, "Portal")]
result = await sync_steam_library(steam_user)
assert (result.linked, result.created) == (1, 0)
[entry] = db_steam_library_handler.get_entries(steam_user.id)
assert entry.rom_id == owned_copy.id
assert entry.last_played_at is None
assert result.unmatched_rom_ids == []
async def test_prefers_a_rom_with_a_file_over_a_store_only_one(
steam_api: MagicMock, steam_user: User, win: Platform
):
make_rom(
win,
"Portal 2",
fs_stem="Portal 2 (steam-620)",
steam_id=620,
storefront="steam",
)
with_file = make_rom(make_platform("linux"), "Portal 2", steam_id=620)
steam_api.get_owned_games.return_value = [_game(620, "Portal 2")]
await sync_steam_library(steam_user)
[entry] = db_steam_library_handler.get_entries(steam_user.id)
assert entry.rom_id == with_file.id
async def test_a_second_sync_reuses_the_store_only_rom(
steam_api: MagicMock, steam_user: User, win: Platform
):
steam_api.get_owned_games.return_value = [_game(220, "Half-Life 2")]
await sync_steam_library(steam_user)
result = await sync_steam_library(steam_user)
assert (result.linked, result.created) == (1, 0)
assert len(db_steam_library_handler.get_entries(steam_user.id)) == 1
async def test_forgets_games_no_longer_owned(
steam_api: MagicMock, steam_user: User, win: Platform
):
steam_api.get_owned_games.return_value = [
_game(220, "Half-Life 2"),
_game(400, "Portal"),
]
await sync_steam_library(steam_user)
steam_api.get_owned_games.return_value = [_game(400, "Portal", playtime=30)]
result = await sync_steam_library(steam_user)
assert result.removed == 1
[entry] = db_steam_library_handler.get_entries(steam_user.id)
assert (entry.steam_app_id, entry.playtime_minutes) == (400, 30)
async def test_a_matched_store_only_rom_is_not_scanned_again(
steam_api: MagicMock, steam_user: User, win: Platform
):
steam_api.get_owned_games.return_value = [_game(220, "Half-Life 2")]
[rom_id] = (await sync_steam_library(steam_user)).unmatched_rom_ids
db_rom_handler.update_rom(rom_id, {"url_cover": "https://example.com/cover.jpg"})
result = await sync_steam_library(steam_user)
assert result.unmatched_rom_ids == []
async def test_a_private_library_is_an_error(
steam_api: MagicMock, steam_user: User, win: Platform
):
steam_api.get_owned_games.return_value = None
with pytest.raises(SteamLibraryError, match="Game details"):
await sync_steam_library(steam_user)
async def test_an_unlinked_user_is_an_error(admin_user: User):
with pytest.raises(SteamLibraryError, match="no linked Steam account"):
await sync_steam_library(admin_user)
async def test_uses_the_existing_win_platform(win: Platform):
platform = await steam_library_platform()
assert platform.id == win.id
async def test_creates_the_win_platform_and_its_folder():
with patch(
"handler.steam_library_handler.fs_platform_handler.add_platform",
new_callable=AsyncMock,
) as add_folder:
platform = await steam_library_platform()
add_folder.assert_awaited_once_with(fs_slug="win")
assert (platform.slug, platform.fs_slug) == ("win", "win")
assert db_platform_handler.get_platform_by_slug("win") is not None
async def test_a_folder_that_cannot_be_created_is_an_error():
with patch(
"handler.steam_library_handler.fs_platform_handler.add_platform",
new_callable=AsyncMock,
side_effect=PermissionError("read-only"),
):
with pytest.raises(SteamLibraryError, match="platform folder"):
await steam_library_platform()

View File

@@ -11,6 +11,7 @@ from models.rom import (
LookupHashes,
Rom,
RomFile,
RomStorefront,
compute_full_path_hash,
compute_search_titles,
)
@@ -53,6 +54,11 @@ def test_has_file_on_disk_covers_both_file_less_cases(rom: Rom):
rom.is_physical = True
assert rom.has_file_on_disk is False
rom.is_physical = False
rom.storefront = RomStorefront.STEAM
assert rom.has_file_on_disk is False
assert rom.never_has_file is True
def test_rom_with_libretro_match_is_identified(rom: Rom):
rom.libretro_id = "abc123"

View File

@@ -0,0 +1,123 @@
from unittest.mock import AsyncMock, patch
import pytest
from endpoints.sockets.scan import ScanPayload
from exceptions.socket_exceptions import NoScanWorkerException
from handler.database import db_user_handler
from handler.steam_library_handler import SteamLibraryError, SteamSyncResult
from models.user import User
from tasks.scheduled.sync_steam_libraries import SyncSteamLibrariesTask
MODULE = "tasks.scheduled.sync_steam_libraries"
@pytest.fixture
def task() -> SyncSteamLibrariesTask:
return SyncSteamLibrariesTask()
@pytest.fixture(autouse=True)
def api_key():
with patch(f"{MODULE}.STEAM_API_KEY", "key"):
yield
@pytest.fixture
def linked_user(admin_user: User) -> User:
db_user_handler.update_user(admin_user.id, {"steam_id": "76561197960287930"})
return admin_user
@pytest.fixture
def queue_scan():
with patch(f"{MODULE}.queue_scan", new_callable=AsyncMock) as queue:
yield queue
async def test_syncs_every_linked_user(
task: SyncSteamLibrariesTask, linked_user: User, viewer_user: User, queue_scan
):
with patch(
f"{MODULE}.sync_steam_library",
new_callable=AsyncMock,
return_value=SteamSyncResult(owned=1, created=1, unmatched_rom_ids=[7]),
) as sync:
stats = await task.run()
[call] = sync.await_args_list
assert call.args[0].id == linked_user.id
assert stats == {"processed": 1, "total": 1}
queue_scan.assert_awaited_once_with(
ScanPayload(roms_ids=[7]), started_by_user_id=None
)
async def test_one_users_failure_does_not_stop_the_rest(
task: SyncSteamLibrariesTask, linked_user: User, viewer_user: User, queue_scan
):
db_user_handler.update_user(viewer_user.id, {"steam_id": "76561197960287931"})
with patch(
f"{MODULE}.sync_steam_library",
new_callable=AsyncMock,
side_effect=[SteamLibraryError("private"), SteamSyncResult()],
) as sync:
stats = await task.run()
assert sync.await_count == 2
assert stats == {"processed": 2, "total": 2}
queue_scan.assert_not_awaited()
async def test_a_requested_sync_reports_its_failure(
task: SyncSteamLibrariesTask, linked_user: User, queue_scan
):
with patch(
f"{MODULE}.sync_steam_library",
new_callable=AsyncMock,
side_effect=SteamLibraryError("private"),
):
with pytest.raises(SteamLibraryError, match="private"):
await task.run(user_id=linked_user.id)
async def test_a_requested_sync_scans_for_that_user(
task: SyncSteamLibrariesTask, linked_user: User, queue_scan
):
with patch(
f"{MODULE}.sync_steam_library",
new_callable=AsyncMock,
return_value=SteamSyncResult(unmatched_rom_ids=[3, 1]),
):
await task.run(user_id=linked_user.id)
queue_scan.assert_awaited_once_with(
ScanPayload(roms_ids=[1, 3]), started_by_user_id=linked_user.id
)
async def test_no_scan_worker_leaves_the_games_for_the_next_sync(
task: SyncSteamLibrariesTask, linked_user: User, queue_scan
):
queue_scan.side_effect = NoScanWorkerException("none")
with patch(
f"{MODULE}.sync_steam_library",
new_callable=AsyncMock,
return_value=SteamSyncResult(unmatched_rom_ids=[1]),
):
stats = await task.run(user_id=linked_user.id)
assert stats == {"processed": 1, "total": 1}
async def test_does_nothing_without_an_api_key(
task: SyncSteamLibrariesTask, linked_user: User
):
with (
patch(f"{MODULE}.STEAM_API_KEY", None),
patch(f"{MODULE}.sync_steam_library", new_callable=AsyncMock) as sync,
):
stats = await task.run()
sync.assert_not_awaited()
assert stats == {"processed": 0, "total": 0}

View File

@@ -258,6 +258,9 @@ def _replay(connection: sa.Connection, filename: str) -> None:
("0148_rom_age_limits.py", "permission_groups"),
("0148_rom_age_limits.py", "users"),
("0151_state_content_hash.py", "states"),
("0155_steam_library.py", "roms"),
("0155_steam_library.py", "users"),
("0155_steam_library.py", "steam_library_entries"),
],
)
def test_a_revision_replayed_over_the_migrated_schema_is_a_no_op(

View File

@@ -505,6 +505,7 @@ def drop_save_target_layout_type(conn: sa.Connection) -> None:
PLAIN_COLUMNS: list[sa.Column[Any]] = [
sa.Column("is_physical", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("upc", sa.String(length=64)),
sa.Column("storefront", sa.String(length=32)),
sa.Column("locked_fields", CustomJSON()),
sa.Column("demozoo_id", sa.Integer()),
sa.Column("pouet_id", sa.Integer()),

View File

@@ -314,6 +314,7 @@ backend/
│ ├── scheduled/ # Cron-scheduled tasks
│ │ ├── scan_library.py # Nightly library rescan
│ │ ├── sync_retroachievements_progress.py # Pull RA user progress
│ │ ├── sync_steam_libraries.py # Import linked Steam libraries
│ │ ├── update_switch_titledb.py # Refresh Switch TitleDB
│ │ ├── update_launchbox_metadata.py # Refresh LaunchBox data
│ │ ├── convert_images_to_webp.py # Artwork WebP conversion
@@ -654,6 +655,22 @@ Audio metadata for a `SOUNDTRACK` rom_file (1:1), indexed for the music API. Wri
---
#### Steam Library
**Table:** `steam_library_entries` (games a user owns on Steam)
| Column | Type | Notes |
| -------------------------- | ------------ | ----------------------------- |
| `user_id` + `steam_app_id` | FK + Integer | Unique constraint |
| `rom_id` | FK | The rom standing for the game |
| `playtime_minutes` | Integer | Steam's total playtime |
| `last_played_at` | Timestamp | Null when never played |
A game not already in the library gets a store-only rom on `win`: `storefront`
is `steam`, and it has no file, like a physical game.
---
#### ROM User Data
**Table:** `rom_user` (per-user, per-ROM tracking)
@@ -870,6 +887,9 @@ A reset link is emailed when SMTP is set up, the user has an address and `ROMM_B
| PUT | `/{id}` | ME_WRITE | Update user |
| DELETE | `/{id}` | USERS_WRITE | Delete user |
| POST | `/{id}/ra/refresh` | ME_WRITE | Refresh RetroAchievements data |
| PUT | `/{id}/steam` | ME_WRITE | Link a Steam account |
| DELETE | `/{id}/steam` | ME_WRITE | Unlink a Steam account |
| POST | `/{id}/steam/sync` | ME_WRITE | Queue a Steam library sync |
### 6.3 Client Tokens (`/api/client-tokens`)
@@ -1726,6 +1746,7 @@ Toggled via environment variables:
| `update_launchbox_metadata` | `ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA` | `0 4 * * *` | Refresh LaunchBox data |
| `convert_images_to_webp` | `ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP` | `0 4 * * *` | Image optimization |
| `sync_retroachievements_progress` | `ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC` | `0 4 * * *` | Sync RA user progress |
| `sync_steam_libraries` | `ENABLE_SCHEDULED_STEAM_LIBRARY_SYNC` | `30 4 * * *` | Import linked Steam libraries |
| `cleanup_orphaned_resources` | `ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES` | `0 5 * * *` | Remove unused artwork |
| `cleanup_netplay` | `ENABLE_SCHEDULED_CLEANUP_NETPLAY` (default on) | `*/30 * * * *` | Clean empty rooms |
| `cleanup_upload_tmp` | `ENABLE_SCHEDULED_CLEANUP_UPLOAD_TMP` (default on) | `0 * * * *` | Drop stale uploads |
@@ -1964,6 +1985,7 @@ Falls back to `FakeRedis` in test mode.
| `FLASHPOINT_API_ENABLED` | `false` | Flashpoint archive |
| `HLTB_API_ENABLED` | `false` | HowLongToBeat |
| `STEAM_API_ENABLED` | `false` | Steam storefront |
| `STEAM_API_KEY` | - | Steam library import |
| `DISABLE_EMULATOR_JS` | `false` | Hide EmulatorJS player |
| `DISABLE_RUFFLE_RS` | `false` | Hide Ruffle Flash player |
| `DISABLE_JSDOS` | `false` | Hide js-dos player |

View File

@@ -87,6 +87,7 @@ DEMOZOO_API_ENABLED=false # Enable Demozoo (filename tags (demozoo-N) / paste I
POUET_API_ENABLED=false # Enable Pouët (filename tags (pouet-N) / paste ID; no API key)
CSDB_API_ENABLED=false # Enable CSDb (filename tags (csdb-N) / paste ID / Demozoo CsdbRelease; no API key)
STEAM_API_ENABLED=false # Enable Steam API integration (PC platforms only)
STEAM_API_KEY= # Steam Web API key, for importing users' Steam libraries
TGDB_API_ENABLED=false # Enable TheGamesDB API integration
# Only use when building your own image or running from source
# SCREENSCRAPER_DEV_ID=
@@ -128,6 +129,8 @@ ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES=false # Enable scheduled cleanup of
SCHEDULED_CLEANUP_ORPHANED_RESOURCES_CRON=0 5 * * * # Cron expression for scheduled orphaned resource cleanup
ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC=false # Enable scheduled RetroAchievements progress sync
SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC_CRON=0 4 * * * # Cron expression for scheduled RetroAchievements sync
ENABLE_SCHEDULED_STEAM_LIBRARY_SYNC=false # Enable scheduled sync of linked Steam libraries (needs STEAM_API_KEY)
SCHEDULED_STEAM_LIBRARY_SYNC_CRON=30 4 * * * # Cron expression for scheduled Steam library sync
ENABLE_SCHEDULED_BUILD_RECOMMENDATIONS=true # Enable the scheduled rebuild of the recommendations index
SCHEDULED_BUILD_RECOMMENDATIONS_CRON=30 5 * * * # Cron expression for the recommendations index rebuild

View File

@@ -35,6 +35,7 @@ export type { Body_delete_memory_cards_api_memory_cards_delete_post } from './mo
export type { Body_delete_roms_api_roms_delete_post } from './models/Body_delete_roms_api_roms_delete_post';
export type { Body_delete_saves_api_saves_delete_post } from './models/Body_delete_saves_api_saves_delete_post';
export type { Body_delete_states_api_states_delete_post } from './models/Body_delete_states_api_states_delete_post';
export type { Body_link_steam_account_api_users__id__steam_put } from './models/Body_link_steam_account_api_users__id__steam_put';
export type { Body_patch_rom_api_roms__id__patch_post } from './models/Body_patch_rom_api_roms__id__patch_post';
export type { Body_refresh_retro_achievements_api_users__id__ra_refresh_post } from './models/Body_refresh_retro_achievements_api_users__id__ra_refresh_post';
export type { Body_remove_hidden_entity_api_permissions_hidden_delete } from './models/Body_remove_hidden_entity_api_permissions_hidden_delete';

View File

@@ -0,0 +1,11 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_link_steam_account_api_users__id__steam_put = {
/**
* SteamID64, Steam profile link, or custom profile URL name.
*/
profile: string;
};

View File

@@ -109,6 +109,7 @@ export type DetailedRomSchema = {
updated_at: string;
missing_from_fs: boolean;
is_physical: boolean;
storefront: (string | null);
has_file_on_disk: boolean;
upc: (string | null);
has_notes: boolean;

View File

@@ -20,6 +20,7 @@ export type MetadataSourcesDict = {
POUET_API_ENABLED: boolean;
CSDB_API_ENABLED: boolean;
STEAM_API_ENABLED: boolean;
STEAM_LIBRARY_ENABLED: boolean;
LIBRETRO_API_ENABLED: boolean;
};

View File

@@ -101,6 +101,7 @@ export type SimpleRomSchema = {
updated_at: string;
missing_from_fs: boolean;
is_physical: boolean;
storefront: (string | null);
has_file_on_disk: boolean;
upc: (string | null);
has_notes: boolean;

View File

@@ -19,6 +19,8 @@ export type UserSchema = {
last_active: (string | null);
ra_username?: (string | null);
ra_progression?: (RAProgression | null);
steam_id?: (string | null);
steam_persona_name?: (string | null);
ui_settings?: (Record<string, any> | null);
current_device_id?: (string | null);
created_at: string;

View File

@@ -116,6 +116,7 @@ export const ROM_DEFAULTS: SimpleRom = {
updated_at: "2026-01-02T00:00:00Z",
missing_from_fs: false,
is_physical: false,
storefront: null,
has_file_on_disk: true,
upc: null,
has_notes: false,

View File

@@ -165,6 +165,7 @@ const syntheticRom = computed<SimpleRom>(() => ({
updated_at: "",
missing_from_fs: false,
is_physical: false,
storefront: null,
has_file_on_disk: false,
upc: null,
has_notes: false,

View File

@@ -36,6 +36,7 @@ const defaultHeartbeat: Heartbeat = {
POUET_API_ENABLED: false,
CSDB_API_ENABLED: false,
STEAM_API_ENABLED: false,
STEAM_LIBRARY_ENABLED: false,
LIBRETRO_API_ENABLED: false,
},
FILESYSTEM: {

View File

@@ -156,6 +156,7 @@ export function romFixture(overrides: Partial<SimpleRom> = {}): SimpleRom {
updated_at: WRITTEN_AT,
missing_from_fs: false,
is_physical: false,
storefront: null,
has_file_on_disk: false,
upc: null,
has_notes: false,