diff --git a/.claude/skills/backend-development/SKILL.md b/.claude/skills/backend-development/SKILL.md index 126fbf2d0..cc6bbb8d7 100644 --- a/.claude/skills/backend-development/SKILL.md +++ b/.claude/skills/backend-development/SKILL.md @@ -101,5 +101,6 @@ 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 / type-check run through Trunk** (ruff, black, isort, mypy, bandit): `trunk fmt && trunk check`. CI enforces Trunk on every PR. Never bypass with `--no-verify`. +- **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. - New/changed logic needs a test; new endpoints need endpoint tests. diff --git a/.claude/skills/frontend-v2-components/SKILL.md b/.claude/skills/frontend-v2-components/SKILL.md index 6a971e710..c1e5acd4c 100644 --- a/.claude/skills/frontend-v2-components/SKILL.md +++ b/.claude/skills/frontend-v2-components/SKILL.md @@ -107,7 +107,7 @@ import { useCan } from "@/v2/composables/useCan"; - Every primitive ships at least one story with controls and at least one variant per theme. - A new interactive primitive that warrants gamepad navigation ships a `play()` interaction. - Modified primitive: existing story must still render and its interactions still pass. -- `npm run test` runs Vitest **and** every `/lib` story's `play()` via `composeStories`. Don't duplicate coverage between Vitest (pure logic) and Storybook `play()` (components). +- `npm run test` runs Vitest **and** every `/lib` and `components/shared` story's `play()` via `composeStories`. Don't duplicate coverage between Vitest (pure logic) and Storybook `play()` (components). - **Responsive QA:** `.storybook/rommViewports.ts` + viewport globals in `preview.ts`; see `frontend-v2-input` for `data-bp` vs iframe width. --- diff --git a/.claude/skills/review-polish/SKILL.md b/.claude/skills/review-polish/SKILL.md index 1044f28b9..f04bd6272 100644 --- a/.claude/skills/review-polish/SKILL.md +++ b/.claude/skills/review-polish/SKILL.md @@ -1,6 +1,6 @@ --- name: review-polish -description: The before-review and before-handoff pass for RomM, covering both stacks. First shapes the code the checks can't see — comment and docstring discipline (the single most-corrected thing in this repo), duplicated constants/types/getters, imprecise names, loose typing in tests. Then runs the verification gate that keeps CI green — frontend (typecheck/lint/test/build/i18n/tokens), backend (pytest/alembic/trunk), the OpenAPI regen step, and (for UI) manual browser/theme/input/Storybook checks. Ends with what the PR description owes a reviewer: screenshots of a UI change, a mermaid diagram of an architectural one. Use after the code works, right before committing, opening a PR, or telling the user a change is done. +description: "The before-review and before-handoff pass for RomM, covering both stacks. First shapes the code the checks can't see: comment and docstring discipline (the single most-corrected thing in this repo), duplicated constants/types/getters, imprecise names, loose typing in tests. Then runs the verification gate that keeps CI green: frontend (typecheck/lint/test/build/i18n/tokens), backend (pytest/alembic/trunk), the OpenAPI regen step, and (for UI) manual browser/theme/input/Storybook checks. Ends with what the PR description owes a reviewer: screenshots of a UI change, a mermaid diagram of an architectural one. Use after the code works, right before committing, opening a PR, or telling the user a change is done." --- # RomM: Review Polish & Verification @@ -106,7 +106,7 @@ short a word. ## D. Tests: strict typing is part of the test -Trunk runs mypy over `backend/tests/`, and `vue-tsc` covers frontend tests. Both +mypy covers `backend/tests/`, and `vue-tsc` covers frontend tests. Both catch these, but only after the contributor has handed the PR over. - **Narrow optionals before attribute access.** `mock.await_args` is @@ -145,7 +145,7 @@ Run from `frontend/`: 1. `npm run typecheck`: zero errors (`vue-tsc --noEmit`). 2. `npm run typecheck:scripts`: zero errors (`tsc -p tsconfig.node.json`, covers `scripts/`). 3. `npm run lint` _(if present)_ / ESLint clean. Trunk also runs ESLint + Prettier in CI. -4. `npm run test`: zero failures (Vitest + happy-dom; runs unit tests **and** every `/lib` story's `play()` via `composeStories`). +4. `npm run test`: zero failures (Vitest + happy-dom; runs unit tests **and** every `/lib` and `components/shared` story's `play()` via `composeStories`). 5. `npm run build`: zero failures (CI sanity check). **If you touched the backend API:** start the backend, run `npm run generate`, then re-`typecheck`. @@ -181,13 +181,14 @@ With `uiVersion = "v2"`: Run from `backend/`: 1. `uv run pytest ` — zero failures on the tests affected by the diff. Never run the whole suite locally (20+ minutes); see [AGENTS.md](../../../AGENTS.md) for how to pick targets. CI runs it in full. -2. `trunk fmt && trunk check` — ruff/black/isort/mypy/bandit clean (CI enforces Trunk). -3. **If you added a migration:** `uv run alembic upgrade head` then `uv run alembic downgrade -1` to prove both directions; it must work on MariaDB **and** PostgreSQL (CI runs both). -4. **If a response schema or route signature changed:** regenerate frontend types (`npm run generate`) and typecheck the frontend. +2. `trunk fmt && trunk check`: ruff/black/isort/bandit clean (CI enforces Trunk). +3. `uv run mypy --config-file ../.trunk/configs/mypy.ini .`: zero errors across the backend (CI enforces it). +4. **If you added a migration:** `uv run alembic upgrade head` then `uv run alembic downgrade -1` to prove both directions; it must work on MariaDB **and** PostgreSQL (CI runs both). +5. **If a response schema or route signature changed:** regenerate frontend types (`npm run generate`) and typecheck the frontend. ### CI gates this mirrors -`typecheck.yml` (vue-tsc + lockfile lint), `frontend.yml` (vitest + build), `i18n.yml` (locale check), `pytest.yml` (pytest on MariaDB + PostgreSQL), `migrations.yml` (alembic on both DBs), `trunk-check.yml` (Trunk across the repo). Green locally → green in CI. +`typecheck.yml` (vue-tsc + lockfile lint), `frontend.yml` (vitest + build), `i18n.yml` (locale check), `pytest.yml` (pytest on MariaDB + PostgreSQL), `migrations.yml` (alembic on both DBs), `mypy.yml` (mypy across the backend), `trunk-check.yml` (Trunk across the repo). Green locally → green in CI. ### Don't diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5c7cd4a3c..b8d99d12f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,16 +6,37 @@ on: # - "[0-9]+.[0-9]+.[0-9]+*" release: types: [published] + # Rolling `nightly` image of master. + schedule: + - cron: "17 4 * * *" permissions: contents: read -# `build` pushes digests here and `merge` tags them from here; the two must agree. env: + CHANNEL: ${{ github.event_name == 'schedule' && 'nightly' || 'release' }} + # `build` pushes digests here and `merge` tags them from here; the two must agree. DIGEST_IMAGE: ghcr.io/${{ github.repository_owner }}/romm + IMAGES: | + name=rommapp/romm + name=ghcr.io/rommapp/romm + # `build` and `merge` must derive the same tag set. + TAGS: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=semver,pattern={{major}} + type=schedule,pattern=nightly + # Labels on each platform image, annotations on the index. metadata-action fills in + # the version itself (with `-slim`) and would render a `{{version}}` here as empty. + OCI_METADATA: | + org.opencontainers.image.title=rommapp/romm + org.opencontainers.image.description=RomM (ROM Manager) allows you to scan, enrich, and browse your game collection with a clean and responsive interface. With support for multiple platforms, various naming schemes and custom tags, RomM is a must-have for anyone who plays on emulators. + org.opencontainers.image.licenses=AGPL-3.0-only jobs: validate-tag-semver: + # Forks have no registry credentials, so their nightly would fail every day. + if: github.event_name != 'schedule' || github.repository == 'rommapp/romm' runs-on: ubuntu-latest permissions: contents: read @@ -27,7 +48,7 @@ jobs: env: TAG: ${{ github.event.release.tag_name }} run: | - if [[ "$TAG" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-alpha\.[0-9]+|-beta\.[0-9]+|-rc\.[0-9]+)?$ ]]; then + if [[ "$CHANNEL" == "nightly" || "$TAG" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-alpha\.[0-9]+|-beta\.[0-9]+|-rc\.[0-9]+)?$ ]]; then echo "valid=true" >>"$GITHUB_OUTPUT" else echo "valid=false" >>"$GITHUB_OUTPUT" @@ -80,43 +101,30 @@ jobs: id: meta-slim uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 with: - images: | - name=rommapp/romm - name=ghcr.io/rommapp/romm + images: ${{ env.IMAGES }} flavor: | latest=auto suffix=-slim,onlatest=true - tags: | - type=semver,pattern={{version}} - type=semver,pattern={{major}}.{{minor}} - type=semver,pattern={{major}} - labels: | - org.opencontainers.image.version={{version}}-slim - org.opencontainers.image.title="rommapp/romm" - org.opencontainers.image.description="RomM (ROM Manager) allows you to scan, enrich, and browse your game collection with a clean and responsive interface. With support for multiple platforms, various naming schemes and custom tags, RomM is a must-have for anyone who plays on emulators." - org.opencontainers.image.licenses="AGPLv3" + tags: ${{ env.TAGS }} + labels: ${{ env.OCI_METADATA }} - name: Generate Docker metadata (full) id: meta uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 with: - images: | - name=rommapp/romm - name=ghcr.io/rommapp/romm - tags: | - type=semver,pattern={{version}} - type=semver,pattern={{major}}.{{minor}} - type=semver,pattern={{major}} - labels: | - org.opencontainers.image.version={{version}} - org.opencontainers.image.title="rommapp/romm" - org.opencontainers.image.description="RomM (ROM Manager) allows you to scan, enrich, and browse your game collection with a clean and responsive interface. With support for multiple platforms, various naming schemes and custom tags, RomM is a must-have for anyone who plays on emulators." - org.opencontainers.image.licenses="AGPLv3" + images: ${{ env.IMAGES }} + tags: ${{ env.TAGS }} + labels: ${{ env.OCI_METADATA }} + # Nightly builds carry the short commit so each one is identifiable and busts + # version-keyed caches. - name: Set version env: VERSION: ${{ steps.meta.outputs.version }} run: | + if [[ "$CHANNEL" == "nightly" ]]; then + VERSION="${VERSION}-${GITHUB_SHA::7}" + fi sed -i "s//$VERSION/" backend/__version__.py - name: Build and push slim image by digest @@ -128,6 +136,7 @@ jobs: platforms: ${{ matrix.platform }} labels: ${{ steps.meta-slim.outputs.labels }} target: slim-image + sbom: true outputs: type=image,name=${{ env.DIGEST_IMAGE }},push-by-digest=true,name-canonical=true,push=true # Both stages run `apk upgrade` off a fixed base digest, so nothing in # them changes between releases and the cache would serve the package @@ -135,7 +144,9 @@ jobs: no-cache-filters: python-runtime,production-stage # Deliberately not seeded from the preview cache: those layers are # built from PR head content and must not reach a release image. - cache-from: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }} + cache-from: | + type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }} + ${{ env.CHANNEL == 'nightly' && format('type=registry,ref={0}:nightly-{1}', env.CACHE_IMAGE, matrix.arch) || '' }} build-args: | SCREENSCRAPER_DEV_ID=${{ secrets.SCREENSCRAPER_DEV_ID }} SCREENSCRAPER_DEV_PASSWORD=${{ secrets.SCREENSCRAPER_DEV_PASSWORD }} @@ -151,10 +162,15 @@ jobs: platforms: ${{ matrix.platform }} labels: ${{ steps.meta.outputs.labels }} target: full-image + sbom: true outputs: type=image,name=${{ env.DIGEST_IMAGE }},push-by-digest=true,name-canonical=true,push=true no-cache-filters: python-runtime,production-stage - cache-from: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }} - cache-to: type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }},mode=max + cache-from: | + type=registry,ref=${{ env.CACHE_IMAGE }}:release-${{ matrix.arch }} + ${{ env.CHANNEL == 'nightly' && format('type=registry,ref={0}:nightly-{1}', env.CACHE_IMAGE, matrix.arch) || '' }} + # Nightly reads the release cache but writes its own, so master layers + # never seed a release image. + cache-to: type=registry,ref=${{ env.CACHE_IMAGE }}:${{ env.CHANNEL }}-${{ matrix.arch }},mode=max build-args: | SCREENSCRAPER_DEV_ID=${{ secrets.SCREENSCRAPER_DEV_ID }} SCREENSCRAPER_DEV_PASSWORD=${{ secrets.SCREENSCRAPER_DEV_PASSWORD }} @@ -187,6 +203,8 @@ jobs: merge: needs: build runs-on: ubuntu-latest + env: + DOCKER_METADATA_ANNOTATIONS_LEVELS: index permissions: contents: read packages: write @@ -225,28 +243,20 @@ jobs: id: meta-slim uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 with: - images: | - name=rommapp/romm - name=ghcr.io/rommapp/romm + images: ${{ env.IMAGES }} flavor: | latest=auto suffix=-slim,onlatest=true - tags: | - type=semver,pattern={{version}} - type=semver,pattern={{major}}.{{minor}} - type=semver,pattern={{major}} + tags: ${{ env.TAGS }} + annotations: ${{ env.OCI_METADATA }} - name: Generate Docker metadata (full) id: meta uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0 with: - images: | - name=rommapp/romm - name=ghcr.io/rommapp/romm - tags: | - type=semver,pattern={{version}} - type=semver,pattern={{major}}.{{minor}} - type=semver,pattern={{major}} + images: ${{ env.IMAGES }} + tags: ${{ env.TAGS }} + annotations: ${{ env.OCI_METADATA }} # Tags spanning both registries are fine here: `imagetools create` copies # the blobs over when a target sits in a different registry than the digests. @@ -263,6 +273,13 @@ jobs: tags+=(--tag "$tag") done < <(jq -r '.tags[]' <<<"$metadata") + # The labels only reach each platform's image config; registries + # read a multi-platform image's metadata from its index. + local annotations=() + while IFS= read -r annotation; do + annotations+=(--annotation "$annotation") + done < <(jq -r '.annotations[]' <<<"$metadata") + local sources=() local digest for digest in "$dir"/*; do @@ -277,7 +294,7 @@ jobs: return 1 fi - docker buildx imagetools create "${tags[@]}" "${sources[@]}" + docker buildx imagetools create "${tags[@]}" "${annotations[@]}" "${sources[@]}" } push_variant /tmp/digests/slim "$SLIM_METADATA" diff --git a/.github/workflows/mypy.yml b/.github/workflows/mypy.yml new file mode 100644 index 000000000..da4d4250e --- /dev/null +++ b/.github/workflows/mypy.yml @@ -0,0 +1,60 @@ +name: Run mypy + +on: + pull_request: + paths: + - "backend/**" + - ".github/scripts/**.py" + - "frontend/src/locales/*.py" + - ".github/workflows/mypy.yml" + - ".trunk/configs/mypy.ini" + - pyproject.toml + - uv.lock + - .python-version + push: + branches: + - "master" + paths: + - "backend/**" + - ".github/scripts/**.py" + - "frontend/src/locales/*.py" + - ".github/workflows/mypy.yml" + - ".trunk/configs/mypy.ini" + - pyproject.toml + - uv.lock + - .python-version + +permissions: + contents: read + +jobs: + mypy: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install mariadb connectors + run: | + sudo apt-get update + sudo apt-get install -y libmariadb3 libmariadb-dev + + - name: Install uv + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + + - name: Install python + run: | + uv python install + + - name: Install dependencies + run: | + uv sync --frozen --extra dev --extra test + + # The scripts import the app from backend/, as they add it to sys.path. + - name: Type check the backend and the scripts outside it + env: + MYPYPATH: backend + run: | + uv run mypy --config-file .trunk/configs/mypy.ini backend .github/scripts frontend/src/locales diff --git a/.gitignore b/.gitignore index 3fcadbc8d..e010c9e7e 100644 --- a/.gitignore +++ b/.gitignore @@ -97,3 +97,6 @@ frontend/test-results/ frontend/playwright-report/ frontend/blob-report/ frontend/.last-run.json + +# mypy +.mypy_cache diff --git a/.trunk/configs/mypy.ini b/.trunk/configs/mypy.ini index 1adf1be33..8974bf1d3 100644 --- a/.trunk/configs/mypy.ini +++ b/.trunk/configs/mypy.ini @@ -1,6 +1,9 @@ [mypy] check_untyped_defs = True +warn_unused_ignores = True +warn_redundant_casts = True disable_error_code = import-untyped +enable_error_code = ignore-without-code # INI configs take a regex here, not a TOML-style list. exclude = (?x)(^|/)alembic/ diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 001286a00..f547bea09 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -21,6 +21,8 @@ lint: - svgo - oxipng - pyright + # Trunk's venv lacks the project's packages; mypy.yml runs it against uv's. + - mypy enabled: - zizmor@1.30.1 - pinact@4.0.0 @@ -34,7 +36,6 @@ lint: - checkov@3.3.8 - git-diff-check - isort@8.0.1 - - mypy@2.3.0 - osv-scanner@2.3.3 - prettier@3.9.5: packages: @@ -57,12 +58,6 @@ lint: - backend/utils/rom_patcher/patcher.js # Intentionally malformed YAML, used as a test fixture - backend/tests/config/fixtures/config/malformed_config.yml - # Alembic env/migrations rely on runtime-injected globals (context, op) - # that mypy cannot resolve; already excluded in mypy.ini, but Trunk passes - # changed files explicitly, which bypasses that exclude. - - linters: [mypy] - paths: - - backend/alembic/** # The v1 UI is frozen and the freeze check blocks changes to these paths, # so ESLint findings in its templates cannot lead to fixes. Its TypeScript # stays covered, since that was already linted before .vue was. diff --git a/CLAUDE.md b/CLAUDE.md index 771b337a5..0bb0545c9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,20 +4,9 @@ RomM is a self-hosted ROM manager and player: scan a game library off disk, enri --- -## The stack at a glance - -| | Backend | Frontend | -| --------- | ------------------------------------------- | ----------------------------------------- | -| Path | `backend/` | `frontend/` | -| Language | Python 3.14+ | TypeScript 5.9 (Vue 3) | -| Framework | FastAPI, SQLAlchemy 2.0, Alembic | Vue 3 + Vite, Vuetify, Pinia, Vue Router | -| Infra | Redis + RQ (jobs/cache/sessions), Socket.IO | vue-i18n, Socket.IO client | -| DB | MariaDB (default), MySQL, PostgreSQL | - | -| Tooling | `uv`, pytest, Trunk (ruff/black/isort/mypy) | `npm`, vue-tsc, ESLint, Vitest, Storybook | - The frontend talks to the backend over `/api/*` (REST) and `/ws` (Socket.IO). TypeScript types are **generated** from the backend's OpenAPI schema into `frontend/src/__generated__/` - the backend is the single source of truth for API shapes. -### Deep-dive references +## Deep-dive references - **`docs/BACKEND_ARCHITECTURE.md`** - directory map, ER diagram, every endpoint, auth/scopes, tasks. - **`docs/FRONTEND_ARCHITECTURE.md`** - routing, stores, services, theming, build tooling. @@ -26,34 +15,15 @@ The frontend talks to the backend over `/api/*` (REST) and `/ws` (Socket.IO). Ty --- -## The frontend has two UIs - know which you're in +## Stack-specific guidance -- **v1 is frozen.** Everything under `frontend/src/views/`, `src/components/`, `src/console/`, `src/layouts/` is legacy and will be deleted wholesale in a final wave. **Do not refactor v1.** Only touch it for a critical bug, and when a v2 fork exists, mark the v1 export `@deprecated`. -- **v2 is the active rewrite** under `frontend/src/v2/`, gated by `user.ui_settings.uiVersion`. It has its own design system (tokens), primitive library (`R*` components in `src/v2/lib/`), universal input (mouse/touch/keyboard/gamepad), and responsive system. New frontend work goes in v2. - -v2 has a detailed constitution, split across focused skills (below). **Read the relevant skill before editing v2 code.** +`frontend/CLAUDE.md` (v1 vs v2, frontend commands) and `backend/CLAUDE.md` (backend commands) load when you work in those directories. New frontend work goes in v2 (`frontend/src/v2/`); v1 is frozen. --- ## Skills - load the focused guide for your task -These live in `.claude/skills/` and carry the detailed rules. Invoke the one that matches what you're doing: - -| Skill | When | -| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `knowledge-base` | Understanding how part of the codebase works or where it lives, via Greptile's synthesized knowledge base. Verify what it says against the code. | -| `frontend-v2-components` | Building/editing any v2 component - tiers (lib/shared/feature), file & SFC conventions, barrels, anti-patterns. | -| `frontend-v2-theming` | Colors, tokens, light/dark themes, visual language - and the **zero-hex-literal** policy. | -| `frontend-v2-input` | Interactive components, focus/spatial navigation, gamepad/keyboard, breakpoints & responsive layout. | -| `frontend-v2-patterns` | Feature behavior - errors/snackbars, loading, sockets, state persistence, pagination, forms, permissions, destructive confirmations. | -| `frontend-i18n` | Any user-visible string or change under `frontend/src/locales/**`. | -| `backend-development` | Endpoints, handlers, models, schemas, metadata adapters, tasks, migrations under `backend/`. | -| `review-polish` | Before committing / opening a PR / declaring done - the self-review pass (comments, duplication, naming, test typing) plus the checks that keep CI green. | -| `security-audit` | Vetting a diff (release tag range or PR) for anything malicious or a security regression - supply chain, egress, auth/injection, CI, provenance. | -| `pr-ready` | Before opening a PR - the four passes in order: `security-audit`, `code-review xhigh --fix`, `simplify`, `review-polish`. Not auto-invoked. | -| `address-bot-reviews` | After Greptile and Copilot review a PR - triage each finding, fix what holds up, reply with the fix or the reason, and resolve the threads. Not auto-invoked. | -| `draft-release-notes` | Drafting the GitHub release notes for a release, stable or alpha/beta, from the diff since the previous stable tag. | -| `draft-announcement` | Drafting the Discord announcement for a release, from the release notes plus an interview about community news. Not auto-invoked. | +These live in `.claude/skills/` and carry the detailed rules. Invoke the one that matches what you're doing. `pr-ready`, `address-bot-reviews`, and `draft-announcement` are run by the user, not auto-invoked. --- @@ -61,7 +31,7 @@ These live in `.claude/skills/` and carry the detailed rules. Invoke the one tha **Disclose AI assistance in the PR.** RomM requires it (see `CONTRIBUTING.md`): state that AI was used and to what extent. This is mandatory and non-negotiable for agent-written contributions. **Branch off `master`; open PRs against `master`.** Fork → feature branch → PR. Don't push to `master`. -**Linting is via [Trunk](https://trunk.io)** (`trunk fmt && trunk check`) — it wraps ruff, black, isort, mypy, ESLint, Prettier, and more, and runs in CI on every PR. **Never commit with `--no-verify`.** +**Linting is via [Trunk](https://trunk.io)** (`trunk fmt && trunk check`), which wraps ruff, black, isort, ESLint, Prettier, and more, and runs in CI on every PR. **Never commit with `--no-verify`.** **The backend owns the API contract.** Changed a response schema or route? Regenerate frontend types (`npm run generate`) and re-typecheck. **Tests travel with code.** New logic gets a test; new endpoints get endpoint tests; new v2 primitives get a Storybook story (+ `play()` if interactive). **Verify before handoff.** Don't say "done" on UI work without testing it in the browser in both themes and all input modalities. See `review-polish`. @@ -84,31 +54,4 @@ These live in `.claude/skills/` and carry the detailed rules. Invoke the one tha **Setup:** see `DEVELOPER_SETUP.md`. Docker path is `cp env.template .env` → `docker compose build` → `docker compose up -d` (app at `http://localhost:3000`). -**Backend** (`cd backend`): - -```bash -uv sync --all-extras --dev # install -uv run main.py # run (migrations auto-apply) -uv run pytest # test - affected files only, NEVER the whole suite -uv run alembic revision --autogenerate -m "msg" # new migration (then HAND-REVIEW) -uv run alembic upgrade head # apply migrations -``` - -**Frontend** (`cd frontend`): - -```bash -npm install # install (Node 24) -npm run dev # dev server :3000 -npm run typecheck # vue-tsc -npm run typecheck:scripts # tsc on the Node/Vite tooling in scripts/ -npm run test # vitest (+ Storybook play() tests) -npm run test:e2e # playwright (needs a running app + seeded e2e users) -npm run build # production build -npm run generate # regenerate types from backend OpenAPI (backend must be running) -npm run build:tokens # regenerate v2 tokens.css (auto on predev/prebuild) -npm run storybook # component library on :6006 -python3 src/locales/check_i18n_locales.py # i18n parity check -python3 src/locales/check_i18n_sorted.py # locale keys sorted (--fix to sort) -``` - **Lint (both stacks):** `trunk fmt && trunk check`. diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index 6bfaa7ead..d384d1ffa 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -128,7 +128,7 @@ uv run python3 main.py #### - Run the task workers -A manual task run is refused, and a scheduled job stays queued, until an RQ worker listens on its queue; scans have a worker of their own. Each command is a foreground process, so run them in separate terminals. `-c config` reads the Redis connection from the same `REDIS_*` settings in `.env` the backend uses. +A manual task run is refused, and a scheduled job stays queued, until an RQ worker listens on its queue; scans and streaming teardowns each have a worker of their own. Each command is a foreground process, so run them in separate terminals. `-c config` reads the Redis connection from the same `REDIS_*` settings in `.env` the backend uses. ```sh cd backend @@ -140,6 +140,11 @@ cd backend uv run rq worker -c config --worker-class handler.rq_worker.RomMWorker --with-scheduler scans ``` +```sh +cd backend +uv run rq worker -c config --worker-class handler.rq_worker.RomMWorker --with-scheduler streaming +``` + `--with-scheduler` releases delayed jobs, such as the rescans the filesystem watcher waits out, so each worker needs it. The recurring schedule is registered by the RQ cron process, which the workers then execute: ```sh @@ -178,11 +183,15 @@ Component docs and visual QA for `frontend/src/v2/` (port 6006): ```sh npm run storybook -npm run storybook:test # composeStories + play() + a11y (v2 /lib stories) +npm run storybook:test # composeStories + play() + a11y (v2 /lib and components/shared stories) ``` For responsive layouts, use the viewport toolbar presets from `.storybook/rommViewports.ts`. +#### - Optional: local frontend against a remote RomM + +To run `npm run dev` or `npm run preview` against another RomM instance (for example a home server with a full library), set `DEV_PROXY_TARGET` in the repo-root `.env` to its origin, such as `https://romm.example.com`. Vite then proxies `/api`, `/ws` and `/assets/romm` there instead of the local backend. Leave it empty to keep the default `http://127.0.0.1:${DEV_PORT}`. The remote's TLS certificate must be valid. Sign in with a username and password: OIDC login does not work through the proxy, because the identity provider redirects to the remote's `OIDC_REDIRECT_URI`, so the session never reaches localhost. + ## Setting up the linter We use [Trunk](https://trunk.io) for linting, which combines multiple linters and formatters with sensible defaults and a single configuration file. You'll need to install the Trunk CLI to use it. @@ -200,6 +209,13 @@ trunk fmt trunk check ``` +Type checking runs separately from Trunk, against the project's own environment. CI type-checks the whole backend on every backend change; to run it locally: + +```sh +cd backend +uv run mypy --config-file ../.trunk/configs/mypy.ini . +``` + **Failing to install and run the linter will result in a failed CI check, which won't allow us to merge your PR.** ## Test setup diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md new file mode 100644 index 000000000..85919cb08 --- /dev/null +++ b/backend/CLAUDE.md @@ -0,0 +1,12 @@ +# RomM backend + +## Commands (`cd backend`) + +```bash +uv sync --all-extras --dev # install +uv run main.py # run (migrations auto-apply) +uv run pytest # test - affected files only, NEVER the whole suite +uv run mypy --config-file ../.trunk/configs/mypy.ini . # type-check the whole backend +uv run alembic revision --autogenerate -m "msg" # new migration (then HAND-REVIEW) +uv run alembic upgrade head # apply migrations +``` diff --git a/backend/adapters/services/retroachievements.py b/backend/adapters/services/retroachievements.py index b1e04f834..ed1ca78e2 100644 --- a/backend/adapters/services/retroachievements.py +++ b/backend/adapters/services/retroachievements.py @@ -35,7 +35,7 @@ async def auth_middleware( Reference: https://api-docs.retroachievements.org/getting-started.html#quick-start-http-requests """ - req.url = req.url.update_query({"y": RETROACHIEVEMENTS_API_KEY}) # type: ignore + req.url = req.url.update_query({"y": RETROACHIEVEMENTS_API_KEY}) # type: ignore[dict-item] return await handler(req) diff --git a/backend/adapters/services/steam.py b/backend/adapters/services/steam.py index 6cb2e1875..88fa9f3b6 100644 --- a/backend/adapters/services/steam.py +++ b/backend/adapters/services/steam.py @@ -139,12 +139,28 @@ class SteamService: query["filters"] = filters url = self.url.joinpath("appdetails").with_query(query) response = await self._request(str(url)) - envelope = cast(SteamAppDetailsEnvelope | None, response.get(str(app_id))) + envelope = response.get(str(app_id)) + if envelope is None and len(response) == 1: + envelope = self._envelope_keyed_by_another_id(response, app_id) + envelope = cast(SteamAppDetailsEnvelope | None, envelope) if not envelope or not envelope.get("success"): return None return envelope.get("data") + @staticmethod + def _envelope_keyed_by_another_id(response: dict, app_id: int) -> dict | None: + """Steam keys some apps' envelope by another ID, e.g. one of their DLC.""" + envelope = next(iter(response.values())) + if not isinstance(envelope, dict): + return None + + data = envelope.get("data") + if not isinstance(data, dict) or data.get("steam_appid") != app_id: + return None + + return envelope + async def get_library_capsule_url(self, app_id: int) -> str | None: """The portrait capsule URL when the CDN serves one, else None.""" return await self._probe_cdn_asset( diff --git a/backend/alembic/versions/0124_gallery_and_fk_indexes.py b/backend/alembic/versions/0124_gallery_and_fk_indexes.py index d58bda283..53abf78fe 100644 --- a/backend/alembic/versions/0124_gallery_and_fk_indexes.py +++ b/backend/alembic/versions/0124_gallery_and_fk_indexes.py @@ -16,7 +16,7 @@ Create Date: 2026-09-07 00:00:00.000000 from alembic import op -from utils.database import POSTGRESQL_FK_INDEXES, is_postgresql +from utils.database import is_postgresql # revision identifiers, used by Alembic. revision = "0124_gallery_and_fk_indexes" @@ -24,6 +24,33 @@ down_revision = "0123_recommendation_metadata" branch_labels = None depends_on = None +# The foreign keys this revision indexed on PostgreSQL, as they stood then. +# `utils.database.POSTGRESQL_FK_INDEXES` tracks the models and a later revision +# can drop one of these columns, which would silently change what this revision +# creates and, worse, what its downgrade drops. +POSTGRESQL_FK_INDEXES = ( + ("collections", "ix_collections_user_id", "user_id"), + ("smart_collections", "ix_smart_collections_user_id", "user_id"), + ("rom_notes", "ix_rom_notes_user_id", "user_id"), + ("firmware", "ix_firmware_platform_id", "platform_id"), + ("collections_roms", "ix_collections_roms_rom_id", "rom_id"), + ("music_playlist_tracks", "ix_music_playlist_tracks_rom_file_id", "rom_file_id"), + ("music_favorite_tracks", "ix_music_favorite_tracks_rom_file_id", "rom_file_id"), + ("play_sessions", "ix_play_sessions_rom_id", "rom_id"), + ("play_sessions", "ix_play_sessions_device_id", "device_id"), + ("play_sessions", "ix_play_sessions_sync_session_id", "sync_session_id"), + ("saves", "ix_saves_user_id", "user_id"), + ("states", "ix_states_user_id", "user_id"), + ("screenshots", "ix_screenshots_user_id", "user_id"), + ("rom_file_user", "ix_rom_file_user_user_id", "user_id"), + ("memory_cards", "ix_memory_cards_platform_id", "platform_id"), + ( + "streaming_container_adoptions", + "ix_streaming_container_adoptions_decided_by_user_id", + "decided_by_user_id", + ), +) + # (table, index name, columns) PORTABLE_INDEXES = ( ("screenshots", "ix_screenshots_rom_user", ["rom_id", "user_id"]), diff --git a/backend/alembic/versions/0135_drop_play_session_sync_link.py b/backend/alembic/versions/0135_drop_play_session_sync_link.py new file mode 100644 index 000000000..d6a13b886 --- /dev/null +++ b/backend/alembic/versions/0135_drop_play_session_sync_link.py @@ -0,0 +1,73 @@ +"""Drop the play session's link to a sync session + +Revision ID: 0135_drop_play_session_sync_link +Revises: 0134_gallery_sort_indexes +Create Date: 2026-09-21 00:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op + +from utils.database import is_postgresql + +# revision identifiers, used by Alembic. +revision = "0135_drop_play_session_sync_link" +down_revision = "0134_gallery_sort_indexes" +branch_labels = None +depends_on = None + +INDEX_NAME = "ix_play_sessions_sync_session_id" +FK_NAME = "fk_play_sessions_sync_session_id" + + +def _existing_fk_name(conn: sa.Connection) -> str | None: + """The constraint on this column, under whatever name its server chose.""" + for fk in sa.inspect(conn).get_foreign_keys("play_sessions"): + if fk.get("referred_table") == "sync_sessions" and fk.get( + "constrained_columns" + ) == ["sync_session_id"]: + return fk.get("name") or FK_NAME + return None + + +def upgrade() -> None: + conn = op.get_bind() + + # PostgreSQL drops a column's constraints with it; MariaDB and MySQL refuse + # until the foreign key is gone, and 0076 left it for the server to name. + if not is_postgresql(conn): + name = _existing_fk_name(conn) + if name: + op.drop_constraint(name, "play_sessions", type_="foreignkey") + + op.drop_index(INDEX_NAME, table_name="play_sessions", if_exists=True) + op.drop_column("play_sessions", "sync_session_id", if_exists=True) + + +def downgrade() -> None: + conn = op.get_bind() + + op.add_column( + "play_sessions", + sa.Column("sync_session_id", sa.Integer(), nullable=True), + if_not_exists=True, + ) + # Only on PostgreSQL, which is where 0124 put it: MariaDB and MySQL index a + # single-column foreign key themselves, and the index they make backs the + # constraint, so one created here could not be dropped again. + if is_postgresql(conn): + op.create_index( + INDEX_NAME, "play_sessions", ["sync_session_id"], if_not_exists=True + ) + # Guarded like the steps above, since these databases commit each one and a + # downgrade that stopped halfway is replayed from the top. + if not _existing_fk_name(conn): + op.create_foreign_key( + FK_NAME, + "play_sessions", + "sync_sessions", + ["sync_session_id"], + ["id"], + ondelete="SET NULL", + ) diff --git a/backend/alembic/versions/0136_deleted_assets.py b/backend/alembic/versions/0136_deleted_assets.py new file mode 100644 index 000000000..0b2e3eb26 --- /dev/null +++ b/backend/alembic/versions/0136_deleted_assets.py @@ -0,0 +1,62 @@ +"""Add deleted_assets table + +Revision ID: 0136_deleted_assets +Revises: 0135_drop_play_session_sync_link +Create Date: 2026-09-21 00:00:00.000000 + +""" + +import sqlalchemy as sa +from alembic import op + +from utils.database import CustomJSON + +# revision identifiers, used by Alembic. +revision = "0136_deleted_assets" +down_revision = "0135_drop_play_session_sync_link" +branch_labels = None +depends_on = None + +INDEX_NAME = "ix_deleted_assets_user_rom_slot" +ROM_INDEX_NAME = "ix_deleted_assets_rom_id" + + +def upgrade() -> None: + op.create_table( + "deleted_assets", + 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("slot", sa.String(length=255), nullable=False), + sa.Column("content_hashes", CustomJSON(), nullable=False), + sa.Column( + "created_at", + sa.TIMESTAMP(timezone=True), + nullable=False, + server_default=sa.text("now()"), + ), + sa.Column( + "updated_at", + sa.TIMESTAMP(timezone=True), + nullable=False, + server_default=sa.text("now()"), + ), + sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), + sa.ForeignKeyConstraint(["rom_id"], ["roms.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + if_not_exists=True, + ) + op.create_index( + INDEX_NAME, + "deleted_assets", + ["user_id", "rom_id", "slot"], + unique=True, + if_not_exists=True, + ) + op.create_index( + ROM_INDEX_NAME, "deleted_assets", ["rom_id"], unique=False, if_not_exists=True + ) + + +def downgrade() -> None: + op.drop_table("deleted_assets", if_exists=True) diff --git a/backend/config/__init__.py b/backend/config/__init__.py index 7c5b30ab2..3901325ee 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -206,9 +206,16 @@ EMAIL_ENABLED: Final[bool] = bool( ROMM_CORS_ALLOWED_ORIGINS: Final[list[str]] = [ o.strip() - for o in (_get_env("ROMM_CORS_ALLOWED_ORIGINS", "*")).split(",") + for o in (_get_env("ROMM_CORS_ALLOWED_ORIGINS") or "").split(",") if o.strip() ] + + +def cors_allow_credentials(origins: list[str]) -> bool: + """A wildcard origin carries no credentials, since it echoes any caller's.""" + return "*" not in origins + + ROMM_SESSION_SECURE_COOKIE: Final[bool] = safe_str_to_bool( _get_env("ROMM_SESSION_SECURE_COOKIE") ) diff --git a/backend/decorators/auth.py b/backend/decorators/auth.py index ef39e432f..bba980e66 100644 --- a/backend/decorators/auth.py +++ b/backend/decorators/auth.py @@ -1,5 +1,6 @@ import functools import inspect +from collections.abc import Callable from typing import Any from authlib.integrations.starlette_client import OAuth @@ -135,11 +136,11 @@ def _requires_scopes(scopes: list[Scope]): def protected_route( - method: Any, + method: Callable[..., Callable[[DecoratedCallable], DecoratedCallable]], path: str, scopes: list[Scope] | None = None, - **kwargs, -): + **kwargs: Any, +) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: fn = _requires_scopes(scopes or [])(func) return method( diff --git a/backend/decorators/database.py b/backend/decorators/database.py index cdf9ac283..bef582fe1 100644 --- a/backend/decorators/database.py +++ b/backend/decorators/database.py @@ -1,4 +1,5 @@ import functools +from collections.abc import Callable from fastapi import HTTPException, status from sqlalchemy.exc import ProgrammingError @@ -7,9 +8,9 @@ from handler.database.base_handler import sync_session from logger.logger import log -def begin_session(func): +def begin_session[**P, R](func: Callable[P, R]) -> Callable[P, R]: @functools.wraps(func) - def wrapper(*args, **kwargs): + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: # Reuse a caller-provided session so the handler can join an existing unit of work if kwargs.get("session") is not None: return func(*args, **kwargs) diff --git a/backend/endpoints/audit_events.py b/backend/endpoints/audit_events.py index b3f0a07f0..3b2ef22b1 100644 --- a/backend/endpoints/audit_events.py +++ b/backend/endpoints/audit_events.py @@ -1,32 +1,30 @@ from datetime import datetime from typing import Annotated -from fastapi import Query, Request -from fastapi_pagination import resolve_params -from fastapi_pagination.limit_offset import LimitOffsetParams -from pydantic import BaseModel +from fastapi import Depends, Query, Request +from pydantic import BaseModel, Field from decorators.auth import protected_route from endpoints.responses.audit_event import AuditEventSchema -from endpoints.responses.base import TypedLimitOffsetPage +from endpoints.responses.base import LimitOffsetPage, PageParams from handler.auth.constants import Scope from handler.auth.dependencies import get_permissions from handler.database import db_audit_event_handler from handler.database.audit_events_handler import AuditEventFilters from models.audit_event import AuditCategory -from utils.router import APIRouter +from utils.router import APIRouter, as_query_dependency router = APIRouter(prefix="/audit-events", tags=["audit"]) -class AuditLimitOffsetParams(LimitOffsetParams): - limit: int = Query(50, ge=1, le=200, description="Page size limit") - offset: int = Query(0, ge=0, description="Page offset") +class AuditPageParams(PageParams): + limit: int = Field(50, ge=1, le=200, description="Page size limit") -class AuditPage[T: BaseModel](TypedLimitOffsetPage[T]): - __params_type__ = AuditLimitOffsetParams +AUDIT_PAGE_QUERY = as_query_dependency(AuditPageParams) + +class AuditPage[T: BaseModel](LimitOffsetPage[T]): # Rows are ordered by when they happened, not by id, so later pages pin to # the highest id rather than to the first row's. max_id: int | None = None @@ -35,6 +33,7 @@ class AuditPage[T: BaseModel](TypedLimitOffsetPage[T]): @protected_route(router.get, "", [Scope.ME_READ]) def get_audit_events( request: Request, + params: Annotated[AuditPageParams, Depends(AUDIT_PAGE_QUERY)], actor_id: Annotated[ list[int] | None, Query( @@ -62,7 +61,6 @@ def get_audit_events( ) -> AuditPage[AuditEventSchema]: """The audit log, newest first: everyone's for an admin, the caller's own otherwise.""" perms = get_permissions(request) - params: AuditLimitOffsetParams = resolve_params() # An admin's token scoped below users.read must not read other users' history. sees_everyone = perms.is_admin and Scope.USERS_READ in request.auth.scopes @@ -86,9 +84,12 @@ def get_audit_events( limit=params.limit, offset=params.offset, ) - return AuditPage.create( - [AuditEventSchema.from_row(event, device_name) for event, device_name in rows], - params, + return AuditPage( + items=[ + AuditEventSchema.from_row(event, device_name) for event, device_name in rows + ], total=total, + limit=params.limit, + offset=params.offset, max_id=highest_id, ) diff --git a/backend/endpoints/music.py b/backend/endpoints/music.py index 46d4ddd03..280958183 100644 --- a/backend/endpoints/music.py +++ b/backend/endpoints/music.py @@ -1,12 +1,10 @@ from typing import Annotated -from fastapi import HTTPException, Query, Request, status -from fastapi_pagination import resolve_params -from fastapi_pagination.limit_offset import LimitOffsetParams -from pydantic import BaseModel +from fastapi import Depends, HTTPException, Query, Request, status +from pydantic import BaseModel, Field from decorators.auth import protected_route -from endpoints.responses.base import TypedLimitOffsetPage +from endpoints.responses.base import LimitOffsetPage, PageParams from endpoints.responses.music import ( FacetValueSchema, MusicGameFacetSchema, @@ -18,19 +16,22 @@ from handler.auth.constants import Scope from handler.auth.dependencies import get_permissions from handler.auth.permissions import ResolvedPermissions from handler.database import db_music_playlist_handler, db_rom_handler -from utils.router import APIRouter +from utils.router import APIRouter, as_query_dependency router = APIRouter(prefix="/music", tags=["music"]) -class MusicLimitOffsetParams(LimitOffsetParams): +class MusicPageParams(PageParams): # Sized to the largest page the jukebox requests (a whole soundtrack). - limit: int = Query(50, ge=1, le=1_000, description="Page size limit") - offset: int = Query(0, ge=0, description="Page offset") + limit: int = Field(50, ge=1, le=1_000, description="Page size limit") -class MusicPage[T: BaseModel](TypedLimitOffsetPage[T]): - __params_type__ = MusicLimitOffsetParams +MUSIC_PAGE_QUERY = as_query_dependency(MusicPageParams) + + +# Its own class so the OpenAPI schema keeps the `MusicPage_*` names. +class MusicPage[T: BaseModel](LimitOffsetPage[T]): + pass class MusicTrackIdsPayload(BaseModel): @@ -69,6 +70,7 @@ def resolve_track_ids(rom_file_ids: list[int], perms: ResolvedPermissions) -> li @protected_route(router.get, "/tracks", [Scope.ROMS_READ]) def get_music_tracks( request: Request, + params: Annotated[MusicPageParams, Depends(MUSIC_PAGE_QUERY)], search: Annotated[ str | None, Query(description="Substring match on title/artist/album.") ] = None, @@ -105,7 +107,6 @@ def get_music_tracks( ) -> MusicPage[MusicTrackSchema]: """Flat, filterable, paginated list of soundtrack tracks.""" perms = get_permissions(request) - params: MusicLimitOffsetParams = resolve_params() rows, total = db_rom_handler.get_music_tracks( hidden_platform_ids=perms.hidden_platform_ids, hidden_rom_ids=perms.hidden_rom_ids, @@ -135,6 +136,7 @@ def get_music_tracks( @protected_route(router.get, "/favorites", [Scope.PLAYLISTS_READ]) def get_music_favorites( request: Request, + params: Annotated[MusicPageParams, Depends(MUSIC_PAGE_QUERY)], search: Annotated[ str | None, Query(description="Substring match on title/artist/album.") ] = None, @@ -168,7 +170,6 @@ def get_music_favorites( ) -> MusicPage[MusicTrackSchema]: """The requesting user's favorite tracks; same shape and filters as /tracks.""" perms = get_permissions(request) - params: MusicLimitOffsetParams = resolve_params() rows, total = db_rom_handler.get_music_tracks( hidden_platform_ids=perms.hidden_platform_ids, hidden_rom_ids=perms.hidden_rom_ids, @@ -218,6 +219,7 @@ def remove_music_favorites(request: Request, payload: MusicTrackIdsPayload) -> d def _facet_page( field: str, request: Request, + params: PageParams, *, search: str | None, artist: str | None, @@ -231,7 +233,6 @@ def _facet_page( order_dir: str, ) -> MusicPage[FacetValueSchema]: perms = get_permissions(request) - params: MusicLimitOffsetParams = resolve_params() rows, total = db_rom_handler.get_music_facet( field=field, hidden_platform_ids=perms.hidden_platform_ids, @@ -256,6 +257,7 @@ def _facet_page( @protected_route(router.get, "/artists", [Scope.ROMS_READ]) def get_music_artists( request: Request, + params: Annotated[MusicPageParams, Depends(MUSIC_PAGE_QUERY)], search: Annotated[str | None, Query(description="Typeahead on artist.")] = None, album: Annotated[str | None, Query()] = None, genre: Annotated[str | None, Query()] = None, @@ -270,6 +272,7 @@ def get_music_artists( return _facet_page( "artists", request, + params, search=search, artist=None, album=album, @@ -286,6 +289,7 @@ def get_music_artists( @protected_route(router.get, "/albums", [Scope.ROMS_READ]) def get_music_albums( request: Request, + params: Annotated[MusicPageParams, Depends(MUSIC_PAGE_QUERY)], search: Annotated[str | None, Query(description="Typeahead on album.")] = None, artist: Annotated[str | None, Query()] = None, genre: Annotated[str | None, Query()] = None, @@ -300,6 +304,7 @@ def get_music_albums( return _facet_page( "albums", request, + params, search=search, artist=artist, album=None, @@ -316,6 +321,7 @@ def get_music_albums( @protected_route(router.get, "/genres", [Scope.ROMS_READ]) def get_music_genres( request: Request, + params: Annotated[MusicPageParams, Depends(MUSIC_PAGE_QUERY)], search: Annotated[str | None, Query(description="Typeahead on genre.")] = None, artist: Annotated[str | None, Query()] = None, album: Annotated[str | None, Query()] = None, @@ -330,6 +336,7 @@ def get_music_genres( return _facet_page( "genres", request, + params, search=search, artist=artist, album=album, @@ -346,6 +353,7 @@ def get_music_genres( @protected_route(router.get, "/years", [Scope.ROMS_READ]) def get_music_years( request: Request, + params: Annotated[MusicPageParams, Depends(MUSIC_PAGE_QUERY)], search: Annotated[str | None, Query(description="Typeahead on year.")] = None, artist: Annotated[str | None, Query()] = None, album: Annotated[str | None, Query()] = None, @@ -360,6 +368,7 @@ def get_music_years( return _facet_page( "years", request, + params, search=search, artist=artist, album=album, @@ -376,6 +385,7 @@ def get_music_years( @protected_route(router.get, "/game-genres", [Scope.ROMS_READ]) def get_music_game_genres( request: Request, + params: Annotated[MusicPageParams, Depends(MUSIC_PAGE_QUERY)], search: Annotated[ str | None, Query(description="Typeahead on the game's genre.") ] = None, @@ -396,7 +406,6 @@ def get_music_game_genres( Distinct from `/genres`, which facets the tag written on the audio file. """ perms = get_permissions(request) - params: MusicLimitOffsetParams = resolve_params() rows, total = db_rom_handler.get_music_game_genre_facet( hidden_platform_ids=perms.hidden_platform_ids, hidden_rom_ids=perms.hidden_rom_ids, @@ -422,6 +431,7 @@ def get_music_game_genres( @protected_route(router.get, "/platforms", [Scope.ROMS_READ]) def get_music_platforms( request: Request, + params: Annotated[MusicPageParams, Depends(MUSIC_PAGE_QUERY)], search: Annotated[str | None, Query(description="Typeahead on platform.")] = None, artist: Annotated[str | None, Query()] = None, album: Annotated[str | None, Query()] = None, @@ -437,7 +447,6 @@ def get_music_platforms( ) -> MusicPage[MusicPlatformFacetSchema]: """Platforms that have soundtrack tracks, with per-platform counts.""" perms = get_permissions(request) - params: MusicLimitOffsetParams = resolve_params() rows, total = db_rom_handler.get_music_platform_facet( hidden_platform_ids=perms.hidden_platform_ids, hidden_rom_ids=perms.hidden_rom_ids, @@ -463,6 +472,7 @@ def get_music_platforms( @protected_route(router.get, "/games", [Scope.ROMS_READ]) def get_music_games( request: Request, + params: Annotated[MusicPageParams, Depends(MUSIC_PAGE_QUERY)], search: Annotated[ str | None, Query(description="Substring match on game/title/artist/album.") ] = None, @@ -481,7 +491,6 @@ def get_music_games( ) -> MusicPage[MusicGameFacetSchema]: """Games that have soundtrack tracks -- the jukebox's album list.""" perms = get_permissions(request) - params: MusicLimitOffsetParams = resolve_params() rows, total = db_rom_handler.get_music_game_facet( hidden_platform_ids=perms.hidden_platform_ids, hidden_rom_ids=perms.hidden_rom_ids, diff --git a/backend/endpoints/music_playlists.py b/backend/endpoints/music_playlists.py index 7c3678a19..23166507d 100644 --- a/backend/endpoints/music_playlists.py +++ b/backend/endpoints/music_playlists.py @@ -1,16 +1,16 @@ from typing import Annotated -from fastapi import HTTPException +from fastapi import Depends, HTTPException from fastapi import Path as PathVar from fastapi import Query, Request, Response, status -from fastapi_pagination import resolve_params from pydantic import BaseModel, Field from sqlalchemy.exc import IntegrityError from decorators.auth import protected_route from endpoints.music import ( - MusicLimitOffsetParams, + MUSIC_PAGE_QUERY, MusicPage, + MusicPageParams, MusicTrackIdsPayload, resolve_track_ids, ) @@ -154,6 +154,7 @@ def delete_playlist( @protected_route(router.get, "/{id}/tracks", [Scope.PLAYLISTS_READ]) def get_playlist_tracks( request: Request, + params: Annotated[MusicPageParams, Depends(MUSIC_PAGE_QUERY)], id: Annotated[int, PathVar(description="Playlist internal id.", ge=1)], order_by: Annotated[ str, @@ -167,7 +168,6 @@ def get_playlist_tracks( than the playlist's stored track_count.""" playlist = _get_visible_playlist(request, id) perms = get_permissions(request) - params: MusicLimitOffsetParams = resolve_params() rows, total = db_rom_handler.get_music_tracks( hidden_platform_ids=perms.hidden_platform_ids, hidden_rom_ids=perms.hidden_rom_ids, diff --git a/backend/endpoints/netplay.py b/backend/endpoints/netplay.py index ccf7937fc..46b99c3bb 100644 --- a/backend/endpoints/netplay.py +++ b/backend/endpoints/netplay.py @@ -3,7 +3,10 @@ from typing import Dict, TypedDict from fastapi import Request from decorators.auth import protected_route +from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException from handler.auth.constants import Scope +from handler.auth.dependencies import assert_rom_visible +from handler.database import db_rom_handler from handler.netplay_handler import NetplayRoom, netplay_handler from utils.router import APIRouter @@ -31,7 +34,7 @@ def _get_owner_player_name(room: NetplayRoom) -> str: ) -def _is_room_open(room: NetplayRoom, game_id: str) -> bool: +def _is_room_open(room: NetplayRoom, game_id: int) -> bool: if len(room["players"]) >= room["max_players"]: return False return str(room["game_id"]) == str(game_id) @@ -45,8 +48,14 @@ class RoomsResponse(TypedDict): hasPassword: bool -@protected_route(router.get, "/list", [Scope.ASSETS_READ]) -async def get_rooms(request: Request, game_id: str) -> Dict[str, RoomsResponse]: +@protected_route(router.get, "/list", [Scope.ROMS_READ]) +async def get_rooms(request: Request, game_id: int) -> Dict[str, RoomsResponse]: + rom = db_rom_handler.get_rom_visibility(game_id) + if not rom: + raise RomNotFoundInDatabaseException(game_id) + + assert_rom_visible(request, rom) + netplay_rooms = await netplay_handler.get_all() open_rooms: Dict[str, RoomsResponse] = { diff --git a/backend/endpoints/notification_channels.py b/backend/endpoints/notification_channels.py index 423363461..9e653b626 100644 --- a/backend/endpoints/notification_channels.py +++ b/backend/endpoints/notification_channels.py @@ -1,11 +1,14 @@ from collections.abc import Awaitable +from functools import cache from typing import TypeVar from fastapi import HTTPException, Request, status from decorators.auth import protected_route from endpoints.responses.notification_channel import ( - EmailChannelCreatePayload, + AppriseServiceSchema, + AppriseUrlFieldsSchema, + AppriseUrlPayload, NotificationChannelCodePayload, NotificationChannelCreatePayload, NotificationChannelSchema, @@ -13,9 +16,10 @@ from endpoints.responses.notification_channel import ( NotificationChannelUpdatePayload, ) from handler.auth.constants import Scope +from handler.auth.dependencies import assert_admin from handler.database import db_notification_channel_handler from handler.email_handler import EmailError -from handler.notification_channels import channels +from handler.notification_channels import apprise_channel, channels from handler.notification_channels.channels import ChannelError from handler.notification_channels.confirmation import CodeCooldownError from models.notification_channel import NotificationChannel, NotificationChannelType @@ -67,31 +71,48 @@ def get_notification_channels(request: Request) -> list[NotificationChannelSchem ] +@protected_route(router.get, "/apprise-services", [Scope.ME_READ]) +def get_apprise_services(request: Request) -> list[AppriseServiceSchema]: + """Every service an admin's Apprise channel can go out on, with its fields.""" + assert_admin(request) + return _apprise_catalog() + + +@protected_route(router.post, "/apprise-services/parse", [Scope.ME_READ]) +def parse_apprise_url( + request: Request, payload: AppriseUrlPayload +) -> AppriseUrlFieldsSchema: + """Read a service's own URL (a Discord webhook's) or an Apprise URL into its fields.""" + assert_admin(request) + try: + service, fields = apprise_channel.fields_from_url(payload.url) + except ValueError as exc: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc) + ) from exc + return AppriseUrlFieldsSchema(service=service.id, fields=fields) + + +@cache +def _apprise_catalog() -> list[AppriseServiceSchema]: + return [AppriseServiceSchema.from_service(s) for s in apprise_channel.services()] + + @protected_route(router.post, "", [Scope.ME_WRITE], status_code=status.HTTP_201_CREATED) async def create_notification_channel( request: Request, payload: NotificationChannelCreatePayload ) -> NotificationChannelSchema: """Add a channel; an email address gets a code to confirm it with first.""" - if isinstance(payload, EmailChannelCreatePayload): - created = channels.create_channel( - request.user, - NotificationChannelType.EMAIL, - payload.name, - payload.min_level, - payload.topics, - address=payload.address, - ) - else: - created = channels.create_channel( - request.user, - NotificationChannelType.WEBHOOK, - payload.name, - payload.min_level, - payload.topics, - url=payload.url, - format=payload.format, - secret=payload.secret, - ) + # What each type sends it to: a URL and secret, an address, or a service's fields. + target = payload.model_dump(exclude={"type", "name", "min_level", "topics"}) + created = channels.create_channel( + request.user, + NotificationChannelType(payload.type), + payload.name, + payload.min_level, + payload.topics, + **target, + ) return NotificationChannelSchema.from_channel(await _as_http(created)) @@ -116,10 +137,10 @@ async def update_notification_channel( request.user, changes, url=payload.url, - format=payload.format, secret=payload.secret, secret_given="secret" in payload.model_fields_set, address=payload.address, + fields=payload.fields, ) ) return NotificationChannelSchema.from_channel(updated) diff --git a/backend/endpoints/permissions.py b/backend/endpoints/permissions.py index c2f7e55ac..19dd9dba3 100644 --- a/backend/endpoints/permissions.py +++ b/backend/endpoints/permissions.py @@ -209,6 +209,8 @@ async def update_permission_group( else None ), ) + if updated is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found") # Grant changes alter every member's effective permissions. for member_id in db_permission_handler.get_group_member_ids(id): await emit_permissions_changed(member_id) diff --git a/backend/endpoints/responses/base.py b/backend/endpoints/responses/base.py index 09a51d792..4570d40b6 100644 --- a/backend/endpoints/responses/base.py +++ b/backend/endpoints/responses/base.py @@ -1,11 +1,11 @@ from collections.abc import Sequence from datetime import datetime, timezone -from typing import Annotated, Any, Self, cast +from typing import Annotated, Self -from fastapi_pagination.bases import AbstractParams -from fastapi_pagination.limit_offset import LimitOffsetPage from pydantic import BaseModel as PydanticBaseModel -from pydantic import PlainSerializer +from pydantic import Field, PlainSerializer + +from utils.router import as_query_dependency def _serialize_utc_datetime(dt: datetime) -> str: @@ -24,16 +24,27 @@ class BaseModel(PydanticBaseModel): pass -class TypedLimitOffsetPage[T: PydanticBaseModel](LimitOffsetPage[T]): - """LimitOffsetPage whose `create` is typed to return the subclass it builds.""" +class PageParams(PydanticBaseModel): + # Temporarily high until every app paginates + limit: int = Field(50, ge=1, le=10_000, description="Page size limit") + offset: int = Field(0, ge=0, description="Page offset") + + +PAGE_QUERY = as_query_dependency(PageParams) + + +class LimitOffsetPage[T: PydanticBaseModel](PydanticBaseModel): + items: Sequence[T] + total: int = Field(ge=0) + limit: int = Field(ge=1) + offset: int = Field(ge=0) @classmethod def create( cls, items: Sequence[T], - params: AbstractParams, + params: PageParams, *, - total: int | None = None, - **kwargs: Any, + total: int, ) -> Self: - return cast(Self, super().create(items, params, total=total, **kwargs)) + return cls(items=items, total=total, limit=params.limit, offset=params.offset) diff --git a/backend/endpoints/responses/feeds.py b/backend/endpoints/responses/feeds.py index dea8ebf24..204d0b426 100644 --- a/backend/endpoints/responses/feeds.py +++ b/backend/endpoints/responses/feeds.py @@ -44,7 +44,7 @@ WEBRCADE_SUPPORTED_PLATFORM_SLUGS = frozenset( ) ) -WEBRCADE_SLUG_TO_TYPE_MAP = { +WEBRCADE_SLUG_TO_TYPE_MAP: dict[str, str] = { UPS.ATARI2600: "2600", UPS.ATARI5200: "5200", UPS.ATARI7800: "7800", diff --git a/backend/endpoints/responses/notification_channel.py b/backend/endpoints/responses/notification_channel.py index ef1bc3982..4c7c3a46a 100644 --- a/backend/endpoints/responses/notification_channel.py +++ b/backend/endpoints/responses/notification_channel.py @@ -1,19 +1,27 @@ -from typing import Annotated, Literal, Self +from typing import Annotated, Literal, Self, TypeAlias -from pydantic import Field, field_validator +from pydantic import Field, StrictBool, field_validator +from handler.notification_channels import apprise_channel +from handler.notification_channels.apprise_channel import ( + AppriseField, + AppriseService, + FieldType, +) from handler.notification_channels.config import masked_url, read_config from models.notification import NotificationTopic from models.notification_channel import ( NOTIFICATION_CHANNEL_ADDRESS_MAX_LENGTH, NOTIFICATION_CHANNEL_CODE_MAX_LENGTH, + NOTIFICATION_CHANNEL_MAX_FIELDS, + NOTIFICATION_CHANNEL_MAX_LIST_ITEMS, NOTIFICATION_CHANNEL_NAME_MAX_LENGTH, NOTIFICATION_CHANNEL_SECRET_MAX_LENGTH, + NOTIFICATION_CHANNEL_SERVICE_MAX_LENGTH, NOTIFICATION_CHANNEL_URL_MAX_LENGTH, NotificationChannel, NotificationChannelMinLevel, NotificationChannelType, - WebhookFormat, ) from utils.validation import EMAIL_PATTERN @@ -22,11 +30,22 @@ from .base import BaseModel, UTCDatetime ChannelName = Annotated[ str, Field(min_length=1, max_length=NOTIFICATION_CHANNEL_NAME_MAX_LENGTH) ] -WebhookUrl = Annotated[ +ChannelUrl = Annotated[ str, Field(min_length=1, max_length=NOTIFICATION_CHANNEL_URL_MAX_LENGTH) ] ChannelSecret = Annotated[str, Field(max_length=NOTIFICATION_CHANNEL_SECRET_MAX_LENGTH)] EmailAddress = Annotated[str, Field(max_length=NOTIFICATION_CHANNEL_ADDRESS_MAX_LENGTH)] +AppriseServiceId = Annotated[ + str, Field(min_length=1, max_length=NOTIFICATION_CHANNEL_SERVICE_MAX_LENGTH) +] +_FieldText = Annotated[str, Field(max_length=NOTIFICATION_CHANNEL_URL_MAX_LENGTH)] +_FieldList = Annotated[ + list[_FieldText], Field(max_length=NOTIFICATION_CHANNEL_MAX_LIST_ITEMS) +] +AppriseFieldValue: TypeAlias = StrictBool | int | float | _FieldText | _FieldList +AppriseFields = Annotated[ + dict[str, AppriseFieldValue], Field(max_length=NOTIFICATION_CHANNEL_MAX_FIELDS) +] def _check_address(address: str | None) -> str | None: @@ -43,9 +62,13 @@ class NotificationChannelSchema(BaseModel): min_level: NotificationChannelMinLevel # None forwards every topic. topics: list[NotificationTopic] | None - # A webhook's URL with its token hidden, or an email address. + # The URL with its secrets hidden, or an email address. target: str - format: WebhookFormat | None + # An Apprise channel's; `fields` leaves its secrets out, `stored_secrets` names them. + service: str | None + service_name: str | None + fields: dict[str, AppriseFieldValue] | None + stored_secrets: list[str] | None has_secret: bool confirmed: bool last_delivered_at: UTCDatetime | None @@ -56,7 +79,19 @@ class NotificationChannelSchema(BaseModel): @classmethod def from_channel(cls, channel: NotificationChannel) -> Self: config = read_config(channel.config) - is_webhook = channel.type == NotificationChannelType.WEBHOOK + service = config.get("service") + stored_fields = config.get("fields", {}) + service_name, fields, stored_secrets = None, None, None + match channel.type: + case NotificationChannelType.APPRISE if service: + service_name, target = apprise_channel.describe(service, stored_fields) + fields, stored_secrets = apprise_channel.split_fields( + service, stored_fields + ) + case NotificationChannelType.WEBHOOK if config.get("url"): + target = masked_url(config["url"]) + case _: + target = config.get("address", "") return cls( id=channel.id, type=NotificationChannelType(channel.type), @@ -68,12 +103,11 @@ class NotificationChannelSchema(BaseModel): if channel.topics is not None else None ), - target=( - masked_url(config["url"]) - if is_webhook and "url" in config - else config.get("address", "") - ), - format=config.get("format") if is_webhook else None, + target=target, + service=service, + service_name=service_name, + fields=fields, + stored_secrets=stored_secrets, has_secret=bool(config.get("secret")), confirmed=channel.confirmed_at is not None, last_delivered_at=channel.last_delivered_at, @@ -88,12 +122,18 @@ class _ChannelFilters(BaseModel): topics: list[NotificationTopic] | None = None +class AppriseChannelCreatePayload(_ChannelFilters): + type: Literal["apprise"] + name: ChannelName + service: AppriseServiceId + fields: AppriseFields + + class WebhookChannelCreatePayload(_ChannelFilters): type: Literal["webhook"] name: ChannelName - url: WebhookUrl - format: WebhookFormat = WebhookFormat.JSON - # The HMAC key of a JSON webhook, or an ntfy access token. + url: ChannelUrl + # The key the payload is signed with. secret: ChannelSecret | None = None @@ -106,7 +146,9 @@ class EmailChannelCreatePayload(_ChannelFilters): NotificationChannelCreatePayload = Annotated[ - WebhookChannelCreatePayload | EmailChannelCreatePayload, + AppriseChannelCreatePayload + | WebhookChannelCreatePayload + | EmailChannelCreatePayload, Field(discriminator="type"), ] @@ -118,10 +160,11 @@ class NotificationChannelUpdatePayload(BaseModel): enabled: bool | None = None min_level: NotificationChannelMinLevel | None = None topics: list[NotificationTopic] | None = None - url: WebhookUrl | None = None - format: WebhookFormat | None = None + url: ChannelUrl | None = None secret: ChannelSecret | None = None address: EmailAddress | None = None + # An Apprise channel's fields; a secret left out keeps its value, an empty one goes. + fields: AppriseFields | None = None check_address = field_validator("address")(_check_address) @@ -130,6 +173,66 @@ class NotificationChannelCodePayload(BaseModel): code: str = Field(min_length=1, max_length=NOTIFICATION_CHANNEL_CODE_MAX_LENGTH) +class AppriseFieldSchema(BaseModel): + key: str + label: str + type: FieldType + required: bool + private: bool + # Sent as an option rather than as part of the address. + advanced: bool + default: AppriseFieldValue | None + # A choice's values, as text: that is how they sit in the URL. + values: list[str] | None + min: float | None + max: float | None + + @classmethod + def from_field(cls, field: AppriseField) -> Self: + return cls( + key=field.key, + label=field.label, + type=field.type, + required=field.required, + private=field.private, + advanced=field.advanced, + default=field.default, + values=[str(value) for value in field.values] if field.values else None, + min=field.min, + max=field.max, + ) + + +class AppriseServiceSchema(BaseModel): + id: str + name: str + setup_url: str | None + # The fields the URL a service gives out fills in; empty without one. + url_fields: list[str] + fields: list[AppriseFieldSchema] + + @classmethod + def from_service(cls, service: AppriseService) -> Self: + return cls( + id=service.id, + name=service.name, + setup_url=service.setup_url, + url_fields=list(service.url_fields), + fields=[AppriseFieldSchema.from_field(field) for field in service.fields], + ) + + +class AppriseUrlPayload(BaseModel): + url: ChannelUrl + + +class AppriseUrlFieldsSchema(BaseModel): + """The service a pasted URL is for, and the fields it fills in.""" + + service: str + fields: dict[str, AppriseFieldValue] + + class NotificationChannelTestResult(BaseModel): ok: bool error: str | None diff --git a/backend/endpoints/responses/platform.py b/backend/endpoints/responses/platform.py index 7cdf8aa34..2f05ee468 100644 --- a/backend/endpoints/responses/platform.py +++ b/backend/endpoints/responses/platform.py @@ -41,14 +41,14 @@ class PlatformSchema(BaseModel): is_identified: bool missing_from_fs: bool - @computed_field # type: ignore + @computed_field # type: ignore[prop-decorator] @property def display_name(self) -> str: return self.custom_name or self.name # Counts every row like `rom_count` does; callers wanting only usable # BIOS filter the `firmware` list that ships alongside it. - @computed_field # type: ignore + @computed_field # type: ignore[prop-decorator] @property def firmware_count(self) -> int: return len(self.firmware) diff --git a/backend/endpoints/responses/play_session.py b/backend/endpoints/responses/play_session.py index 2dd961739..9f0b80373 100644 --- a/backend/endpoints/responses/play_session.py +++ b/backend/endpoints/responses/play_session.py @@ -13,7 +13,6 @@ class PlaySessionSchema(BaseModel): user_id: int device_id: str | None rom_id: int | None - sync_session_id: int | None save_slot: str | None start_time: datetime end_time: datetime diff --git a/backend/endpoints/responses/rom.py b/backend/endpoints/responses/rom.py index 158a115f5..412888a02 100644 --- a/backend/endpoints/responses/rom.py +++ b/backend/endpoints/responses/rom.py @@ -488,7 +488,7 @@ class SiblingRomSchema(BaseModel): fs_name_no_ext: str is_main_sibling: bool - @computed_field # type: ignore + @computed_field # type: ignore[prop-decorator] @property def sort_comparator(self) -> str: return ( diff --git a/backend/endpoints/responses/streaming.py b/backend/endpoints/responses/streaming.py index faa5723e9..5e6c09def 100644 --- a/backend/endpoints/responses/streaming.py +++ b/backend/endpoints/responses/streaming.py @@ -30,11 +30,18 @@ class StreamingContainerSchema(BaseModel): emulator: str supports_memory_cards: bool supports_save_picker: bool + supports_live_states: bool + import_kinds: list[Literal["save", "state"]] + """Which foreign-emulator picks the broker declares it can import, empty + when it declares none or cannot be asked.""" class StreamingConfigSchema(BaseModel): enabled: bool containers: list[StreamingContainerSchema] + emulator_labels: dict[str, str] + """Display name per emulator id, so a save or state tagged with one can be + labelled without a second copy of the map on the frontend.""" class SessionTerminationSchema(BaseModel): @@ -50,6 +57,9 @@ class SessionTerminationSchema(BaseModel): platform: str | None = None rom_id: int | None = None rom_name: str | None = None + container: str | None = None + claimed_at: str | None = None + desktop: bool = False class SessionStatusSchema(BaseModel): @@ -58,6 +68,9 @@ class SessionStatusSchema(BaseModel): extraction_phase: str | None = None """Set while a webstation broker unpacks a pkg or archive, which is the part of a launch long enough that the player needs to see something.""" + host: str | None = None + """The room URL of a launched session, for a tab that missed launch-ready, + reported by the status poll only and left None by a heartbeat.""" termination: SessionTerminationSchema | None = None @@ -78,18 +91,34 @@ class LaunchReadyPayload(BaseModel): platform: str container: str + claimed_at: str + """The claim's stamp, since a re-claim of the same container shares its key.""" host: str resume: bool | None = None """None when no resume was asked for; False means the state could not be pushed and the session started fresh.""" +class ImportRefusalSchema(BaseModel): + """One `.import/` member the broker's activate declined to place.""" + + reason: str + member: str | None = None + expected: str | None = None + detail: str | None = None + suggest_emulator: str | None = None + docs: str | None = None + + class LaunchFailedPayload(BaseModel): """`streaming:launch-failed`. The claim is already released.""" platform: str container: str + claimed_at: str detail: str + refusals: list[ImportRefusalSchema] | None = None + refusals_truncated: int = 0 class LaunchPhasePayload(BaseModel): @@ -97,9 +126,28 @@ class LaunchPhasePayload(BaseModel): platform: str container: str + claimed_at: str phase: str | None = None +class ContainerBusyDetail(BaseModel): + """The 409 body when a claim finds its container held.""" + + message: str + draining: bool + """A previous session is still shutting down, rather than anyone holding it.""" + rom_name: str | None + """The game holding it, None when the caller may not see which.""" + claimed_at: str | None + + +SOCKET_PAYLOADS: tuple[type[BaseModel], ...] = ( + LaunchReadyPayload, + LaunchFailedPayload, + LaunchPhasePayload, +) + + class DesktopSessionSchema(BaseModel): container: str platform: str @@ -117,7 +165,7 @@ class JoinedSessionSchema(BaseModel): class SaveAndExitResponse(BaseModel): - status: Literal["ok"] + status: Literal["ok", "not_found"] saved: bool platform: str released: bool @@ -223,6 +271,9 @@ class AdminContainerSchema(BaseModel): configured: bool """False for a container with no usable broker address: it can never be claimed, and saying so beats listing it as idle.""" + draining: bool = False + """The previous session's exit work is still running, so the container is + held by nobody and about to come free.""" session: ContainerSessionSchema | None = None diff --git a/backend/endpoints/responses/sync.py b/backend/endpoints/responses/sync.py index e89056132..54ed0d50e 100644 --- a/backend/endpoints/responses/sync.py +++ b/backend/endpoints/responses/sync.py @@ -1,32 +1,35 @@ -from typing import Literal - from pydantic import ConfigDict, Field +from handler.sync.comparison import SyncAction + from .base import BaseModel, UTCDatetime from .play_session import PlaySessionIngestResponse class SyncOperationSchema(BaseModel): - action: Literal["upload", "download", "conflict", "no_op"] = Field( + action: SyncAction = Field( description=( "Operation the client should perform. 'upload' when the client has a " "save the server lacks (including any null-slot save, which is never " "paired with server saves), 'download' when the server has a newer or " - "unknown save, 'conflict' when both sides changed independently, and " + "unknown save, 'conflict' when both sides changed independently, " + "'delete' when the slot the client still holds was emptied here, and " "'no_op' when no action is needed." ) ) rom_id: int = Field(description="ID of the ROM this operation applies to.") save_id: int | None = Field( default=None, - description="ID of the server save, if one exists (null for uploads).", + description=( + "ID of the server save, if one exists (null for uploads and deletes)." + ), ) file_name: str = Field(description="Name of the save file.") slot: str | None = Field( default=None, description=( - "Slot the operation applies to. Echoes the client slot for uploads; " - "for downloads and conflicts it is the server save's slot." + "Slot the operation applies to. Echoes the client slot for uploads " + "and deletes; for downloads and conflicts it is the server save's slot." ), ) emulator: str | None = Field( @@ -52,6 +55,7 @@ class SyncNegotiateResponse(BaseModel): total_download: int total_conflict: int total_no_op: int + total_delete: int class SyncSessionSchema(BaseModel): diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 0ed0cd6eb..08a714d1c 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -27,9 +27,6 @@ from fastapi import ( status, ) from fastapi.responses import Response -from fastapi_pagination import resolve_params -from fastapi_pagination.limit_offset import LimitOffsetParams -from fastapi_pagination.types import GreaterEqualZero from pydantic import BaseModel, Field from sqlalchemy.exc import IntegrityError from starlette.responses import FileResponse @@ -42,7 +39,7 @@ from config import ( ) from decorators.auth import protected_route from endpoints.responses import BulkOperationResponse -from endpoints.responses.base import TypedLimitOffsetPage +from endpoints.responses.base import PAGE_QUERY, LimitOffsetPage, PageParams from endpoints.responses.recommendation import SimilarRomSchema from endpoints.responses.rom import ( DetailedRomSchema, @@ -120,7 +117,7 @@ from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log from models.audit_event import AuditAction, AuditTargetType -from models.collection import VirtualCollection +from models.collection import Collection, SmartCollection, VirtualCollection from models.permission import PermAction, PermEntity from models.rom import ( HAS_FILE_ON_DISK_FILTERS, @@ -460,19 +457,12 @@ def parse_raw_metadata(form_data: RomUpdateForm, form_key: str) -> dict | None: return None -class CustomLimitOffsetParams(LimitOffsetParams): - # Temporarily increase the limit until we can implement pagination on all apps - limit: int = Query(50, ge=1, le=10_000, description="Page size limit") - offset: int = Query(0, ge=0, description="Page offset") - - -class CustomLimitOffsetPage[T: BaseModel](TypedLimitOffsetPage[T]): +class CustomLimitOffsetPage[T: BaseModel](LimitOffsetPage[T]): # Null when the caller opts out of the count with `with_total=false`. - total: GreaterEqualZero | None # type: ignore[assignment] + total: int | None = Field(ge=0) # type: ignore[assignment] char_index: dict[str, int] rom_id_index: list[int] filter_values: RomFiltersDict - __params_type__ = CustomLimitOffsetParams # Month 1-12 and day 1-31, so a match is already a calendar day. @@ -517,6 +507,7 @@ ROM_FILTER_QUERY = as_query_dependency(RomFilterParams) def get_roms( request: Request, filters: Annotated[RomFilterParams, Depends(ROM_FILTER_QUERY)], + params: Annotated[PageParams, Depends(PAGE_QUERY)], with_char_index: Annotated[ bool, Query(description="Whether to get the char index."), @@ -757,7 +748,6 @@ def get_roms( else None ) - params: CustomLimitOffsetParams = resolve_params() if with_rom_id_index: page_ids = list(rom_id_index[params.offset : params.offset + params.limit]) else: @@ -778,10 +768,11 @@ def get_roms( else: page_items = [] - return CustomLimitOffsetPage.create( - _transform(page_items), - params, + return CustomLimitOffsetPage( + items=_transform(page_items), total=resolve_total(), + limit=params.limit, + offset=params.offset, char_index=char_index_dict, rom_id_index=list(rom_id_index), filter_values=filter_values, @@ -883,6 +874,7 @@ def _bulk_download_target( return AuditTarget( AuditTargetType.VIRTUAL_COLLECTION, virtual_collection_id, name ) + collection: Collection | SmartCollection | None if collection_id: collection = db_collection_handler.get_collection(collection_id) elif smart_collection_id: diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index b606ea9c8..bce0109a8 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -17,6 +17,7 @@ from handler.asset_store import release_thumbnail, remove_asset_file, rename_ass from handler.auth.constants import Scope from handler.auth.dependencies import assert_rom_visible from handler.database import ( + db_deleted_asset_handler, db_device_handler, db_device_save_sync_handler, db_rom_handler, @@ -108,6 +109,19 @@ DATETIME_TAG_PATTERN = re.compile(r" \[\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\]") async def _delete_save(save: Save) -> None: """Drop a save row with its file and screenshot.""" + # Recorded first: a record for a save still present is never read, while + # a deletion with no record lets every device holding it offer it back. + if save.slot: + content_hash = save.content_hash or ( + await fs_asset_handler.compute_content_hash(save.full_path) + ) + if content_hash: + db_deleted_asset_handler.record_deletion( + user_id=save.user_id, + rom_id=save.rom_id, + slot=save.slot, + content_hash=content_hash, + ) db_save_handler.delete_save(save.id) await remove_asset_file(save.full_path, "Save file") await release_thumbnail(save.screenshot) diff --git a/backend/endpoints/sockets/logs.py b/backend/endpoints/sockets/logs.py index 5812189b8..4b56b29a3 100644 --- a/backend/endpoints/sockets/logs.py +++ b/backend/endpoints/sockets/logs.py @@ -18,14 +18,12 @@ from typing import Any, Final from config import DISABLE_LOGS_VIEWER from endpoints.sockets.activity import activity_on_disconnect, store_authenticated_user -from handler.database import db_user_handler from handler.redis_handler import async_cache from handler.socket_handler import socket_handler from logger.log_stream_handler import LOG_BUFFER_KEY, LOG_CHANNEL from logger.logger import log from models.user import Role from utils import json_module -from utils.auth import get_session_from_environ ADMIN_ROOM: Final = "admin" FORWARDER_LOCK_KEY: Final = "romm:logs:forwarder" @@ -45,16 +43,8 @@ async def connect(sid: str, environ: dict[str, Any], auth: Any = None) -> None: scan/sync sockets keep working for everyone. """ try: - session = await get_session_from_environ(environ) - if session.get("iss") != "romm:auth": - return - - username = session.get("sub") - if not username: - return - - user = db_user_handler.get_user_by_username(username) - if not user or not user.enabled: + user = await socket_handler.authenticate(sid, environ) + if user is None: return await store_authenticated_user(sid, user.id) @@ -62,10 +52,6 @@ async def connect(sid: str, environ: dict[str, Any], auth: Any = None) -> None: if not DISABLE_LOGS_VIEWER and user.role == Role.ADMIN: await socket_handler.socket_server.enter_room(sid, ADMIN_ROOM) - - session_id = session.get("session_id") - if session_id: - await socket_handler.bind_to_login_session(sid, session_id) except Exception: # noqa: BLE001 - never let auth resolution refuse a socket log.exception("Failed to resolve user on socket connect") diff --git a/backend/endpoints/sockets/netplay.py b/backend/endpoints/sockets/netplay.py index 0fcce4251..26ad383f8 100644 --- a/backend/endpoints/sockets/netplay.py +++ b/backend/endpoints/sockets/netplay.py @@ -1,8 +1,29 @@ -from typing import Any, NotRequired, TypedDict +"""Netplay rooms over Socket.IO, gated on the ROM being played. + +A guest may bypass that gate with the owner's room password. +""" + +from __future__ import annotations + +import secrets +from typing import TYPE_CHECKING, Any, NotRequired, TypedDict from endpoints.netplay import DEFAULT_MAX_PLAYERS +from handler.auth.constants import Scope +from handler.auth.permissions import resolve_permissions +from handler.database import db_rom_handler, db_user_handler from handler.netplay_handler import NetplayPlayerInfo, NetplayRoom, netplay_handler from handler.socket_handler import netplay_socket_handler +from logger.logger import log + +if TYPE_CHECKING: + from models.user import User + +# Session keys. The connect-time identity and the room membership share one +# server-side session dict, so every read goes through these names. +AUTH_USER_SESSION_KEY = "netplay_auth_user_id" +ROOM_SESSION_KEY = "session_id" +PLAYER_SESSION_KEY = "player_id" class RoomDataExtra(TypedDict): @@ -13,12 +34,106 @@ class RoomDataExtra(TypedDict): game_id: NotRequired[str] domain: NotRequired[str] player_name: NotRequired[str] - room_password: NotRequired[str] class RoomData(TypedDict): extra: RoomDataExtra maxPlayers: NotRequired[int] + password: NotRequired[str] + + +class WebRTCSignalData(TypedDict, total=False): + target: str + candidate: Any + offer: Any + answer: Any + requestRenegotiate: bool + + +async def _save_session(sid: str, values: dict[str, Any]) -> None: + session = await netplay_socket_handler.get_session(sid) + session.update(values) + await netplay_socket_handler.socket_server.save_session(sid, session) + + +async def _authenticated_user(sid: str) -> User | None: + """The connect-time user, reloaded per call so a disable lands without a reconnect.""" + user_id = (await netplay_socket_handler.get_session(sid)).get(AUTH_USER_SESSION_KEY) + if user_id is None: + return None + + user = db_user_handler.get_user(int(user_id)) + if not user or not user.enabled: + return None + return user + + +async def _playable_rom_id(sid: str, game_id: Any) -> int | None: + """The ROM id if the socket's user passes the gate the ROM endpoints apply, else None.""" + user = await _authenticated_user(sid) + if user is None or Scope.ROMS_READ not in user.oauth_scopes: + return None + + try: + rom_id = int(game_id) + except (TypeError, ValueError): + return None + + rom = db_rom_handler.get_rom_visibility(rom_id) + if rom is None or not resolve_permissions(user).can_see_rom( + rom.id, rom.platform_id + ): + return None + return rom.id + + +def _room_password(data: RoomData) -> str | None: + """The room password, which EmulatorJS sends beside ``extra`` rather than in it.""" + password = data.get("password") + return password if isinstance(password, str) and password else None + + +def _password_matches(expected: str, supplied: str | None) -> bool: + return supplied is not None and secrets.compare_digest( + expected.encode(), supplied.encode() + ) + + +def _socket_room(session_id: str) -> str: + """Prefixed, so a client-chosen room id cannot name another socket's own room.""" + return f"netplay-room:{session_id}" + + +@netplay_socket_handler.socket_server.on("connect") +async def connect(sid: str, environ: dict[str, Any], auth: Any = None) -> None: + """Accept every socket, since guests join by password, storing the session's user.""" + try: + user = await netplay_socket_handler.authenticate(sid, environ) + if user is not None: + await _save_session(sid, {AUTH_USER_SESSION_KEY: user.id}) + except Exception: # noqa: BLE001 - never let auth resolution refuse a socket + log.exception("Failed to resolve user on netplay connect") + + +def _player_info( + sid: str, extra_data: RoomDataExtra, player_id: str +) -> NetplayPlayerInfo: + return NetplayPlayerInfo( + socketId=sid, + player_name=str(extra_data.get("player_name") or f"Player {player_id}"), + userid=extra_data.get("userid"), + playerId=extra_data.get("playerId"), + ) + + +async def _enter_room(sid: str, session_id: str, player_id: str, room: NetplayRoom): + 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} + ) + await netplay_socket_handler.socket_server.emit( + "users-updated", room["players"], room=_socket_room(session_id) + ) @netplay_socket_handler.socket_server.on("open-room") @@ -31,39 +146,33 @@ async def open_room(sid: str, data: RoomData): if not session_id or not player_id: return "Invalid data: sessionId and playerId required" + rom_id = await _playable_rom_id(sid, extra_data.get("game_id")) + if rom_id is None: + log.warning("Netplay room creation rejected: not authorized for this rom") + return "Not authorized to open a room for this game" + + await leave_room(sid) + if await netplay_handler.get(session_id): return "Room already exists" + # A malformed value would break the room listing for everyone on this ROM. + max_players = data.get("maxPlayers") + if not isinstance(max_players, int) or max_players < 1: + max_players = DEFAULT_MAX_PLAYERS + new_room = NetplayRoom( owner=sid, - players={ - player_id: NetplayPlayerInfo( - socketId=sid, - player_name=extra_data.get("player_name") or f"Player {player_id}", - userid=extra_data.get("userid"), - playerId=extra_data.get("playerId"), - ) - }, + players={player_id: _player_info(sid, extra_data, player_id)}, peers=[], - room_name=extra_data.get("room_name") or f"Room {session_id}", - game_id=extra_data.get("game_id") or "default", + room_name=str(extra_data.get("room_name") or f"Room {session_id}"), + game_id=str(rom_id), domain=extra_data.get("domain", None), - password=extra_data.get("room_password", None), - max_players=data.get("maxPlayers") or DEFAULT_MAX_PLAYERS, + password=_room_password(data), + max_players=max_players, ) await netplay_handler.set(session_id, new_room) - - await netplay_socket_handler.socket_server.enter_room(sid, session_id) - await netplay_socket_handler.socket_server.save_session( - sid, - { - "session_id": session_id, - "player_id": player_id, - }, - ) - await netplay_socket_handler.socket_server.emit( - "users-updated", new_room["players"], room=session_id - ) + await _enter_room(sid, session_id, player_id, new_room) @netplay_socket_handler.socket_server.on("join-room") @@ -76,41 +185,45 @@ async def join_room(sid: str, data: RoomData): if not session_id or not player_id: return "Invalid data: sessionId and playerId required" + # Before the lookup, so rejoining the current room reads it without this socket. + await leave_room(sid) + current_room = await netplay_handler.get(session_id) if not current_room: return "Room not found" - if current_room["password"] and current_room["password"] != extra_data.get( - "room_password" - ): - return "Incorrect password" + # A password room admits whoever has the password, any other needs the ROM. + if current_room["password"]: + if not _password_matches(current_room["password"], _room_password(data)): + return "Incorrect password" + elif await _playable_rom_id(sid, current_room["game_id"]) is None: + log.warning("Netplay join rejected: not authorized for this rom") + return "Not authorized to join this room" - if len(current_room["players"].keys()) >= current_room["max_players"]: + if player_id in current_room["players"]: + return "Player already in room" + + if len(current_room["players"]) >= current_room["max_players"]: return "Room is full" - current_room["players"][player_id] = NetplayPlayerInfo( - socketId=sid, - player_name=extra_data.get("player_name") or f"Player {player_id}", - userid=extra_data.get("userid"), - playerId=extra_data.get("playerId"), - ) + current_room["players"][player_id] = _player_info(sid, extra_data, player_id) await netplay_handler.set(session_id, current_room) - - await netplay_socket_handler.socket_server.enter_room(sid, session_id) - await netplay_socket_handler.socket_server.save_session( - sid, - { - "session_id": session_id, - "player_id": player_id, - }, - ) - await netplay_socket_handler.socket_server.emit( - "users-updated", current_room["players"], room=session_id - ) + await _enter_room(sid, session_id, player_id, current_room) return None, current_room["players"] +async def _is_room_peer(sid: str, target: str) -> bool: + """Whether ``sid`` and ``target`` are both players in the caller's room.""" + session_id = (await netplay_socket_handler.get_session(sid)).get(ROOM_SESSION_KEY) + room = await netplay_handler.get(session_id) if session_id else None + if not room: + return False + + peers = {player["socketId"] for player in room["players"].values()} + return sid in peers and target in peers + + async def _handle_leave(sid: str, session_id: str, player_id: str): current_room = await netplay_handler.get(session_id) if not current_room: @@ -120,69 +233,54 @@ async def _handle_leave(sid: str, session_id: str, player_id: str): if not current_room["players"]: await netplay_handler.delete([session_id]) - # Notify clients that the room is now empty await netplay_socket_handler.socket_server.emit( - "users-updated", {}, room=session_id + "users-updated", {}, room=_socket_room(session_id) ) return if sid == current_room["owner"]: - # Owner left, assign a new one - remaining_players = list(current_room["players"].values()) - if remaining_players: - current_room["owner"] = remaining_players[0]["socketId"] + current_room["owner"] = next(iter(current_room["players"].values()))["socketId"] await netplay_handler.set(session_id, current_room) await netplay_socket_handler.socket_server.emit( - "users-updated", current_room["players"], room=session_id + "users-updated", current_room["players"], room=_socket_room(session_id) ) @netplay_socket_handler.socket_server.on("leave-room") -async def leave_room(sid: str): - stored_session = await netplay_socket_handler.socket_server.get_session(sid) - session_id = stored_session.get("session_id") - player_id = stored_session.get("player_id") +async def leave_room(sid: str) -> None: + session = await netplay_socket_handler.get_session(sid) + session_id = session.pop(ROOM_SESSION_KEY, None) + player_id = session.pop(PLAYER_SESSION_KEY, None) if session_id and player_id: await _handle_leave(sid, session_id, player_id) - await netplay_socket_handler.socket_server.leave_room(sid, session_id) - - -class WebRTCSignalData(TypedDict, total=False): - target: str - candidate: Any - offer: Any - answer: Any - requestRenegotiate: bool + await netplay_socket_handler.socket_server.leave_room( + sid, _socket_room(session_id) + ) + await netplay_socket_handler.socket_server.save_session(sid, session) @netplay_socket_handler.socket_server.on("webrtc-signal") async def webrtc_signal(sid: str, data: WebRTCSignalData): target = data.get("target") - request_renegotiate = data.get("requestRenegotiate", False) + # Signals relay only between peers of one room, so a client cannot inject an + # offer or answer into a session it never joined. + if not target or not await _is_room_peer(sid, target): + log.warning("Netplay signal to a non-peer rejected") + return - if request_renegotiate: - if not target: - return - await netplay_socket_handler.socket_server.emit( - "webrtc-signal", - {"sender": sid, "requestRenegotiate": True}, - to=target, - ) - else: - if not target: - return # drop message, no recipient - await netplay_socket_handler.socket_server.emit( - "webrtc-signal", - { - "sender": sid, - "candidate": data.get("candidate"), - "offer": data.get("offer"), - "answer": data.get("answer"), - }, - to=target, - ) + payload: dict[str, Any] = ( + {"sender": sid, "requestRenegotiate": True} + if data.get("requestRenegotiate", False) + else { + "sender": sid, + "candidate": data.get("candidate"), + "offer": data.get("offer"), + "answer": data.get("answer"), + } + ) + await netplay_socket_handler.socket_server.emit("webrtc-signal", payload, to=target) @netplay_socket_handler.socket_server.on("webrtc-signal-error") @@ -192,20 +290,15 @@ async def webrtc_signal_error(_sid: str, _error: str, _data: Any): @netplay_socket_handler.socket_server.on("disconnect") async def disconnect(sid: str): - stored_session = await netplay_socket_handler.socket_server.get_session(sid) - session_id = stored_session.get("session_id") - player_id = stored_session.get("player_id") - - if session_id and player_id: - await _handle_leave(sid, session_id, player_id) + await netplay_socket_handler.unbind_from_login_session(sid) + await leave_room(sid) async def _broadcast_to_room(sid: str, event: str, data: Any): - stored_session = await netplay_socket_handler.socket_server.get_session(sid) - session_id = stored_session.get("session_id") + session_id = (await netplay_socket_handler.get_session(sid)).get(ROOM_SESSION_KEY) if session_id: await netplay_socket_handler.socket_server.emit( - event, data, room=session_id, skip_sid=sid + event, data, room=_socket_room(session_id), skip_sid=sid ) diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 2523d909b..42b0aa3b9 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -25,6 +25,7 @@ from endpoints.responses.streaming import ( AdminContainersResponse, AdminSessionSchema, AdminSessionsResponse, + ContainerBusyDetail, ContainerSessionSchema, DesktopSessionSchema, ForceReleaseResponse, @@ -58,6 +59,7 @@ from handler.streaming import ( access, background, commands, + imports, languages, launch, lifecycle, @@ -77,7 +79,8 @@ from handler.streaming.config import ( container_for_session, containers_by_key, containers_for_platform, - resolve_containers, + emulator_labels, + first_claim_targets, streaming_enabled, ) from handler.streaming.protocol import room_url_on @@ -88,23 +91,28 @@ from handler.streaming.session_store import ( claim_drain_marker, claim_gate, clear_termination, + get_abandoned_session, get_live_session, get_session, get_termination, + hold_session_claim, iter_live_sessions, iter_session_keys, mutate_session, record_termination, refresh_session, release_own_session, + same_claim, session_disc_id, + session_is_desktop, session_is_stale, + session_platform_matches, session_redis_key, set_session_disc, stamp_launched, ) from logger.logger import log -from models.assets import MemoryCard, MemoryCardVersion, Save +from models.assets import MemoryCard, MemoryCardVersion, Save, State from models.rom import Rom from models.user import Role from utils.m3u import playlist_files @@ -167,11 +175,21 @@ class LoadStateRequest(BaseModel): slot: Annotated[int, Field(ge=1, le=MAX_SLOT)] = 1 +CONTAINER_KEY_MAX_LENGTH = 300 +CLAIMED_AT_MAX_LENGTH = 64 + +# A claim is named by its container and the stamp it was taken at. +ContainerQuery = Annotated[ + str | None, Query(alias="container", max_length=CONTAINER_KEY_MAX_LENGTH) +] +ClaimedAtQuery = Annotated[str | None, Query(max_length=CLAIMED_AT_MAX_LENGTH)] + + class DesktopStreamingSessionRequest(BaseModel): # The container to open, named by the key GET /streaming/containers # reports. Named rather than pooled: an admin configuring a container # needs that one, not whichever is free. - container: Annotated[str, Field(min_length=1, max_length=300)] + container: Annotated[str, Field(min_length=1, max_length=CONTAINER_KEY_MAX_LENGTH)] def platform_capabilities(platform: str) -> PlatformCapabilities: @@ -202,9 +220,12 @@ async def _session_status( platform: str, request: Request, candidates: list[ResolvedContainer] | None = None, + *, + include_desktop: bool = False, + claimed_at: str | None = None, ) -> dict[str, Any]: - """Whether the caller holds a session among `candidates` (the platform's first - pool by default), and if not, why it ended. Read-only, so it is safe to poll.""" + """Whether the caller holds this platform's session among `candidates` (its + first pool by default) and, if not, why it ended, read-only so safe to poll.""" if candidates is None: candidates = containers_for_platform(platform) if not candidates: @@ -212,10 +233,22 @@ async def _session_status( status_code=404, detail=f"No streaming container configured for platform '{platform}'", ) - found = await access.find_session_for_user(candidates, request.user.id) + found = await access.find_session_for_user( + candidates, + request.user.id, + platform=platform, + include_desktop=include_desktop, + claimed_at=claimed_at, + ) if found is not None: container, _, session = found - status: dict[str, Any] = {"status": "active", "platform": platform} + status: dict[str, Any] = { + "status": "active", + "platform": platform, + # The room the launch answered with, so a tab that missed the + # launch-ready push can enter the stream off a poll. + "host": session.get("host"), + } # An activate that has not returned yet leaves no launched_at behind. # Gating the broker round trip on it keeps this route pure Redis for # the rest of the session, which is the part that gets polled forever. @@ -228,11 +261,14 @@ async def _session_status( ) return status # The tombstone is keyed per container, so with a pool the caller's notice - # can sit under any of them. + # can sit under any of them, and another claim's is not the answer. termination = None for candidate in candidates: - termination = await get_termination(candidate.key, request.user.id) - if termination is not None: + notice = await get_termination(candidate.key, request.user.id) + if notice is not None and access.session_in_scope( + notice, platform, include_desktop, claimed_at + ): + termination = notice break return { "status": "ended", @@ -255,36 +291,53 @@ def _joinable_container_label( @protected_route(router.get, "/config", [Scope.ROMS_READ]) async def get_config(request: Request) -> StreamingConfigSchema: """Return streaming configuration to the frontend""" - # Keyed by platform: a pool is a backend concern, the frontend picks a + # One row per platform: a pool is a backend concern, the frontend picks a # platform and the claim decides which container serves it. - safe_containers: dict[str, StreamingContainerSchema] = {} - for c in resolve_containers(): - if c.platform in safe_containers: - continue - # The record carries the platform's label and capabilities, so a - # platform hidden from this caller must not be listed here either. - if not access.platform_is_visible(request, c.platform): - continue - safe_containers[c.platform] = StreamingContainerSchema( - platform=c.platform, - host=c.host, - label=c.label, - # Ship slot capabilities so the frontend selector reads them - # instead of keeping its own hardcoded per-platform copy. - capabilities=SlotCapabilitiesSchema(**c.capabilities), - # State namespace for this container, so the frontend can - # filter the resume picker the same way hydration filters. - emulator=c.emulator, - # Whether this container syncs whole memory cards, so the - # frontend only offers the card picker where it applies. - supports_memory_cards=c.memory_card_sync, - # Whether an older save archive still lands here, so the frontend - # only offers the save picker where a pick means something. - supports_save_picker=c.supports_save_picker, + # The record carries the platform's label and capabilities, so a + # platform hidden from this caller must not be listed here either. + visible = [ + c + for c in first_claim_targets() + if access.platform_is_visible(request, c.platform) + ] + # Concurrently, so one unreachable broker costs one timeout, not one each. + specs = await asyncio.gather( + *( + asyncio.to_thread(webstation.import_spec, c, c.emulator, c.platform) + for c in visible + ) + ) + safe_containers: list[StreamingContainerSchema] = [] + for c, spec in zip(visible, specs, strict=True): + safe_containers.append( + StreamingContainerSchema( + platform=c.platform, + host=c.host, + label=c.label, + # Ship slot capabilities so the frontend selector reads them + # instead of keeping its own hardcoded per-platform copy. + capabilities=SlotCapabilitiesSchema(**c.capabilities), + # State namespace for this container, so the frontend can + # filter the resume picker the same way hydration filters. + emulator=c.emulator, + # Whether this container syncs whole memory cards, so the + # frontend only offers the card picker where it applies. + supports_memory_cards=c.memory_card_sync, + # Whether an older save archive still lands here, so the frontend + # only offers the save picker where a pick means something. + supports_save_picker=c.supports_save_picker, + # Whether the in-game Save and Load buttons reach a broker that + # honours them, which an exit-state emulator's does not. + supports_live_states=c.supports_live_states, + # So the picker only offers a foreign pick the claim will take. + import_kinds=spec.pickable_kinds() if spec is not None else [], + ) ) return StreamingConfigSchema( - enabled=streaming_enabled(), containers=list(safe_containers.values()) + enabled=streaming_enabled(), + containers=safe_containers, + emulator_labels=emulator_labels(), ) @@ -309,12 +362,12 @@ async def _win_container( if not entered: raise HTTPException( status_code=409, - detail={ - "message": "You already have a session on this platform", - "draining": False, - "rom_name": None, - "claimed_at": None, - }, + detail=ContainerBusyDetail( + message="You already have a session on this platform", + draining=False, + rom_name=None, + claimed_at=None, + ).model_dump(), ) return await _reserve_container(request, candidates, session, platform) @@ -326,24 +379,26 @@ async def _reserve_container( platform: str, ) -> ResolvedContainer: """Walk the platform's containers and claim the first one available.""" - # Status, heartbeat and release all resolve by platform and answer with the - # first match, so a second session for one user is one nothing can reach. - held = await access.find_session_for_user(candidates, request.user.id) + # Status, heartbeat and release reach one session per platform, so a second + # is unreachable. One elsewhere is no bar: its container fails the claim below. + held = await access.find_session_for_user( + candidates, request.user.id, platform=platform + ) if held is not None: - holder, _, mine = held + own_container, _, mine = held if not session_is_stale(mine): raise HTTPException( status_code=409, - detail={ - "message": "You already have a session on this platform", - "draining": False, - "rom_name": access.visible_rom_name(request, mine), - "claimed_at": mine.get("claimed_at"), - }, + detail=ContainerBusyDetail( + message="You already have a session on this platform", + draining=False, + rom_name=access.visible_rom_name(request, mine), + claimed_at=mine.get("claimed_at"), + ).model_dump(), ) # Their own session, abandoned. Take that container back rather than # rolling them onto a free one and stranding this one until its TTL. - candidates = [holder] + candidates = [own_container] async def try_claim(candidate: ResolvedContainer) -> bool: # SET NX is atomic: exactly one concurrent claim wins the key. The TTL @@ -374,52 +429,64 @@ async def _reserve_container( # backend doing it is what refreshes it. deadline = time.monotonic() + lifecycle.ABANDONED_TEARDOWN_WAIT for candidate in candidates: - existing = await get_session(candidate.key) - if ( - existing is None - or existing.get("draining") - or not session_is_stale(existing) - ): + existing = await get_abandoned_session(candidate.key) + if existing is None: continue log.warning( "taking over stale session, platform=%s user_id=%s", platform, existing.get("user_id"), ) + # A container serves several platforms, so the swept session may be another + # one's, and its state, saves and card belong to that platform's emulator. + record = ( + container_for_session( + containers_by_key(), candidate.key, existing.get("platform") + ) + or candidate + ) if not await lifecycle.await_teardown_within_budget( - candidate, + record, candidate.key, existing, max(0.0, deadline - time.monotonic()), + claimed_by=request.user.id, ): continue if await try_claim(candidate): return candidate - # Report the head of the pool as the holder: with one container that is the - # only holder, and with several the player just needs to know the platform - # is busy. - existing = await get_session(candidates[0].key) or {} - # A drain marker belongs to nobody: the previous session is over and its - # exit state is still coming out of the container, so rom_name and - # claimed_at are both blank and "in use" would name no one. The player who - # just pressed save-and-exit sees this, and needs to be told to wait rather - # than that somebody else took their platform. - draining = bool(existing.get("draining")) + # A drain marker names no holder, so the holder comes from a live session, + # while `draining` still says a container is about to come free. + snapshots = [ + snapshot or {} + for snapshot in await asyncio.gather( + *(get_session(candidate.key) for candidate in candidates) + ) + ] + draining = any(snapshot.get("draining") for snapshot in snapshots) + holder = next( + ( + snapshot + for snapshot in snapshots + if snapshot and not snapshot.get("draining") + ), + {}, + ) if draining: - message = "The previous session is still saving, try again shortly" + message = "The previous session is still shutting down, try again shortly" elif len(candidates) == 1: message = "Session in use" else: message = f"All {len(candidates)} containers for this platform are in use" raise HTTPException( status_code=409, - detail={ - "message": message, - "draining": draining, - "rom_name": access.visible_rom_name(request, existing), - "claimed_at": existing.get("claimed_at"), - }, + detail=ContainerBusyDetail( + message=message, + draining=draining, + rom_name=access.visible_rom_name(request, holder), + claimed_at=holder.get("claimed_at"), + ).model_dump(), ) @@ -586,12 +653,18 @@ async def _hydrate_saves( card: MemoryCard | None, blank_card_id: int | None, save: Save | None = None, -) -> str | None: + save_foreign: bool = False, + import_state: State | None = None, +) -> imports.ImportHydration: """Put the player's save data on the container before the game reads it. Games read saves at boot, so unlike states this cannot be deferred to a - background task. Returns the container path of an uploaded archive, for the - protocols that restore one as part of the launch. + background task. + + Returns: + The container path of an uploaded archive (for the protocols that + restore one as part of the launch), and whether `import_state` + specifically made it onto the container. """ if card is not None: # Whole-card sync: hydrate (or wipe to blank) is REQUIRED. If it fails @@ -611,15 +684,37 @@ async def _hydrate_saves( ) if container.is_webstation: + if save_foreign or import_state is not None: + # A synced memory card is not special-cased: the broker refuses it + # with memcard_synced_separately. + try: + result = await imports.hydrate_import_archive( + request.user.id, + rom, + container, + save=save, + save_is_foreign=save_foreign, + state=import_state, + ) + except Exception: + log.exception("import archive hydration failed, continuing launch") + result = imports.ImportHydration() + if result.path is not None: + return result + if save_foreign: + # A foreign save has no native side to fall back to. + return imports.ImportHydration() + # Only the foreign state failed, so any native save still hydrates. # Restore runs inside activate on this protocol, so hydration only gets # the bytes onto the container and names the path activate restores. # Still runs under whole-card sync: the archive carries the state the # last session ended on, which the card does not. # Best-effort: a failed upload just means the container keeps its own. try: - return await saves.hydrate_saves_to_webstation( + path = await saves.hydrate_saves_to_webstation( request.user.id, rom.id, container, save ) + return imports.ImportHydration(path) except Exception: log.exception("save hydration failed, continuing launch") elif card is None: @@ -629,7 +724,7 @@ async def _hydrate_saves( await saves.hydrate_saves_to_broker(request.user.id, rom.id, container) except Exception: log.exception("save hydration failed, continuing launch") - return None + return imports.ImportHydration() @protected_route( @@ -638,7 +733,10 @@ async def _hydrate_saves( [Scope.ROMS_USER_WRITE], # The prompt for a card the container still holds is a real body the client # parses, so it is declared rather than left as an undocumented `detail`. - responses={428: {"model": MemoryCardImportRequired}}, + responses={ + 409: {"model": ContainerBusyDetail}, + 428: {"model": MemoryCardImportRequired}, + }, status_code=202, ) async def claim_session( @@ -687,17 +785,20 @@ async def claim_session( # leave a container wedged behind a failed launch. resume_state = None resume_slot: int | None = None + resume_foreign = False if req.state_id is not None: - resume_state, resume_slot = states.resolve_resume_state( - request.user.id, rom, reference, req.state_id + # Off the event loop, since a foreign pick asks the broker synchronously. + resume_state, resume_slot, resume_foreign = await asyncio.to_thread( + states.resolve_resume_state, request.user.id, rom, reference, req.state_id ) # Same for the save pick: a save the player cannot restore here has to # fail before the container is reserved, not during the launch. picked_save = None + save_foreign = False if req.save_id is not None: - picked_save = saves.resolve_save_archive( - request.user.id, rom, reference, req.save_id + picked_save, save_foreign = await asyncio.to_thread( + saves.resolve_save_archive, request.user.id, rom, reference, req.save_id ) # Resolve the memory card to mount before claiming too, so a bad card id @@ -753,6 +854,57 @@ async def claim_session( container = await _win_container(request, candidates, session, platform) session_key = container.key + # On an archive-resume container (DuckStation, RPCS3) the save archive + # carries its own exit state, and only the newest archive carries the newest + # capture, so any other state and save pairing needs the state imported. + state_off_archive = False + if ( + resume_state is not None + and not resume_foreign + and container.resumes_from_archive + ): + newest_states = await asyncio.to_thread( + states.user_states_for_emulator, request.user.id, rom.id, container.emulator + ) + state_off_archive = not newest_states or newest_states[0].id != resume_state.id + if not state_off_archive and picked_save is not None: + newest_save = None + if not save_foreign: + newest_save = await asyncio.to_thread( + saves.newest_restorable, + request.user.id, + rom.id, + container.emulator, + ) + state_off_archive = newest_save is None or newest_save.id != picked_save.id + + # The pre-win checks asked the pool's reference; the won container's own + # import-spec is what decides, and one answer covers both picks. + spec = None + if resume_foreign or state_off_archive or save_foreign: + spec = await asyncio.to_thread( + webstation.import_spec, container, container.emulator, container.platform + ) + if resume_foreign: + import_slot = spec.resume_slot() if spec is not None else None + if import_slot is None: + await lifecycle.abort_claim(session_key, session) + raise HTTPException( + status_code=400, detail="This container cannot resume the picked state" + ) + resume_slot = import_slot + if save_foreign and (spec is None or not spec.accepts("save")): + await lifecycle.abort_claim(session_key, session) + raise HTTPException( + status_code=400, detail="This container cannot restore the picked save" + ) + resume_via_import = ( + (resume_foreign or state_off_archive) + and spec is not None + and spec.accepts("state") + and spec.state_channel == "archive" + ) + # The emulator containers mount the RomM library at the same path the # backend uses (LIBRARY_BASE_PATH, /romm/library by default), so the # backend-side path is valid inside the broker container too. If a @@ -762,39 +914,56 @@ async def claim_session( library_base = container.library_path rom_path = f"{library_base}/{rom.full_path}" - probe = await _probe_container_card(container, session, req.card_import) + # Nothing beats for the player until the stream is up, and on a slow + # container these steps can outlast the window after which a claim is stale. + claim_hold = asyncio.create_task(hold_session_claim(session_key, session)) + try: + probe = await _probe_container_card(container, session, req.card_import) - # The player is back in a session, so any note about their previous one - # being force-released has served its purpose. Cleared across the whole - # pool, not just the container just won: the notice is keyed by container, - # and one left on a sibling would be reported as the reason this session - # ended when it finally does. - for candidate in candidates: - await clear_termination(candidate.key, request.user.id) + # The player is back in a session, so any note about their previous one + # being force-released has served its purpose. Cleared across the whole + # pool, not just the container just won: the notice is keyed by container, + # and one left on a sibling would be reported as the reason this session + # ended when it finally does. + for candidate in candidates: + await clear_termination(candidate.key, request.user.id) - memory_card, created_blank_card_id = await _settle_memory_card( - request, container, session, memory_card, rom, probe - ) + memory_card, created_blank_card_id = await _settle_memory_card( + request, container, session, memory_card, rom, probe + ) - # Push the resume state before launch so its file is in place when the - # broker's deferred slot load fires. Best-effort: a failed push falls - # back to a fresh launch, reported through `resume` in the response. - # The webstation broker only takes a state while a session is up, and its - # session starts at activate, so that push has to happen after launch. - resume_pushed = False - resume_after_launch = container.is_webstation and resume_state is not None - if resume_state is not None and not resume_after_launch: - resume_pushed = await states.push_resume_state(container, resume_state) + # Push the resume state before launch so its file is in place when the + # broker's deferred slot load fires. Best-effort: a failed push falls + # back to a fresh launch, reported through `resume` in the response. + # The webstation broker only takes a state while a session is up, and its + # session starts at activate, so that push has to happen after launch. + resume_pushed = False + resume_after_launch = container.is_webstation and resume_state is not None + if resume_state is not None and not resume_after_launch: + resume_pushed = await states.push_resume_state(container, resume_state) - archive_path = await _hydrate_saves( - request, - container, - session, - rom, - memory_card, - created_blank_card_id, - picked_save, - ) + # The last exit's detached save pull may still be filing the archive to hydrate. + await saves.wait_for_save_pull(request.user.id, rom.id) + + archive_path, state_imported = await _hydrate_saves( + request, + container, + session, + rom, + memory_card, + created_blank_card_id, + picked_save, + save_foreign=save_foreign, + import_state=resume_state if resume_via_import else None, + ) + finally: + claim_hold.cancel() + resume_import: launch.ResumeImport = "none" + if resume_via_import: + resume_import = "imported" if state_imported else "lost" + elif state_off_archive: + # The archive would resume a state the player did not pick. + resume_import = "lost" # Detached because an activate blocks through pkg and archive extraction, # minutes on a large title, which no player can cancel out of. @@ -815,6 +984,7 @@ async def claim_session( resume_slot=resume_slot, resume_pushed=resume_pushed, resume_after_launch=resume_after_launch, + resume_import=resume_import, memory_card_synced=memory_card is not None, multiplayer=multiplayer, blank_card_id=created_blank_card_id, @@ -833,16 +1003,28 @@ async def claim_session( router.post, "/sessions/{platform}/save-and-exit", [Scope.ROMS_USER_WRITE] ) async def save_and_exit_session( - request: Request, platform: str, req: Annotated[SaveAndExitRequest, Body()] + request: Request, + platform: str, + req: Annotated[SaveAndExitRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> SaveAndExitResponse: + """Save game state then release the session. + + Args: + req: `wait` true (the default) blocks until the broker confirms the save + and kill, false has the broker do both in the background. + container_key: the claimed container, as on release. + claimed_at: the claim's stamp, as on release. """ - Save game state then release the session. - wait=true (default): blocks until broker confirms save+kill complete. - wait=false: broker fires save+kill in background, returns immediately. - """ - container, session_key, session = await access.resolve_owned_session( - platform, request + target = await access.resolve_claim( + platform, request, container_key, claimed_at, game_only=True ) + if target is None: + return SaveAndExitResponse( + status="not_found", saved=False, platform=platform, released=True + ) + container, session_key, session = target if req.slot: _assert_valid_slot(platform, req.slot) @@ -852,7 +1034,7 @@ async def save_and_exit_session( # still writing, and the wipe can race its exit flush. card_sync = container.memory_card_sync effective_wait = True if card_sync else req.wait - saved, effective_slot = await asyncio.to_thread( + saved, effective_slot, settled = await asyncio.to_thread( commands.save_and_exit, container, slot=req.slot, wait=effective_wait ) @@ -866,6 +1048,8 @@ async def save_and_exit_session( await lifecycle.record_play_session(session) await lifecycle.clear_session_activity(session_key, session) + # Before the key goes, so a claim that wins it next waits for the pull. + await lifecycle.start_exit_save_pull(container, session, settled=settled) # Sync the exit save to the library. With wait=false the broker save may # still be running; the pull blocks on the broker until it finishes. @@ -930,8 +1114,6 @@ async def save_and_exit_session( except StreamingSessionContended: released = False - lifecycle.collect_exit_saves(container, session) - if not released: log.error("save-and-exit could not give up session %s", session_key) log.info("save-and-exit, platform=%s saved=%s", platform, saved) @@ -946,65 +1128,85 @@ async def save_and_exit_session( async def heartbeat_session( request: Request, platform: str, - container_key: str | None = Query(default=None, alias="container", max_length=300), + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> SessionStatusSchema: - """Refresh the session's liveness stamp and report whether it still exists. + """Refresh the liveness stamp the frontend beats every ~30s, without which the + claim is abandoned after _STREAMING_SESSION_STALE_SECONDS for the next to take. - The frontend calls this every ~30s while a session is active. A session - that stops refreshing counts as abandoned after _STREAMING_SESSION_STALE_SECONDS - and the next claim may take the container over. + Args: + container_key: the claim to beat, needed for any desktop, or for a + container outside the platform's first pool. + claimed_at: the claim's stamp, so a tab that missed its own takeover does + not keep the claim that replaced it alive. - Reports `ended` rather than raising 404 when the caller no longer holds the - session, so a force-released player learns why on the poll they are already - making rather than watching a dead stream. - - `container` names the claim to refresh, needed for a desktop on a container - outside the platform's first pool. + Returns: + `ended` rather than a 404 once the caller no longer holds the session, so + a force-released player learns why on the poll they already make. """ user_id = request.user.id - # A named claim answers for itself: another session the caller holds on the - # platform is not the one this client is beating. + # A named claim answers for itself, and naming the container is the only way + # to reach a desktop, which a game tab must never beat. + named = container_key is not None candidates = ( [access.named_container(platform, container_key)] if container_key is not None else containers_for_platform(platform) ) - found = await access.find_session_for_user(candidates, user_id) - if found is None: - return SessionStatusSchema( - **await _session_status(platform, request, candidates) + found = await access.find_session_for_user( + candidates, + user_id, + platform=platform, + include_desktop=named, + claimed_at=claimed_at, + ) + if found is not None: + _, session_key, held = found + # Merging keeps a swap that landed since the read. Refusing a draining or + # re-claimed session returns None, so the client stops beating a dead claim. + try: + refreshed = await mutate_session( + session_key, + {"last_seen": datetime.now(timezone.utc).isoformat()}, + require=lambda s: same_claim(s, held), + ) + except StreamingSessionContended: + # A key too busy to write is a key that exists, so the session is live + # and the missed stamp is covered by the next beat. + log.warning("heartbeat could not stamp contended session %s", session_key) + return SessionStatusSchema(status="active", platform=platform) + if refreshed is not None: + await lifecycle.refresh_session_activity(session_key, refreshed) + return SessionStatusSchema(status="active", platform=platform) + return SessionStatusSchema( + **await _session_status( + platform, + request, + candidates, + include_desktop=named, + claimed_at=claimed_at, ) - _, session_key, _ = found - - # Merging keeps a swap that landed since the read. Refusing a draining or - # re-claimed session returns None, so the client stops beating a dead claim. - try: - refreshed = await mutate_session( - session_key, - {"last_seen": datetime.now(timezone.utc).isoformat()}, - require=lambda s: not s.get("draining") and s.get("user_id") == user_id, - ) - except StreamingSessionContended: - # A key too busy to write is a key that exists, so the session is live - # and the missed stamp is covered by the next beat. - log.warning("heartbeat could not stamp contended session %s", session_key) - return SessionStatusSchema(status="active", platform=platform) - if refreshed is None: - return SessionStatusSchema( - **await _session_status(platform, request, candidates) - ) - await lifecycle.refresh_session_activity(session_key, refreshed) - return SessionStatusSchema(status="active", platform=platform) + ) @protected_route(router.get, "/sessions/{platform}/status", [Scope.ROMS_READ]) -async def session_status(request: Request, platform: str) -> SessionStatusSchema: +async def session_status( + request: Request, + platform: str, + claimed_at: ClaimedAtQuery = None, +) -> SessionStatusSchema: """Does the caller still hold this platform's session? Unlike the heartbeat this has no side effects, so a client can call it on mount or after a reconnect without extending a claim it may not own. + + Args: + claimed_at: the claim's stamp, so a tab never adopts a claim that + replaced its own. """ - return SessionStatusSchema(**await _session_status(platform, request)) + return SessionStatusSchema( + **await _session_status(platform, request, claimed_at=claimed_at) + ) @protected_route(router.post, "/sessions/{platform}/join", [Scope.ROMS_READ]) @@ -1024,16 +1226,26 @@ async def join_session( candidate, _, session = await access.resolve_named_container( platform, container ) - found = (candidate, session) if session is not None else None + found = ( + (candidate, session) + if session is not None and session_platform_matches(session, platform) + else None + ) else: found = None for candidate in containers_for_platform(platform): session = await get_live_session(candidate.key) if session is None: continue - if session.get("multiplayer"): - found = (candidate, session) - break + if not session_platform_matches(session, platform): + continue + # A member the caller cannot join is not the answer and must not + # mask a later one that is. + joinable, _ = access.joinable_session_rom(request, session) + if not joinable: + continue + found = (candidate, session) + break if found is None: raise HTTPException( @@ -1074,10 +1286,16 @@ async def join_session( @protected_route(router.post, "/sessions/{platform}/volume", [Scope.ROMS_USER_WRITE]) async def set_volume( - request: Request, platform: str, req: Annotated[VolumeRequest, Body()] + request: Request, + platform: str, + req: Annotated[VolumeRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> VolumeResponse: """Set emulator audio volume (0-100).""" - container, session_key, _ = await access.resolve_owned_session(platform, request) + container, session_key, _ = await access.require_claim( + platform, request, container_key, claimed_at + ) ok = await asyncio.to_thread(commands.set_volume, container, req.level) if not ok: @@ -1089,10 +1307,16 @@ async def set_volume( @protected_route(router.post, "/sessions/{platform}/mute", [Scope.ROMS_USER_WRITE]) async def set_mute( - request: Request, platform: str, req: Annotated[MuteRequest, Body()] + request: Request, + platform: str, + req: Annotated[MuteRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> MuteResponse: """Toggle or explicitly set mute state. Omit body to toggle.""" - container, session_key, _ = await access.resolve_owned_session(platform, request) + container, session_key, _ = await access.require_claim( + platform, request, container_key, claimed_at + ) confirmed = await asyncio.to_thread(commands.set_mute, container, req.mute) if confirmed is None: @@ -1106,15 +1330,19 @@ async def set_mute( router.post, "/sessions/{platform}/save-state", [Scope.ROMS_USER_WRITE] ) async def save_state( - request: Request, platform: str, req: Annotated[SaveStateRequest, Body()] + request: Request, + platform: str, + req: Annotated[SaveStateRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> SaveStateResponse: """Save game state to a slot without stopping the emulator. The autosave slot is a valid target: the library keeps every capture, so the player writes through one slot rather than picking one. """ - container, session_key, session = await access.resolve_owned_session( - platform, request + container, session_key, session = await access.require_claim( + platform, request, container_key, claimed_at ) _assert_valid_slot(platform, req.slot) @@ -1145,10 +1373,16 @@ async def save_state( router.post, "/sessions/{platform}/load-state", [Scope.ROMS_USER_WRITE] ) async def load_state( - request: Request, platform: str, req: Annotated[LoadStateRequest, Body()] + request: Request, + platform: str, + req: Annotated[LoadStateRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> LoadStateResponse: """Load game state from a manual slot or the platform's autosave slot.""" - container, session_key, _ = await access.resolve_owned_session(platform, request) + container, session_key, _ = await access.require_claim( + platform, request, container_key, claimed_at + ) _assert_valid_slot(platform, req.slot) ok = await asyncio.to_thread(commands.load_state, container, req.slot) @@ -1161,11 +1395,15 @@ async def load_state( @protected_route(router.post, "/sessions/{platform}/swap-disc", [Scope.ROMS_USER_WRITE]) async def swap_disc( - request: Request, platform: str, req: Annotated[SwapDiscRequest, Body()] + request: Request, + platform: str, + req: Annotated[SwapDiscRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> SwapDiscResponse: """Change the mounted disc without restarting the emulator.""" - container, session_key, session = await access.resolve_owned_session( - platform, request + container, session_key, session = await access.require_claim( + platform, request, container_key, claimed_at ) # Container-scoped, not platform-scoped: only the webstation broker has a # tray route, so a legacy container serving this platform gets the same @@ -1208,38 +1446,27 @@ async def release_session( platform: str, background_tasks: BackgroundTasks, reason: str | None = Query(default=None, max_length=200), - container_key: str | None = Query(default=None, alias="container", max_length=300), + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, save: bool = Query(default=True), ) -> ReleaseSessionResponse: """Release a session and tell the broker to stop the emulator. - `reason` is only meaningful when an admin ends someone else's session; it - is surfaced to the displaced player. `container` names which container to - release, needed when a pool serves the platform and the admin is ending a - session they do not own; it is the key `GET /streaming/sessions` reports. - - `save=false` is a player leaving deliberately without saving. It defaults - on because the other way in here is a tab closing, where nobody chose - anything and the last minutes of play would otherwise be gone. + Args: + reason: why an admin ended someone else's session, shown to that player. + container_key: which pool member to release: the holder sends the one it + claimed, an admin the key `GET /streaming/sessions` reports. + claimed_at: the stamp binding this release to one claim; admin panels end + whatever is running and send none. + save: false for a player leaving deliberately without saving; on by + default because a closing tab chose nothing and would lose recent play. """ - if container_key is not None: - container, session_key, session = await access.resolve_named_container( - platform, container_key - ) - if session is None: - return ReleaseSessionResponse(status="not_found", platform=platform) - access.assert_session_owner(session, request) - else: - try: - container, session_key, session = await access.resolve_owned_session( - platform, request - ) - except HTTPException as exc: - # Nothing configured or nothing active: releasing is a no-op rather - # than an error, matching a repeated release from the same tab. - if exc.status_code != 404: - raise - return ReleaseSessionResponse(status="not_found", platform=platform) + target = await access.resolve_claim( + platform, request, container_key, claimed_at, game_only=False + ) + if target is None: + return ReleaseSessionResponse(status="not_found", platform=platform) + container, session_key, session = target # Teardown pulls the whole card off the broker and pushes a blank one back, # several seconds of broker round-trips. The player who quit does not need @@ -1276,7 +1503,11 @@ async def list_containers(request: Request) -> AdminContainersResponse: containers: list[AdminContainerSchema] = [] for container_key, entries in containers_by_key().items(): first = entries[0] - session = await get_live_session(container_key) if container_key else None + held = await get_session(container_key) if container_key else None + # A drain marker holds the key with no owner. Reported as its own state + # rather than as a session, since there is nobody to name or release. + draining = bool(held and held.get("draining")) + session = None if draining else held user_id = session.get("user_id") if session else None user = db_user_handler.get_user(user_id) if isinstance(user_id, int) else None containers.append( @@ -1289,12 +1520,13 @@ async def list_containers(request: Request) -> AdminContainersResponse: # A container whose host has no scheme has an empty key and can # never be claimed, so surface it rather than listing it as idle. configured=bool(container_key), + draining=draining, session=( ContainerSessionSchema( platform=session.get("platform"), rom_id=session.get("rom_id"), rom_name=session.get("rom_name"), - desktop=bool(session.get("desktop")), + desktop=session_is_desktop(session), claimed_at=session.get("claimed_at"), user_id=user_id, username=user.username if user else None, @@ -1307,7 +1539,12 @@ async def list_containers(request: Request) -> AdminContainersResponse: return AdminContainersResponse(enabled=streaming_enabled(), containers=containers) -@protected_route(router.post, "/desktop", [Scope.ROMS_USER_WRITE]) +@protected_route( + router.post, + "/desktop", + [Scope.ROMS_USER_WRITE], + responses={409: {"model": ContainerBusyDetail}}, +) async def claim_desktop_session( request: Request, req: Annotated[DesktopStreamingSessionRequest, Body()] ) -> DesktopSessionSchema: @@ -1360,11 +1597,14 @@ async def claim_desktop_session( existing = await get_session(session_key) or {} raise HTTPException( status_code=409, - detail={ - "message": "Container in use", - "rom_name": access.visible_rom_name(request, existing), - "claimed_at": existing.get("claimed_at"), - }, + detail=ContainerBusyDetail( + message="Container in use", + # A drain marker means the previous session is still shutting + # down, not that anyone holds it. + draining=bool(existing.get("draining")), + rom_name=access.visible_rom_name(request, existing), + claimed_at=existing.get("claimed_at"), + ).model_dump(), ) try: @@ -1384,7 +1624,7 @@ async def claim_desktop_session( room_url = str(launch_result.get("url", "")) if launch_result else "" host = room_url_on(container.host, room_url) - await stamp_launched(session_key, session) + await stamp_launched(session_key, session, host=None) log.info("desktop session claimed, container=%s", session_key) return DesktopSessionSchema( container=session_key, @@ -1409,19 +1649,10 @@ async def list_joinable_sessions( sessions: list[JoinableSessionSchema] = [] async for container_key, s in iter_live_sessions(): - if not s.get("multiplayer"): - continue - if s.get("user_id") == request.user.id: - continue if rom_id is not None and s.get("rom_id") != rom_id: continue - session_rom_id = s.get("rom_id") - rom = ( - db_rom_handler.get_rom_simple(session_rom_id) - if session_rom_id is not None - else None - ) - if not access.rom_is_visible(request, rom): + joinable, rom = access.joinable_session_rom(request, s) + if not joinable: continue user_id = s.get("user_id") @@ -1431,7 +1662,7 @@ async def list_joinable_sessions( container=container_key, label=_joinable_container_label(grouped, container_key), platform=s.get("platform"), - rom_id=session_rom_id, + rom_id=s.get("rom_id"), rom_name=s.get("rom_name"), host_username=host.username if host else None, claimed_at=s.get("claimed_at"), @@ -1471,7 +1702,7 @@ async def list_sessions(request: Request) -> AdminSessionsResponse: platform=s.get("platform"), rom_id=s.get("rom_id"), rom_name=s.get("rom_name"), - desktop=bool(s.get("desktop")), + desktop=session_is_desktop(s), claimed_at=s.get("claimed_at"), user_id=user_id, username=user.username if user else None, @@ -1513,12 +1744,16 @@ async def force_release_all( # emulator anyway rather than leave it running. await asyncio.to_thread(commands.stop, container) else: - state_slot = await lifecycle.quiesce_container(container, session) + stopped = await lifecycle.quiesce_container(container, session) # Credit playtime to the session's owner, not the admin. await lifecycle.record_play_session(session) await lifecycle.clear_session_activity(container_key, session) - await lifecycle.collect_exit_state(container, session, state_slot) - lifecycle.collect_exit_saves(container, session) + await lifecycle.collect_exit_state( + container, session, stopped.state_slot + ) + await lifecycle.start_exit_save_pull( + container, session, settled=stopped.settled + ) # Note who ended it before the key goes, so the player's next poll # can explain the stream vanishing. diff --git a/backend/endpoints/sync/__init__.py b/backend/endpoints/sync/__init__.py index 6c392e4bd..483ca36a2 100644 --- a/backend/endpoints/sync/__init__.py +++ b/backend/endpoints/sync/__init__.py @@ -1,4 +1,5 @@ import asyncio +from collections import Counter from datetime import datetime from fastapi import BackgroundTasks, HTTPException, Request, status @@ -21,6 +22,7 @@ from endpoints.sockets.sync import emit_sync_conflict from handler.auth.constants import Scope from handler.auth.dependencies import get_permissions from handler.database import ( + db_deleted_asset_handler, db_device_handler, db_device_save_sync_handler, db_save_handler, @@ -28,9 +30,10 @@ from handler.database import ( ) from handler.play_session_handler import ingest_play_sessions from handler.redis_handler import high_prio_queue -from handler.sync.comparison import compare_save_state +from handler.sync.comparison import compare_missing_server_save, compare_save_state from logger.logger import log from models.assets import Save +from models.deleted_asset import DeletedAsset from models.device import SyncMode from models.sync_session import SyncSessionStatus from utils.datetime import to_utc @@ -159,7 +162,8 @@ def negotiate_sync( """Negotiate sync operations between a client device and the server. The client sends its current save state, and the server returns a list of - operations (upload, download, conflict, no_op) to bring both sides in sync. + operations (upload, download, conflict, delete, no_op) to bring both sides + in sync. A client that only holds part of the library can send `rom_ids` to scope the negotiation to the ROMs installed on the device, which keeps the response @@ -199,14 +203,9 @@ def negotiate_sync( detail="Sync is disabled for this device", ) - # Cancel any existing active sessions for this device - cancelled = db_sync_session_handler.cancel_active_sessions( - device_id=device.id, user_id=request.user.id - ) - if cancelled: - log.info(f"Cancelled {cancelled} active sync session(s) for device {device.id}") - - # Create a new sync session + # A session belongs to the launch that negotiated it, not to the device, + # which can have two games open at once. One nobody closes is left to the + # scheduled cleanup rather than to the next negotiation. sync_session = db_sync_session_handler.create_session( device_id=device.id, user_id=request.user.id ) @@ -232,6 +231,20 @@ def negotiate_sync( if current is None or to_utc(save.updated_at) > to_utc(current.updated_at): server_save_map[key] = save + # Read only when a slot has no row left, so a slot refilled since keeps + # its record harmlessly. + emptied_rom_ids = { + s.rom_id + for s in payload.saves + if s.slot and (s.rom_id, s.slot) not in server_save_map + } + deleted_map: dict[tuple[int, str | None], DeletedAsset] = { + (record.rom_id, record.slot): record + for record in db_deleted_asset_handler.get_deletions( + user_id=request.user.id, rom_ids=emptied_rom_ids + ) + } + # Only the newest row per slot is ever looked up, so superseded rows stay out. current_save_ids = [s.id for s in server_save_map.values()] device_syncs = db_device_save_sync_handler.get_syncs_for_device_and_saves( @@ -248,16 +261,21 @@ def negotiate_sync( server_save = server_save_map.get(key) if server_save is None: - # Client has a save the server doesn't -> upload + # Without this the client offers the save back and the deletion + # undoes itself. + deletion = deleted_map.get(key) + result = compare_missing_server_save( + client_save.content_hash, deletion.content_hashes if deletion else () + ) operations.append( SyncOperationSchema( - action="upload", + action=result.action, rom_id=client_save.rom_id, save_id=None, file_name=client_save.file_name, slot=client_save.slot, emulator=client_save.emulator, - reason="Save exists on client but not on server", + reason=result.reason, ) ) continue @@ -353,16 +371,13 @@ def negotiate_sync( ) # Update session with operation counts - total_upload = sum(1 for op in operations if op.action == "upload") - total_download = sum(1 for op in operations if op.action == "download") - total_conflict = sum(1 for op in operations if op.action == "conflict") - total_no_op = sum(1 for op in operations if op.action == "no_op") + counts = Counter(op.action for op in operations) db_sync_session_handler.update_session( session_id=sync_session.id, data={ "status": SyncSessionStatus.IN_PROGRESS, - "operations_planned": total_upload + total_download + total_conflict, + "operations_planned": len(operations) - counts["no_op"], }, ) @@ -371,8 +386,9 @@ def negotiate_sync( log.info( f"Sync negotiation for device {device.id}: " - f"{total_upload} uploads, {total_download} downloads, " - f"{total_conflict} conflicts, {total_no_op} no-ops" + f"{counts['upload']} uploads, {counts['download']} downloads, " + f"{counts['conflict']} conflicts, {counts['delete']} deletions, " + f"{counts['no_op']} no-ops" ) # Sent after the response on the app's loop, so a slow broker never holds @@ -394,10 +410,11 @@ def negotiate_sync( return SyncNegotiateResponse( session_id=sync_session.id, operations=operations, - total_upload=total_upload, - total_download=total_download, - total_conflict=total_conflict, - total_no_op=total_no_op, + total_upload=counts["upload"], + total_download=counts["download"], + total_conflict=counts["conflict"], + total_no_op=counts["no_op"], + total_delete=counts["delete"], ) @@ -417,20 +434,19 @@ def complete_sync_session( detail=f"Sync session with ID {session_id} not found", ) - if sync_session.status not in ( - SyncSessionStatus.PENDING, - SyncSessionStatus.IN_PROGRESS, - ): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Session is already {sync_session.status}", - ) - + # A session the cleanup expired can still be completed: its counts and the + # play sessions the client carries are worth more than the guess that + # nobody would ever report them. One closed on purpose is refused. completed = db_sync_session_handler.complete_session( session_id=session_id, operations_completed=payload.operations_completed, operations_failed=payload.operations_failed, ) + if completed is None: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Session is already {sync_session.status}", + ) log.info( f"Sync session {session_id} completed: " @@ -454,7 +470,6 @@ def complete_sync_session( for s in payload.play_sessions ], device_id=sync_session.device_id, - sync_session_id=session_id, ) play_session_ingest = PlaySessionIngestResponse( results=[ diff --git a/backend/handler/asset_store.py b/backend/handler/asset_store.py index 0f76ecdc7..337d30cc1 100644 --- a/backend/handler/asset_store.py +++ b/backend/handler/asset_store.py @@ -9,7 +9,7 @@ import os from collections.abc import Sequence from io import BytesIO from tempfile import SpooledTemporaryFile -from typing import Any, BinaryIO, TypeAlias +from typing import Any, BinaryIO, TypeAlias, cast from fastapi import HTTPException, UploadFile, status @@ -324,8 +324,12 @@ async def rename_asset[AssetT: (Save, State)](asset: AssetT, file_name: str) -> thumbnail.id, {"file_name": thumbnail_name}, session=session ) if isinstance(asset, Save): - return db_save_handler.update_save( - asset.id, {"file_name": new_name}, touch=False, session=session + # Redundant only in mypy's AssetT=Save pass; the State pass needs it. + return cast( # type: ignore[redundant-cast] + AssetT, + db_save_handler.update_save( + asset.id, {"file_name": new_name}, touch=False, session=session + ), ) return db_state_handler.update_state( asset.id, {"file_name": new_name}, touch=False, session=session diff --git a/backend/handler/auth/middleware/csrf_middleware.py b/backend/handler/auth/middleware/csrf_middleware.py index 11a500645..2b66e50a5 100644 --- a/backend/handler/auth/middleware/csrf_middleware.py +++ b/backend/handler/auth/middleware/csrf_middleware.py @@ -6,7 +6,7 @@ import functools import http.cookies import secrets from re import Pattern -from typing import Optional, cast +from typing import Optional from itsdangerous import BadSignature from itsdangerous.url_safe import URLSafeSerializer @@ -150,7 +150,7 @@ class CSRFMiddleware: def _generate_csrf_token(self, user_id: int | None = None) -> str: obj = {"token": secrets.token_urlsafe(128), "user_id": user_id} - return cast(str, self.serializer.dumps(obj)) + return self.serializer.dumps(obj) def _csrf_cookie_has_user( self, csrf_cookie: str | None, user_id: int | None diff --git a/backend/handler/auth/middleware/redis_session_middleware.py b/backend/handler/auth/middleware/redis_session_middleware.py index c3c3df580..b6e4256c6 100644 --- a/backend/handler/auth/middleware/redis_session_middleware.py +++ b/backend/handler/auth/middleware/redis_session_middleware.py @@ -7,7 +7,7 @@ from starlette.types import ASGIApp, Message, Receive, Scope, Send from config import SESSION_MAX_AGE_SECONDS from handler.redis_handler import async_cache -from handler.socket_handler import socket_handler +from handler.socket_handler import close_login_session_sockets class RedisSessionMiddleware: @@ -41,7 +41,7 @@ class RedisSessionMiddleware: await async_cache.delete( *(f"session:{sid}" for sid in ids), f"user_sessions:{user_id}" ) - await socket_handler.close_login_sessions(ids) + await close_login_session_sockets(ids) async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] not in ("http", "websocket"): @@ -104,7 +104,7 @@ class RedisSessionMiddleware: await async_cache.srem( f"user_sessions:{initial_user_id}", session_id ) - await socket_handler.close_login_sessions([session_id]) + await close_login_session_sockets([session_id]) header_value = f"{self.session_cookie}=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; {self.security_flags}" headers.append("Set-Cookie", header_value) diff --git a/backend/handler/database/__init__.py b/backend/handler/database/__init__.py index a94332c47..1be361c3b 100644 --- a/backend/handler/database/__init__.py +++ b/backend/handler/database/__init__.py @@ -2,6 +2,7 @@ from .audit_events_handler import DBAuditEventsHandler from .client_tokens_handler import DBClientTokensHandler from .collections_handler import DBCollectionsHandler from .container_adoptions_handler import DBContainerAdoptionsHandler +from .deleted_assets_handler import DBDeletedAssetsHandler from .device_save_sync_handler import DBDeviceSaveSyncHandler from .devices_handler import DBDevicesHandler from .firmware_handler import DBFirmwareHandler @@ -25,6 +26,7 @@ db_audit_event_handler = DBAuditEventsHandler() db_client_token_handler = DBClientTokensHandler() db_collection_handler = DBCollectionsHandler() db_container_adoption_handler = DBContainerAdoptionsHandler() +db_deleted_asset_handler = DBDeletedAssetsHandler() db_device_handler = DBDevicesHandler() db_device_save_sync_handler = DBDeviceSaveSyncHandler() db_firmware_handler = DBFirmwareHandler() diff --git a/backend/handler/database/audit_events_handler.py b/backend/handler/database/audit_events_handler.py index 704736b29..9cc4de070 100644 --- a/backend/handler/database/audit_events_handler.py +++ b/backend/handler/database/audit_events_handler.py @@ -57,7 +57,7 @@ class DBAuditEventsHandler(DBBaseHandler): def add_events( self, events: Sequence[AuditEvent], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.add_all(events) @@ -67,7 +67,7 @@ class DBAuditEventsHandler(DBBaseHandler): filters: AuditEventFilters, limit: int, offset: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> tuple[list[tuple[AuditEvent, str | None]], int, int | None]: """A page of events, newest first, each with its device's name, the total, and the highest id among the matches for later pages to be pinned to.""" @@ -143,7 +143,7 @@ class DBAuditEventsHandler(DBBaseHandler): self, cutoff: datetime, batch_size: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: """Delete up to `batch_size` of the oldest events from before `cutoff`.""" # Ids first: MySQL refuses a LIMIT inside an IN subquery. diff --git a/backend/handler/database/client_tokens_handler.py b/backend/handler/database/client_tokens_handler.py index 90a2bca9d..f4510bd8c 100644 --- a/backend/handler/database/client_tokens_handler.py +++ b/backend/handler/database/client_tokens_handler.py @@ -18,7 +18,7 @@ class DBClientTokensHandler(DBBaseHandler): def add_token( self, token: ClientToken, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> ClientToken: return session.merge(token) @@ -26,7 +26,7 @@ class DBClientTokensHandler(DBBaseHandler): def get_token_by_hash( self, hashed_token: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> ClientToken | None: return session.scalar( select(ClientToken).where(ClientToken.hashed_token == hashed_token) @@ -36,7 +36,7 @@ class DBClientTokensHandler(DBBaseHandler): def get_tokens_by_user( self, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[ClientToken]: return session.scalars( select(ClientToken) @@ -47,7 +47,7 @@ class DBClientTokensHandler(DBBaseHandler): @begin_session def get_all_tokens( self, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[ClientToken]: return ( session.scalars( @@ -64,7 +64,7 @@ class DBClientTokensHandler(DBBaseHandler): self, token_id: int, user_id: int | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: stmt = delete(ClientToken).where(ClientToken.id == token_id) if user_id is not None: @@ -77,7 +77,7 @@ class DBClientTokensHandler(DBBaseHandler): def update_last_used( self, token_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: now = datetime.now(timezone.utc) token = session.get(ClientToken, token_id) @@ -103,7 +103,7 @@ class DBClientTokensHandler(DBBaseHandler): token_id: int, new_hash: str, user_id: int | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> ClientToken | None: stmt = ( update(ClientToken) @@ -125,7 +125,7 @@ class DBClientTokensHandler(DBBaseHandler): def count_tokens_by_user( self, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: return ( session.scalar( @@ -141,7 +141,7 @@ class DBClientTokensHandler(DBBaseHandler): self, token_id: int, user_id: int | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> ClientToken | None: stmt = select(ClientToken).where(ClientToken.id == token_id) if user_id is not None: diff --git a/backend/handler/database/collections_handler.py b/backend/handler/database/collections_handler.py index 7c3ec401a..1a8f74d33 100644 --- a/backend/handler/database/collections_handler.py +++ b/backend/handler/database/collections_handler.py @@ -1,5 +1,5 @@ import functools -from collections.abc import Sequence +from collections.abc import Callable, Sequence from datetime import datetime, timezone from typing import Any @@ -17,7 +17,6 @@ from sqlalchemy import ( from sqlalchemy.engine import Row from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import ( - Query, QueryableAttribute, Session, load_only, @@ -59,9 +58,9 @@ def _roms_load_options() -> list[Any]: ] -def with_roms(func): +def with_roms[**P, R](func: Callable[P, R]) -> Callable[P, R]: @functools.wraps(func) - def wrapper(*args, **kwargs): + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: kwargs["query"] = select(Collection).options(*_roms_load_options()) return func(*args, **kwargs) @@ -74,21 +73,21 @@ class DBCollectionsHandler(DBBaseHandler): def add_collection( self, collection: Collection, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: Select[tuple[Collection]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Collection: collection = session.merge(collection) session.flush() - return session.scalar(query.filter_by(id=collection.id).limit(1)) + return session.scalars(query.filter_by(id=collection.id).limit(1)).one() @begin_session @with_roms def get_collection( self, id: int, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: Select[tuple[Collection]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Collection | None: return session.scalar(query.filter_by(id=id).limit(1)) @@ -98,8 +97,8 @@ class DBCollectionsHandler(DBBaseHandler): self, name: str, user_id: int, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: Select[tuple[Collection]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Collection | None: return session.scalar(query.filter_by(name=name, user_id=user_id).limit(1)) @@ -108,8 +107,8 @@ class DBCollectionsHandler(DBBaseHandler): def get_favorite_collection( self, user_id: int, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: Select[tuple[Collection]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Collection | None: return session.scalar( query.filter_by(is_favorite=True, user_id=user_id).limit(1) @@ -130,7 +129,7 @@ class DBCollectionsHandler(DBBaseHandler): def get_collections( self, updated_after: datetime | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Collection]: query = self._collections_query(updated_after=updated_after) return session.scalars(query.options(*_roms_load_options())).unique().all() @@ -139,7 +138,7 @@ class DBCollectionsHandler(DBBaseHandler): def get_collection_ids( self, updated_after: datetime | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[Row[tuple[int, int, bool]]]: """Id, owner and visibility only, so neither eager load fires.""" query = self._collections_query(updated_after=updated_after) @@ -158,8 +157,8 @@ class DBCollectionsHandler(DBBaseHandler): id: int, data: dict, rom_ids: list[int] | None = None, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: Select[tuple[Collection]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Collection: session.execute( update(Collection) @@ -189,7 +188,7 @@ class DBCollectionsHandler(DBBaseHandler): ], ) - return session.scalar(query.filter_by(id=id).limit(1)) + return session.scalars(query.filter_by(id=id).limit(1)).one() @begin_session @with_roms @@ -197,8 +196,8 @@ class DBCollectionsHandler(DBBaseHandler): self, id: int, rom_ids: list[int], - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: Select[tuple[Collection]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Collection: if rom_ids: valid_rom_ids = set( @@ -232,7 +231,7 @@ class DBCollectionsHandler(DBBaseHandler): .execution_options(synchronize_session="evaluate") ) - return session.scalar(query.filter_by(id=id).limit(1)) + return session.scalars(query.filter_by(id=id).limit(1)).one() @begin_session @with_roms @@ -240,8 +239,8 @@ class DBCollectionsHandler(DBBaseHandler): self, id: int, rom_ids: list[int], - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: Select[tuple[Collection]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Collection: if rom_ids: result = session.execute( @@ -258,13 +257,13 @@ class DBCollectionsHandler(DBBaseHandler): .execution_options(synchronize_session="evaluate") ) - return session.scalar(query.filter_by(id=id).limit(1)) + return session.scalars(query.filter_by(id=id).limit(1)).one() @begin_session def delete_collection( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(Collection) @@ -333,7 +332,7 @@ class DBCollectionsHandler(DBBaseHandler): def get_virtual_collection( self, id: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> VirtualCollection | None: name, type = VirtualCollection.from_id(id) collection = session.scalar( @@ -350,7 +349,7 @@ class DBCollectionsHandler(DBBaseHandler): type: str, limit: int | None = None, only_fields: Sequence[QueryableAttribute] | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[VirtualCollection]: query = ( select(VirtualCollection) @@ -381,18 +380,20 @@ class DBCollectionsHandler(DBBaseHandler): def add_smart_collection( self, smart_collection: SmartCollection, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> SmartCollection: smart_collection = session.merge(smart_collection) session.flush() - return session.query(SmartCollection).filter_by(id=smart_collection.id).one() + return session.scalars( + select(SmartCollection).filter_by(id=smart_collection.id) + ).one() @begin_session def get_smart_collection( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> SmartCollection | None: return session.scalar(select(SmartCollection).filter_by(id=id).limit(1)) @@ -401,7 +402,7 @@ class DBCollectionsHandler(DBBaseHandler): self, name: str, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> SmartCollection | None: return session.scalar( select(SmartCollection).filter_by(name=name, user_id=user_id).limit(1) @@ -430,7 +431,7 @@ class DBCollectionsHandler(DBBaseHandler): self, user_id: int | None = None, updated_after: datetime | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[SmartCollection]: query = self._smart_collections_query( user_id=user_id, updated_after=updated_after @@ -442,7 +443,7 @@ class DBCollectionsHandler(DBBaseHandler): self, user_id: int | None = None, updated_after: datetime | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[int]: """Ids only, so no `SmartCollection` is built and no eager user join fires.""" query = self._smart_collections_query( @@ -455,7 +456,7 @@ class DBCollectionsHandler(DBBaseHandler): self, rom_id: int, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[SmartCollection]: # Membership is a cached JSON array of rom ids on the collection, so # push containment + visibility into SQL rather than loading every @@ -490,7 +491,7 @@ class DBCollectionsHandler(DBBaseHandler): self, id: int, data: dict[str, Any], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> SmartCollection: session.execute( update(SmartCollection) @@ -499,13 +500,13 @@ class DBCollectionsHandler(DBBaseHandler): .execution_options(synchronize_session="evaluate") ) - return session.query(SmartCollection).filter_by(id=id).one() + return session.scalars(select(SmartCollection).filter_by(id=id)).one() @begin_session def delete_smart_collection( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(SmartCollection) @@ -516,11 +517,11 @@ class DBCollectionsHandler(DBBaseHandler): def build_smart_collection_query( self, *, - query: Query, + query: Select, smart_collection: SmartCollection, user_id: int | None, session: Session, - ) -> Query: + ) -> Select: """Apply a smart collection's stored criteria to a ROM query. The criteria are `filter_roms`'s own vocabulary, so membership composes @@ -552,7 +553,7 @@ class DBCollectionsHandler(DBBaseHandler): self, smart_collection: SmartCollection, user_id: int | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Row[tuple[int, str | None, str | None]]]: """Every member's id and cover paths, in the collection's own order. @@ -569,22 +570,20 @@ class DBCollectionsHandler(DBBaseHandler): user_id=user_id, session=session, ) - query = self.build_smart_collection_query( + covers_query = self.build_smart_collection_query( query=query, smart_collection=smart_collection, user_id=user_id, session=session, - ).with_only_columns( # type: ignore - Rom.id, Rom.path_cover_s, Rom.path_cover_l - ) + ).with_only_columns(Rom.id, Rom.path_cover_s, Rom.path_cover_l) - return session.execute(query).all() + return session.execute(covers_query).all() @begin_session def refresh_smart_collection( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> SmartCollection | None: """Recompute a smart collection's cached membership columns. @@ -641,7 +640,7 @@ class DBCollectionsHandler(DBBaseHandler): @begin_session def refresh_smart_collections( self, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: """Refresh every smart collection, e.g. once the library has changed.""" ids = session.scalars(select(SmartCollection.id)).all() @@ -655,7 +654,7 @@ class DBCollectionsHandler(DBBaseHandler): self, rom_ids: Sequence[int], membership_only: bool = False, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ): """Refresh the collections a handful of changed ROMs touch. diff --git a/backend/handler/database/container_adoptions_handler.py b/backend/handler/database/container_adoptions_handler.py index 4fd25e06d..3ac64a876 100644 --- a/backend/handler/database/container_adoptions_handler.py +++ b/backend/handler/database/container_adoptions_handler.py @@ -13,7 +13,7 @@ class DBContainerAdoptionsHandler(DBBaseHandler): def get_adoption( self, container_key: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> StreamingContainerAdoption | None: return session.scalar( select(StreamingContainerAdoption).filter_by(container_key=container_key) @@ -25,7 +25,7 @@ class DBContainerAdoptionsHandler(DBBaseHandler): container_key: str, outcome: AdoptionOutcome, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> StreamingContainerAdoption | None: """Returns None when another claim recorded the decision first. The unique constraint is the arbiter, not the earlier read.""" diff --git a/backend/handler/database/deleted_assets_handler.py b/backend/handler/database/deleted_assets_handler.py new file mode 100644 index 000000000..8ef3b9db0 --- /dev/null +++ b/backend/handler/database/deleted_assets_handler.py @@ -0,0 +1,103 @@ +from collections.abc import Collection, Sequence + +from sqlalchemy import select +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import Session + +from decorators.database import begin_session +from models.deleted_asset import MAX_REMEMBERED_HASHES, DeletedAsset + +from .base_handler import DBBaseHandler + + +class DBDeletedAssetsHandler(DBBaseHandler): + def record_deletion( + self, + user_id: int, + rom_id: int, + slot: str, + content_hash: str, + ) -> DeletedAsset: + """Remember a version this slot lost, keeping one row per slot. + + Args: + user_id: Whose library the slot belongs to. + rom_id: The ROM whose slot lost a version. + slot: The slot itself. + content_hash: What that version held. + + Returns: + The record a negotiation will read. + """ + # Separate transactions: on MariaDB, locking a missing key and then + # inserting deadlocks a concurrent deletion, even of another slot. + record = self._merge(user_id, rom_id, slot, content_hash) + if record: + return record + try: + return self._insert(user_id, rom_id, slot, content_hash) + except IntegrityError: + # A concurrent deletion of the same slot inserted first. + record = self._merge(user_id, rom_id, slot, content_hash) + if not record: + raise + return record + + @begin_session + def _insert( + self, + user_id: int, + rom_id: int, + slot: str, + content_hash: str, + session: Session = None, # type: ignore[assignment] + ) -> DeletedAsset: + record = DeletedAsset( + user_id=user_id, + rom_id=rom_id, + slot=slot, + content_hashes=[content_hash], + ) + session.add(record) + session.flush() + return record + + @begin_session + def _merge( + self, + user_id: int, + rom_id: int, + slot: str, + content_hash: str, + session: Session = None, # type: ignore[assignment] + ) -> DeletedAsset | None: + """Add this version to the slot's record, or None when it has none yet.""" + record = session.scalar( + select(DeletedAsset) + .filter_by(user_id=user_id, rom_id=rom_id, slot=slot) + .with_for_update() + ) + if not record: + return None + # A version lost again moves to the end, so trimming keeps it. + hashes = [h for h in record.content_hashes if h != content_hash] + hashes.append(content_hash) + record.content_hashes = hashes[-MAX_REMEMBERED_HASHES:] + session.flush() + return record + + @begin_session + def get_deletions( + self, + user_id: int, + rom_ids: Collection[int], + session: Session = None, # type: ignore[assignment] + ) -> Sequence[DeletedAsset]: + """Every slot of these ROMs this user emptied.""" + if not rom_ids: + return [] + return session.scalars( + select(DeletedAsset) + .filter_by(user_id=user_id) + .filter(DeletedAsset.rom_id.in_(rom_ids)) + ).all() diff --git a/backend/handler/database/device_save_sync_handler.py b/backend/handler/database/device_save_sync_handler.py index 7550f058f..735b6bf2a 100644 --- a/backend/handler/database/device_save_sync_handler.py +++ b/backend/handler/database/device_save_sync_handler.py @@ -17,7 +17,7 @@ class DBDeviceSaveSyncHandler(DBBaseHandler): self, device_id: str, save_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> DeviceSaveSync | None: return session.scalar( select(DeviceSaveSync) @@ -30,7 +30,7 @@ class DBDeviceSaveSyncHandler(DBBaseHandler): self, device_id: str, save_ids: list[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[DeviceSaveSync]: if not save_ids: return [] @@ -45,7 +45,7 @@ class DBDeviceSaveSyncHandler(DBBaseHandler): def get_syncs_for_saves( self, save_ids: list[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> dict[int, list[tuple[DeviceSaveSync, str | None]]]: """Fetch every device sync row for the given saves, grouped by save id. @@ -72,7 +72,7 @@ class DBDeviceSaveSyncHandler(DBBaseHandler): device_id: str, save_id: int, synced_at: datetime | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> DeviceSaveSync: now = synced_at or datetime.now(timezone.utc) existing = session.scalar( @@ -110,7 +110,7 @@ class DBDeviceSaveSyncHandler(DBBaseHandler): device_id: str, save_id: int, untracked: bool, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> DeviceSaveSync | None: existing = session.scalar( select(DeviceSaveSync) @@ -146,7 +146,7 @@ class DBDeviceSaveSyncHandler(DBBaseHandler): def delete_syncs_for_device( self, device_id: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(DeviceSaveSync) diff --git a/backend/handler/database/devices_handler.py b/backend/handler/database/devices_handler.py index 4286b4c0f..460eff3a3 100644 --- a/backend/handler/database/devices_handler.py +++ b/backend/handler/database/devices_handler.py @@ -18,7 +18,7 @@ class DBDevicesHandler(DBBaseHandler): def add_device( self, device: Device, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Device: return session.merge(device) @@ -27,7 +27,7 @@ class DBDevicesHandler(DBBaseHandler): self, device_id: str, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Device | None: return session.scalar( select(Device).filter_by(id=device_id, user_id=user_id).limit(1) @@ -41,7 +41,7 @@ class DBDevicesHandler(DBBaseHandler): hostname: str | None = None, ip_address: str | None = None, platform: str | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Device | None: if mac_address: device = session.scalar( @@ -72,7 +72,7 @@ class DBDevicesHandler(DBBaseHandler): def get_device_by_id( self, device_id: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Device | None: """Get a device by ID without user filtering (for server-side operations).""" return session.scalar(select(Device).filter_by(id=device_id).limit(1)) @@ -82,7 +82,7 @@ class DBDevicesHandler(DBBaseHandler): self, user_id: int, client_device_identifier: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Device | None: """Find a device by its client-supplied stable identifier, scoped to a user.""" if not client_device_identifier: @@ -100,7 +100,7 @@ class DBDevicesHandler(DBBaseHandler): def get_devices( self, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Device]: return session.scalars(select(Device).filter_by(user_id=user_id)).all() @@ -108,7 +108,7 @@ class DBDevicesHandler(DBBaseHandler): def get_all_devices_by_sync_mode( self, sync_mode: SyncMode, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Device]: """Get all devices with a specific sync mode (across all users).""" return session.scalars(select(Device).filter_by(sync_mode=sync_mode)).all() @@ -119,7 +119,7 @@ class DBDevicesHandler(DBBaseHandler): device_id: str, user_id: int, data: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Device | None: session.execute( update(Device) @@ -136,7 +136,7 @@ class DBDevicesHandler(DBBaseHandler): self, device_id: str, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( update(Device) @@ -149,7 +149,7 @@ class DBDevicesHandler(DBBaseHandler): def update_last_seen_debounced( self, device_id: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: """Bump last_seen on the device, skipping if updated within the debounce window. @@ -176,7 +176,7 @@ class DBDevicesHandler(DBBaseHandler): self, device_id: str, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(Device) diff --git a/backend/handler/database/firmware_handler.py b/backend/handler/database/firmware_handler.py index d6f26fdaf..3999886d0 100644 --- a/backend/handler/database/firmware_handler.py +++ b/backend/handler/database/firmware_handler.py @@ -1,4 +1,4 @@ -from collections.abc import Sequence +from collections.abc import Collection, Sequence from sqlalchemy import Select, and_, delete, select, update from sqlalchemy.orm import Session, noload @@ -14,7 +14,7 @@ class DBFirmwareHandler(DBBaseHandler): def add_firmware( self, firmware: Firmware, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Firmware: return session.merge(firmware) @@ -23,7 +23,7 @@ class DBFirmwareHandler(DBBaseHandler): self, id: int, *, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Firmware | None: return session.scalar(select(Firmware).filter_by(id=id).limit(1)) @@ -32,7 +32,7 @@ class DBFirmwareHandler(DBBaseHandler): *, platform_ids: Sequence[int] | None = None, missing: bool | None = None, - hidden_platform_ids: Sequence[int] | None = None, + hidden_platform_ids: Collection[int] | None = None, ) -> Select[tuple[Firmware]]: query = select(Firmware).order_by(Firmware.file_name.asc()) @@ -55,8 +55,8 @@ class DBFirmwareHandler(DBBaseHandler): *, platform_ids: Sequence[int] | None = None, missing: bool | None = None, - hidden_platform_ids: Sequence[int] | None = None, - session: Session = None, # type: ignore + hidden_platform_ids: Collection[int] | None = None, + session: Session = None, # type: ignore[assignment] ) -> Sequence[Firmware]: query = self._firmware_query( platform_ids=platform_ids, @@ -73,8 +73,8 @@ class DBFirmwareHandler(DBBaseHandler): *, platform_ids: Sequence[int] | None = None, missing: bool | None = None, - hidden_platform_ids: Sequence[int] | None = None, - session: Session = None, # type: ignore + hidden_platform_ids: Collection[int] | None = None, + session: Session = None, # type: ignore[assignment] ) -> list[int]: """Ids only, so no `Firmware` is built and no eager platform join fires.""" query = self._firmware_query( @@ -89,7 +89,7 @@ class DBFirmwareHandler(DBBaseHandler): self, platform_id: int, file_name: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ): return session.scalar( select(Firmware) @@ -102,7 +102,7 @@ class DBFirmwareHandler(DBBaseHandler): self, id: int, data: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Firmware: session.execute( update(Firmware) @@ -110,13 +110,13 @@ class DBFirmwareHandler(DBBaseHandler): .values(**data) .execution_options(synchronize_session="evaluate") ) - return session.query(Firmware).filter_by(id=id).one() + return session.scalars(select(Firmware).filter_by(id=id)).one() @begin_session def delete_firmware( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(Firmware) @@ -129,7 +129,7 @@ class DBFirmwareHandler(DBBaseHandler): self, platform_id: int, fs_firmwares_to_keep: list[str], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Firmware]: missing_firmware = ( session.scalars( diff --git a/backend/handler/database/memory_cards_handler.py b/backend/handler/database/memory_cards_handler.py index d8ee410a5..668906e3d 100644 --- a/backend/handler/database/memory_cards_handler.py +++ b/backend/handler/database/memory_cards_handler.py @@ -16,7 +16,7 @@ class DBMemoryCardsHandler(DBBaseHandler): def add_card( self, card: MemoryCard, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MemoryCard: return session.merge(card) @@ -25,7 +25,7 @@ class DBMemoryCardsHandler(DBBaseHandler): self, user_id: int, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MemoryCard | None: """Owner-scoped fetch, for mutations the caller must own (rename, share, delete).""" @@ -37,7 +37,7 @@ class DBMemoryCardsHandler(DBBaseHandler): def get_card_by_id( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MemoryCard | None: """Unscoped fetch, for reads that may cross ownership (a public card's detail or version list) and for lookups by an id already resolved to @@ -50,7 +50,7 @@ class DBMemoryCardsHandler(DBBaseHandler): self, user_id: int, emulator: str | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[MemoryCard]: """A user's own cards, optionally filtered to one emulator (the pick list shown at session claim).""" @@ -64,7 +64,7 @@ class DBMemoryCardsHandler(DBBaseHandler): self, emulator: str, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[MemoryCard]: """Cards for an emulator visible to the requesting user: their own plus other users' public ones. Browsing only, since another user's card is @@ -83,7 +83,7 @@ class DBMemoryCardsHandler(DBBaseHandler): self, id: int, data: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MemoryCard | None: """Returns None when the row was deleted concurrently.""" session.execute( @@ -92,13 +92,13 @@ class DBMemoryCardsHandler(DBBaseHandler): .values(**data) .execution_options(synchronize_session="evaluate") ) - return session.query(MemoryCard).filter_by(id=id).one_or_none() + return session.scalars(select(MemoryCard).filter_by(id=id)).one_or_none() @begin_session def delete_card( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[str]: """Delete a card and return the paths of the version archives that went with it. The listing shares the delete's transaction and locks the rows, @@ -127,7 +127,7 @@ class DBMemoryCardsHandler(DBBaseHandler): def add_version( self, version: MemoryCardVersion, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MemoryCardVersion: return session.merge(version) @@ -135,7 +135,7 @@ class DBMemoryCardsHandler(DBBaseHandler): def get_latest_version( self, card_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MemoryCardVersion | None: """Newest snapshot of a card, used to hydrate a container at claim. @@ -155,7 +155,7 @@ class DBMemoryCardsHandler(DBBaseHandler): self, card_id: int, content_hash: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MemoryCardVersion | None: """Dedup lookup on evacuate: skip storing a snapshot identical to one already held for this card.""" @@ -169,7 +169,7 @@ class DBMemoryCardsHandler(DBBaseHandler): def get_version_by_id( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MemoryCardVersion | None: """Unscoped fetch, for the content-download route.""" return session.get(MemoryCardVersion, id) @@ -178,7 +178,7 @@ class DBMemoryCardsHandler(DBBaseHandler): def get_versions( self, card_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[MemoryCardVersion]: """A card's snapshot history, newest first.""" return session.scalars( @@ -192,7 +192,7 @@ class DBMemoryCardsHandler(DBBaseHandler): self, id: int, missing: bool, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: """Record whether a version's archive is still on disk, so the history can say a snapshot is gone instead of offering a download that 404s.""" diff --git a/backend/handler/database/music_playlists_handler.py b/backend/handler/database/music_playlists_handler.py index fdeac4ba4..a88994073 100644 --- a/backend/handler/database/music_playlists_handler.py +++ b/backend/handler/database/music_playlists_handler.py @@ -16,7 +16,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): def add_playlist( self, playlist: MusicPlaylist, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MusicPlaylist: playlist = session.merge(playlist) session.flush() @@ -29,7 +29,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): def get_playlist( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MusicPlaylist | None: return session.scalar(select(MusicPlaylist).filter_by(id=id).limit(1)) @@ -38,7 +38,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): self, name: str, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MusicPlaylist | None: return session.scalar( select(MusicPlaylist).filter_by(name=name, user_id=user_id).limit(1) @@ -48,7 +48,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): def get_playlists( self, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[MusicPlaylist]: """The user's own playlists plus other users' public ones.""" return ( @@ -71,7 +71,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): self, id: int, data: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> MusicPlaylist: session.execute( update(MusicPlaylist) @@ -86,7 +86,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): def delete_playlist( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(MusicPlaylist) @@ -98,7 +98,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): def get_playlist_track_counts( self, playlist_ids: Sequence[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> dict[int, int]: """Stored entry counts per playlist, before any visibility filtering.""" if not playlist_ids: @@ -114,7 +114,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): def get_playlist_entries( self, playlist_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[MusicPlaylistTrack]: return session.scalars( select(MusicPlaylistTrack) @@ -127,7 +127,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): self, playlist_id: int, rom_file_ids: Sequence[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: candidates = list(dict.fromkeys(rom_file_ids)) if not candidates: @@ -175,7 +175,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): self, playlist_id: int, rom_file_ids: Sequence[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: if not rom_file_ids: return 0 @@ -194,7 +194,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): self, playlist_id: int, ordered_entry_ids: Sequence[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: """Rewrite positions to match ordered_entry_ids; entries not listed keep their relative order after the listed ones.""" @@ -217,7 +217,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): self, user_id: int, rom_file_ids: Sequence[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: candidates = list(dict.fromkeys(rom_file_ids)) if not candidates: @@ -252,7 +252,7 @@ class DBMusicPlaylistsHandler(DBBaseHandler): self, user_id: int, rom_file_ids: Sequence[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: if not rom_file_ids: return 0 diff --git a/backend/handler/database/notification_channels_handler.py b/backend/handler/database/notification_channels_handler.py index d1b47c1fb..401085765 100644 --- a/backend/handler/database/notification_channels_handler.py +++ b/backend/handler/database/notification_channels_handler.py @@ -21,7 +21,7 @@ class DBNotificationChannelsHandler(DBBaseHandler): def get_channels( self, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[NotificationChannel]: return session.scalars( select(NotificationChannel) @@ -34,7 +34,7 @@ class DBNotificationChannelsHandler(DBBaseHandler): self, channel_id: int, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> NotificationChannel | None: return session.scalar( select(NotificationChannel).where( @@ -47,7 +47,7 @@ class DBNotificationChannelsHandler(DBBaseHandler): def get_channel_for_delivery( self, channel_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> tuple[NotificationChannel, str] | None: """The channel and its owner's role, as of now.""" row = session.execute( @@ -64,7 +64,7 @@ class DBNotificationChannelsHandler(DBBaseHandler): def get_deliverable_channels( self, user_ids: Sequence[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[NotificationChannel]: """The users' channels that are on and, for an email address, confirmed.""" return session.scalars( @@ -80,7 +80,7 @@ class DBNotificationChannelsHandler(DBBaseHandler): self, channel: NotificationChannel, limit: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> NotificationChannel | None: """Add the channel unless its user already has `limit`; None if they do.""" # Locking the user's row makes that user's concurrent adds count in turn. @@ -104,7 +104,7 @@ class DBNotificationChannelsHandler(DBBaseHandler): channel_id: int, user_id: int, data: dict[str, Any], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> NotificationChannel | None: session.execute( update(NotificationChannel) @@ -127,7 +127,7 @@ class DBNotificationChannelsHandler(DBBaseHandler): self, channel_id: int, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: result = session.execute( delete(NotificationChannel) @@ -143,7 +143,7 @@ class DBNotificationChannelsHandler(DBBaseHandler): def record_delivery( self, channel_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( update(NotificationChannel) @@ -162,7 +162,7 @@ class DBNotificationChannelsHandler(DBBaseHandler): channel_id: int, error: str, counts: bool, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: """Keep a failed delivery's error; one that `counts` brings the channel closer to off.""" values: dict[str, Any] = { @@ -183,7 +183,7 @@ class DBNotificationChannelsHandler(DBBaseHandler): def turn_off_if_failing( self, channel_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> bool: """Turn the channel off once it failed too often in a row; True if this call did.""" result = session.execute( diff --git a/backend/handler/database/notifications_handler.py b/backend/handler/database/notifications_handler.py index a8eae57bd..64af6d091 100644 --- a/backend/handler/database/notifications_handler.py +++ b/backend/handler/database/notifications_handler.py @@ -24,7 +24,7 @@ class DBNotificationsHandler(DBBaseHandler): def add_notifications( self, notifications: Sequence[Notification], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Notification]: """Store notifications and trim their users' inboxes; returns the rows kept.""" session.add_all(notifications) @@ -61,7 +61,7 @@ class DBNotificationsHandler(DBBaseHandler): def get_notifications( self, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Notification]: return session.scalars( select(Notification) @@ -75,7 +75,7 @@ class DBNotificationsHandler(DBBaseHandler): self, user_id: int, ids: list[int] | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: """Mark the user's unread notifications read, all of them when `ids` is None.""" stmt = update(Notification).where( @@ -95,7 +95,7 @@ class DBNotificationsHandler(DBBaseHandler): self, user_id: int, ids: list[int] | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: """Delete the user's notifications, all of them when `ids` is None.""" stmt = delete(Notification).where(Notification.user_id == user_id) diff --git a/backend/handler/database/permissions_handler.py b/backend/handler/database/permissions_handler.py index d517ad899..93ca52cfe 100644 --- a/backend/handler/database/permissions_handler.py +++ b/backend/handler/database/permissions_handler.py @@ -34,7 +34,7 @@ class DBPermissionsHandler(DBBaseHandler): @begin_session def get_default_group( self, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> PermissionGroup | None: return session.scalar( select(PermissionGroup).filter_by(is_default=True).limit(1) @@ -44,7 +44,7 @@ class DBPermissionsHandler(DBBaseHandler): def get_group_grants( self, group_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[PermissionGroupGrant]: return session.scalars( select(PermissionGroupGrant).filter_by(group_id=group_id) @@ -54,7 +54,7 @@ class DBPermissionsHandler(DBBaseHandler): def get_user_overrides( self, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[UserPermissionOverride]: return session.scalars( select(UserPermissionOverride).filter_by(user_id=user_id) @@ -66,7 +66,7 @@ class DBPermissionsHandler(DBBaseHandler): entity: PermEntity, user_id: int | None, group_id: int | None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> set[int]: """Ids of `entity` hidden from the given user OR their group. @@ -93,7 +93,7 @@ class DBPermissionsHandler(DBBaseHandler): @begin_session def get_groups( self, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[PermissionGroup]: return ( session.scalars(select(PermissionGroup).order_by(PermissionGroup.name)) @@ -105,7 +105,7 @@ class DBPermissionsHandler(DBBaseHandler): def get_group( self, group_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> PermissionGroup | None: return session.get(PermissionGroup, group_id) @@ -113,7 +113,7 @@ class DBPermissionsHandler(DBBaseHandler): def get_group_by_name( self, name: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> PermissionGroup | None: return session.scalar(select(PermissionGroup).filter_by(name=name).limit(1)) @@ -125,7 +125,7 @@ class DBPermissionsHandler(DBBaseHandler): is_default: bool = False, color: str | None = None, grants: Iterable[GrantTuple] = (), - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> PermissionGroup: group = PermissionGroup( name=name, @@ -152,7 +152,7 @@ class DBPermissionsHandler(DBBaseHandler): is_default: bool | None = None, color: str | None = None, grants: Iterable[GrantTuple] | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> PermissionGroup | None: group = session.get(PermissionGroup, group_id) if group is None: @@ -177,7 +177,7 @@ class DBPermissionsHandler(DBBaseHandler): def delete_group( self, group_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute(delete(PermissionGroup).where(PermissionGroup.id == group_id)) @@ -208,7 +208,7 @@ class DBPermissionsHandler(DBBaseHandler): def get_group_member_ids( self, group_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[int]: return list( session.scalars( @@ -223,7 +223,7 @@ class DBPermissionsHandler(DBBaseHandler): self, user_id: int, group_id: int | None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( update(User) @@ -237,7 +237,7 @@ class DBPermissionsHandler(DBBaseHandler): self, user_id: int, overrides: Iterable[OverrideTuple], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(UserPermissionOverride).where( @@ -263,7 +263,7 @@ class DBPermissionsHandler(DBBaseHandler): *, user_id: int | None = None, group_id: int | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[HiddenEntity]: query = select(HiddenEntity) if user_id is not None: @@ -280,7 +280,7 @@ class DBPermissionsHandler(DBBaseHandler): *, user_id: int | None = None, group_id: int | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: # Idempotent: a repeated hide is a no-op rather than a unique violation. existing = session.scalar( @@ -311,7 +311,7 @@ class DBPermissionsHandler(DBBaseHandler): *, user_id: int | None = None, group_id: int | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(HiddenEntity).where( diff --git a/backend/handler/database/platforms_handler.py b/backend/handler/database/platforms_handler.py index bf5cbc522..abac5ff2f 100644 --- a/backend/handler/database/platforms_handler.py +++ b/backend/handler/database/platforms_handler.py @@ -1,9 +1,9 @@ import functools -from collections.abc import Sequence +from collections.abc import Callable, Collection, Sequence from datetime import datetime -from sqlalchemy import delete, func, or_, select, update -from sqlalchemy.orm import Query, Session, selectinload +from sqlalchemy import Select, delete, func, or_, select, update +from sqlalchemy.orm import Session, selectinload from decorators.database import begin_session from models.platform import Platform @@ -12,9 +12,9 @@ from models.rom import Rom from .base_handler import DBBaseHandler -def with_firmware(func): +def with_firmware[**P, R](func: Callable[P, R]) -> Callable[P, R]: @functools.wraps(func) - def wrapper(*args, **kwargs): + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: kwargs["query"] = select(Platform).options( selectinload(Platform.firmware), ) @@ -29,20 +29,20 @@ class DBPlatformsHandler(DBBaseHandler): def add_platform( self, platform: Platform, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: Select[tuple[Platform]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Platform: platform = session.merge(platform) session.flush() - return session.scalar(query.filter_by(id=platform.id).limit(1)) + return session.scalars(query.filter_by(id=platform.id).limit(1)).one() @begin_session def update_platform( self, id: int, data: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Platform: session.execute( update(Platform) @@ -50,15 +50,15 @@ class DBPlatformsHandler(DBBaseHandler): .values(**data) .execution_options(synchronize_session="evaluate") ) - return session.query(Platform).filter_by(id=id).one() + return session.scalars(select(Platform).filter_by(id=id)).one() @begin_session @with_firmware def get_platform( self, id: int, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: Select[tuple[Platform]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Platform | None: return session.scalar(query.filter_by(id=id).limit(1)) @@ -67,9 +67,9 @@ class DBPlatformsHandler(DBBaseHandler): def get_platforms( self, updated_after: datetime | None = None, - hidden_platform_ids: Sequence[int] | None = None, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + hidden_platform_ids: Collection[int] | None = None, + query: Select[tuple[Platform]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Sequence[Platform]: if updated_after: query = query.filter(Platform.updated_at > updated_after) @@ -84,8 +84,8 @@ class DBPlatformsHandler(DBBaseHandler): @begin_session def get_platform_ids( self, - hidden_platform_ids: Sequence[int] | None = None, - session: Session = None, # type: ignore + hidden_platform_ids: Collection[int] | None = None, + session: Session = None, # type: ignore[assignment] ) -> list[int]: """Ids only, deliberately off `with_firmware`: its eager load fires anyway.""" query = select(Platform).order_by(Platform.name.asc()) @@ -100,8 +100,8 @@ class DBPlatformsHandler(DBBaseHandler): def get_platform_by_fs_slug( self, fs_slug: str, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: Select[tuple[Platform]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Platform | None: platform = session.scalar(query.filter_by(fs_slug=fs_slug).limit(1)) if platform: @@ -118,8 +118,8 @@ class DBPlatformsHandler(DBBaseHandler): def get_platform_by_slug( self, slug: str, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: Select[tuple[Platform]] = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Platform | None: return session.scalar(query.filter_by(slug=slug).limit(1)) @@ -127,7 +127,7 @@ class DBPlatformsHandler(DBBaseHandler): def delete_platform( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: # Remove all roms from that platforms first session.execute( @@ -146,8 +146,7 @@ class DBPlatformsHandler(DBBaseHandler): def mark_missing_platforms( self, fs_platforms_to_keep: list[str], - query: Query = None, # type: ignore - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Platform]: missing_platforms = ( session.scalars( diff --git a/backend/handler/database/play_sessions_handler.py b/backend/handler/database/play_sessions_handler.py index 40e1b8cf1..49d8eacfa 100644 --- a/backend/handler/database/play_sessions_handler.py +++ b/backend/handler/database/play_sessions_handler.py @@ -15,7 +15,7 @@ class DBPlaySessionsHandler(DBBaseHandler): def add_sessions( self, play_sessions: list[PlaySession], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[PlaySession]: session.add_all(play_sessions) session.flush() @@ -27,7 +27,7 @@ class DBPlaySessionsHandler(DBBaseHandler): user_id: int, device_id: str | None, rom_start_pairs: list[tuple[int | None, datetime]], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> set[tuple[int | None, datetime]]: """Return which (rom_id, start_time) pairs already exist for this user+device.""" if not rom_start_pairs: @@ -75,7 +75,7 @@ class DBPlaySessionsHandler(DBBaseHandler): end_before: datetime | None = None, limit: int | None = 50, offset: int = 0, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[PlaySession]: stmt = select(PlaySession).filter_by(user_id=user_id) @@ -99,7 +99,7 @@ class DBPlaySessionsHandler(DBBaseHandler): self, user_id: int, rom_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: result = session.scalar( select(func.sum(PlaySession.duration_ms)).where( @@ -114,7 +114,7 @@ class DBPlaySessionsHandler(DBBaseHandler): self, session_id: int, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> bool: result = session.execute( delete(PlaySession) diff --git a/backend/handler/database/recommendations_handler.py b/backend/handler/database/recommendations_handler.py index a13659fdb..322a7ae18 100644 --- a/backend/handler/database/recommendations_handler.py +++ b/backend/handler/database/recommendations_handler.py @@ -79,7 +79,7 @@ class DBRecommendationsHandler(DBBaseHandler): @begin_session def get_feature_rows( - self, session: Session = None # type: ignore + self, session: Session = None # type: ignore[assignment] ) -> list[RomFeatureRow]: """Every ROM's facet values, for building the library-wide IDF. @@ -112,7 +112,7 @@ class DBRecommendationsHandler(DBBaseHandler): @begin_session def get_rom_igdb_ids( - self, session: Session = None # type: ignore + self, session: Session = None # type: ignore[assignment] ) -> dict[int, int]: """ROM id -> IGDB id, for resolving IGDB's related-game ids to owned copies.""" stmt = select(RomFacets.rom_id, RomFacets.igdb_id).where( @@ -122,7 +122,7 @@ class DBRecommendationsHandler(DBBaseHandler): @begin_session def get_rom_identity_ids( - self, session: Session = None # type: ignore + self, session: Session = None # type: ignore[assignment] ) -> dict[int, frozenset[str]]: """ROM id -> "provider:id" tokens from every provider that matched it. @@ -146,7 +146,7 @@ class DBRecommendationsHandler(DBBaseHandler): @begin_session def iter_igdb_related( - self, session: Session = None # type: ignore + self, session: Session = None # type: ignore[assignment] ) -> Iterator[tuple[int, list[int]]]: """Stream each ROM's IGDB related-game ids out of its metadata blob. @@ -184,7 +184,7 @@ class DBRecommendationsHandler(DBBaseHandler): @begin_session def get_collection_membership_sets( - self, session: Session = None # type: ignore + self, session: Session = None # type: ignore[assignment] ) -> list[list[int]]: """ROM ids grouped by user collection, for co-membership scoring.""" stmt = select(CollectionRom.collection_id, CollectionRom.rom_id).order_by( @@ -194,7 +194,7 @@ class DBRecommendationsHandler(DBBaseHandler): @begin_session def get_played_sets( - self, session: Session = None # type: ignore + self, session: Session = None # type: ignore[assignment] ) -> list[list[int]]: """ROM ids grouped by user, restricted to games they actually played. @@ -232,7 +232,7 @@ class DBRecommendationsHandler(DBBaseHandler): self, rom_ids: Sequence[int], edges: Sequence[dict[str, Any]], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: """Swap in a batch of ROMs' edges. @@ -256,7 +256,7 @@ class DBRecommendationsHandler(DBBaseHandler): def get_stored_edges( self, rom_ids: Sequence[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> dict[int, list[tuple[float, int]]]: """Each ROM's current neighbours, for a top-up to merge new ones into. @@ -276,7 +276,7 @@ class DBRecommendationsHandler(DBBaseHandler): return stored @begin_session - def count_similarity_edges(self, session: Session = None) -> int: # type: ignore + def count_similarity_edges(self, session: Session = None) -> int: # type: ignore[assignment] return session.scalar(select(func.count()).select_from(RomSimilarity)) or 0 # --- Reads ------------------------------------------------------------------- @@ -286,7 +286,7 @@ class DBRecommendationsHandler(DBBaseHandler): self, rom_id: int, limit: int = 20, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[SimilarRomEdge]: """Top precomputed neighbours of one ROM, best first. @@ -314,7 +314,7 @@ class DBRecommendationsHandler(DBBaseHandler): self, rom_ids: Sequence[int], limit_per_rom: int = 20, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[tuple[int, int, float, list[dict[str, Any]]]]: """Edges fanning out from a set of seed ROMs, for the personalised feed. @@ -352,7 +352,7 @@ class DBRecommendationsHandler(DBBaseHandler): def get_user_affinity( self, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[UserAffinityRow]: """Everything the user has done with each ROM, plus total playtime. @@ -402,7 +402,7 @@ class DBRecommendationsHandler(DBBaseHandler): def get_rom_names( self, rom_ids: Sequence[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> dict[int, str]: """Display names only, for the "Because you played X" attribution.""" if not rom_ids: @@ -419,7 +419,7 @@ class DBRecommendationsHandler(DBBaseHandler): self, limit: int, exclude_rom_ids: Sequence[int] = (), - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[int]: """Cold-start feed: the best-reviewed games in the library. diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 7c1224b35..5e6573c20 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -3,8 +3,8 @@ import hashlib import json import re import secrets -from collections import Counter -from collections.abc import Iterable, Sequence +from collections import Counter, abc +from collections.abc import Callable, Iterable, Sequence from datetime import datetime from types import SimpleNamespace from typing import Any, Literal, NamedTuple @@ -39,7 +39,7 @@ from sqlalchemy import ( from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import ( ColumnProperty, - Query, + Mapper, QueryableAttribute, Session, joinedload, @@ -48,7 +48,7 @@ from sqlalchemy.orm import ( selectinload, undefer, ) -from sqlalchemy.sql.elements import ColumnElement +from sqlalchemy.sql.elements import ColumnElement, UnaryExpression from sqlalchemy.sql.selectable import Select from config import ROMM_DB_DRIVER @@ -105,6 +105,8 @@ from utils.platform_slugs import UniversalPlatformSlug as UPS from .base_handler import DBBaseHandler, affected_rows +type RomSelect = Select[tuple[Rom]] + EJS_SUPPORTED_PLATFORMS = [ UPS._3DO, UPS.AMIGA, @@ -293,7 +295,8 @@ TRACK_META_SCANNED_COLUMNS = ( @functools.cache def _nullable_columns(model: type) -> frozenset[str]: - return frozenset(c.key for c in sa_inspect(model).columns if c.nullable) + mapper: Mapper[Any] = sa_inspect(model) + return frozenset(c.key for c in mapper.columns if c.nullable) def _copy_scanned_columns( @@ -539,9 +542,9 @@ def sorts_by_rom_user_column(order_by: str, user_id: int) -> bool: return _resolve_gallery_sort_key(order_by, user_id).source == "rom_user" -def with_details(func): +def with_details[**P, R](func: Callable[P, R]) -> Callable[P, R]: @functools.wraps(func) - def wrapper(*args, **kwargs): + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: kwargs["query"] = select(Rom).options( # Ensure platform is loaded for main ROM objects selectinload(Rom.platform), @@ -595,7 +598,7 @@ def with_details(func): return wrapper -def with_simple_details(func): +def with_simple_details[**P, R](func: Callable[P, R]) -> Callable[P, R]: """Lightweight eager-load for the `SimpleRomSchema` (v2 gallery card). Loads only the relationships `SimpleRomSchema` serializes (rom_users, @@ -606,7 +609,7 @@ def with_simple_details(func): """ @functools.wraps(func) - def wrapper(*args, **kwargs): + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: kwargs["query"] = select(Rom).options( selectinload(Rom.platform), selectinload(Rom.rom_users).options( @@ -711,13 +714,13 @@ class DBRomsHandler(DBBaseHandler): def add_rom( self, rom: Rom, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: RomSelect = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Rom: rom = session.merge(rom) session.flush() - return session.scalar(query.filter_by(id=rom.id).limit(1)) + return session.scalars(query.filter_by(id=rom.id).limit(1)).one() @begin_session @with_details @@ -725,8 +728,8 @@ class DBRomsHandler(DBBaseHandler): self, id: int, *, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: RomSelect = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Rom | None: return session.scalar(query.filter_by(id=id).limit(1)) @@ -735,7 +738,7 @@ class DBRomsHandler(DBBaseHandler): self, id: int, *, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomVisibility | None: """The id and platform id a visibility check needs, nothing else.""" row = session.execute( @@ -752,7 +755,7 @@ class DBRomsHandler(DBBaseHandler): self, id: int, *, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomVisibilityLabel | None: """`get_rom_visibility` plus the name pair the file-delete logs need.""" row = session.execute( @@ -771,7 +774,7 @@ class DBRomsHandler(DBBaseHandler): self, id: int, *, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomDeletionTarget | None: """The columns the bulk-delete route reads off one rom, and no relations.""" row = session.execute( @@ -809,8 +812,8 @@ class DBRomsHandler(DBBaseHandler): self, id: int, *, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: RomSelect = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Rom | None: """Get a rom by ID with only the loads `SimpleRomSchema` needs.""" return session.scalar(query.filter_by(id=id).limit(1)) @@ -821,8 +824,8 @@ class DBRomsHandler(DBBaseHandler): self, ids: list[int], *, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: RomSelect = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Sequence[Rom]: """Get multiple ROMs by their IDs.""" if not ids: @@ -835,8 +838,8 @@ class DBRomsHandler(DBBaseHandler): self, ids: Sequence[int], *, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: RomSelect = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Sequence[Rom]: """Get multiple ROMs by ID with only the loads `SimpleRomSchema` needs.""" if not ids: @@ -875,8 +878,8 @@ class DBRomsHandler(DBBaseHandler): user_id: int, *, session: Session, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, + hidden_platform_ids: abc.Collection[int] | None = None, + hidden_rom_ids: abc.Collection[int] | None = None, ) -> dict[int, list[tuple[Rom, bool]]]: """Return {rom_id: [(sibling Rom, is_main_sibling), ...]} in a single query. @@ -959,15 +962,15 @@ class DBRomsHandler(DBBaseHandler): ).all() ) - def filter_by_platform_id(self, query: Query, platform_id: int): + def filter_by_platform_id(self, query: Select, platform_id: int): return query.filter(Rom.platform_id == platform_id) def _filter_by_platform_ids( - self, query: Query, platform_ids: Sequence[int] - ) -> Query: + self, query: Select, platform_ids: Sequence[int] + ) -> Select: return query.filter(Rom.platform_id.in_(platform_ids)) - def _filter_by_collection_id(self, query: Query, collection_id: int): + def _filter_by_collection_id(self, query: Select, collection_id: int): # `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( @@ -979,7 +982,7 @@ class DBRomsHandler(DBBaseHandler): ) def _filter_by_virtual_collection_id( - self, query: Query, session: Session, virtual_collection_id: str + self, query: Select, session: Session, virtual_collection_id: str ): from . import db_collection_handler @@ -993,7 +996,7 @@ class DBRomsHandler(DBBaseHandler): def _filter_by_smart_collection_id( self, - query: Query, + query: Select, session: Session, smart_collection_id: int, user_id: int | None, @@ -1010,7 +1013,7 @@ class DBRomsHandler(DBBaseHandler): return query.filter( Rom.id.in_( db_collection_handler.build_smart_collection_query( - query=member_ids, # type: ignore + query=member_ids, smart_collection=smart_collection, user_id=user_id, session=session, @@ -1033,7 +1036,7 @@ class DBRomsHandler(DBBaseHandler): smart_collection: SmartCollection, rom_ids: Iterable[int], user_id: int | None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> set[int]: """Which of `rom_ids` currently match the collection's criteria. @@ -1046,7 +1049,7 @@ class DBRomsHandler(DBBaseHandler): return set( session.scalars( db_collection_handler.build_smart_collection_query( - query=query, # type: ignore + query=query, smart_collection=smart_collection, user_id=user_id, session=session, @@ -1129,7 +1132,7 @@ class DBRomsHandler(DBBaseHandler): select(RomFile.rom_id.label("id")).where(or_(*file_predicates)), ] - def _filter_by_search_term(self, query: Query, search_term: str): + def _filter_by_search_term(self, query: Select, search_term: str): terms = [term.strip() for term in search_term.split("|")] terms = [term for term in terms if term] if not terms: @@ -1149,7 +1152,7 @@ class DBRomsHandler(DBBaseHandler): ).subquery() return query.filter(Rom.id.in_(select(matches.c.id))) - def _filter_by_matched(self, query: Query, value: bool) -> Query: + def _filter_by_matched(self, query: Select, value: bool) -> Select: """Filter based on whether the rom is matched to a metadata provider. Args: @@ -1170,8 +1173,8 @@ class DBRomsHandler(DBBaseHandler): return query.filter(predicate) def _filter_by_favorite( - self, query: Query, session: Session, value: bool, user_id: int | None - ) -> Query: + self, query: Select, session: Session, value: bool, user_id: int | None + ) -> Select: """Filter based on whether the rom is in the user's favorites collection.""" if not user_id: return query @@ -1188,14 +1191,14 @@ class DBRomsHandler(DBBaseHandler): predicate = not_(predicate) return query.filter(predicate) - def _filter_by_duplicate(self, query: Query, value: bool) -> Query: + def _filter_by_duplicate(self, query: Select, value: bool) -> Select: """Filter based on whether the rom has duplicates.""" predicate = Rom.sibling_roms.any() if not value: predicate = not_(predicate) return query.filter(predicate) - def _filter_by_playable(self, query: Query, value: bool) -> Query: + def _filter_by_playable(self, query: Select, value: bool) -> Select: """Filter based on whether the rom is playable on supported platforms.""" predicate = or_( Platform.slug.in_(EJS_SUPPORTED_PLATFORMS), @@ -1206,8 +1209,8 @@ class DBRomsHandler(DBBaseHandler): return query.join(Platform).filter(predicate) def _filter_by_last_played( - self, query: Query, value: bool, user_id: int | None = None - ) -> Query: + self, query: Select, value: bool, user_id: int | None = None + ) -> Select: """Filter based on whether the rom has a last played value for the user.""" if not user_id: return query @@ -1219,15 +1222,15 @@ class DBRomsHandler(DBBaseHandler): ) return query.filter(has_last_played) - def _filter_by_has_ra(self, query: Query, value: bool) -> Query: + def _filter_by_has_ra(self, query: Select, value: bool) -> Select: predicate = Rom.ra_id.isnot(None) if not value: predicate = not_(predicate) return query.filter(predicate) def _filter_by_has_saves( - self, query: Query, value: bool, user_id: int | None = None - ) -> Query: + self, query: Select, value: bool, user_id: int | None = None + ) -> Select: """Filter based on whether the rom has saves visible to the current user: their own plus other users' public (community) saves.""" if not user_id: @@ -1238,8 +1241,8 @@ class DBRomsHandler(DBBaseHandler): return query.filter(predicate) def _filter_by_has_states( - self, query: Query, value: bool, user_id: int | None = None - ) -> Query: + self, query: Select, value: bool, user_id: int | None = None + ) -> Select: """Filter based on whether the rom has save states visible to the current user: their own plus other users' public (community) states.""" if not user_id: @@ -1249,7 +1252,7 @@ class DBRomsHandler(DBBaseHandler): predicate = not_(predicate) return query.filter(predicate) - def _filter_by_missing_from_fs(self, query: Query, value: bool) -> Query: + def _filter_by_missing_from_fs(self, query: Select, value: bool) -> Select: # The column is NOT NULL, so equality matches the same rows as the # `IS [NOT] FALSE` form. MariaDB only treats the equality as indexable # though, and this filter backs the Missing tab's whole-library scan. @@ -1261,7 +1264,7 @@ class DBRomsHandler(DBBaseHandler): and_(Rom.missing_from_fs == true(), Rom.is_physical.is_(False)) ) - def _filter_by_verified(self, query: Query, value: bool) -> Query: + def _filter_by_verified(self, query: Select, value: bool) -> Select: keys_to_check = [ "tosec_match", "mame_arcade_match", @@ -1290,16 +1293,14 @@ class DBRomsHandler(DBBaseHandler): predicate = text(f"NOT ({conditions})") return query.filter(predicate) else: - predicate = or_( + any_verified = or_( *(Rom.hasheous_metadata[key].as_boolean() for key in keys_to_check) ) - if not value: - predicate = not_(predicate) - return query.filter(predicate) + return query.filter(any_verified if value else not_(any_verified)) def _filter_by_status( self, - query: Query, + query: Select, *, session: Session, values: Sequence[str], @@ -1309,7 +1310,7 @@ class DBRomsHandler(DBBaseHandler): if not values: return query - status_filters = [] + status_filters: list[ColumnElement[bool]] = [] for selected_status in values: if selected_status == "now_playing": status_filters.append(RomUser.now_playing.is_(True)) @@ -1334,14 +1335,14 @@ class DBRomsHandler(DBBaseHandler): def _apply_filter_spec( self, - query: Query, + query: Select, spec: RomFilterSpec, *, session: Session, values: Sequence[str], match_all: bool = False, match_none: bool = False, - ) -> Query: + ) -> Select: """Narrow `query` to the roms matching `values` under `spec`.""" column = spec.column if column is None: @@ -1366,12 +1367,12 @@ class DBRomsHandler(DBBaseHandler): def _filter_by_metadata_providers( self, - query: Query, + query: Select, *, values: Sequence[str], match_all: bool = False, match_none: bool = False, - ) -> Query: + ) -> Select: """Filter on which metadata providers a ROM matched, keyed off each provider's id column on the facets mirror. @@ -1399,7 +1400,7 @@ class DBRomsHandler(DBBaseHandler): @begin_session def filter_roms( self, - query: Query, + query: Select, filters: RomFilterParams | None = None, *, # The grouped dedup aggregates the active sort key over each group; @@ -1416,10 +1417,10 @@ class DBRomsHandler(DBBaseHandler): include_related: bool = True, include_siblings: bool = True, include_notes: bool = True, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, - session: Session = None, # type: ignore - ) -> Query[Rom]: + hidden_platform_ids: abc.Collection[int] | None = None, + hidden_rom_ids: abc.Collection[int] | None = None, + session: Session = None, # type: ignore[assignment] + ) -> Select: from handler.scan_handler import MetadataSource filters = filters or RomFilterParams() @@ -1622,7 +1623,7 @@ class DBRomsHandler(DBBaseHandler): # drop the carried-over ORDER BY the window doesn't use. base_subquery = ( query.order_by(None) - .with_only_columns( # type: ignore + .with_only_columns( Rom.id, Rom.fs_name_no_ext, _prerelease_rank().label("prerelease_rank"), @@ -1764,9 +1765,7 @@ class DBRomsHandler(DBBaseHandler): # Add a filter to the original query to only include the primary ROM from each group query = query.filter( Rom.id.in_( - session.query(group_subquery.c.id).filter( - group_subquery.c.row_num == 1 - ) + select(group_subquery.c.id).where(group_subquery.c.row_num == 1) ) ) @@ -1834,8 +1833,8 @@ class DBRomsHandler(DBBaseHandler): order_dir: str = "asc", search_term: str | None = None, user_id: int | None = None, - session: Session = None, # type: ignore - ) -> tuple[Query[Rom], _GallerySortKey]: + session: Session = None, # type: ignore[assignment] + ) -> tuple[RomSelect, _GallerySortKey]: query = self._join_rom_user(select(Rom), user_id) order_dir = order_dir.lower() @@ -1851,7 +1850,7 @@ class DBRomsHandler(DBBaseHandler): search_term=search_term, ) - return query.order_by(*order_clauses), sort_key # type: ignore + return query.order_by(*order_clauses), sort_key def _scoped_roms_query( self, @@ -1859,7 +1858,7 @@ class DBRomsHandler(DBBaseHandler): session: Session, include_related: bool = True, **kwargs, - ) -> Query[Rom]: + ) -> RomSelect: """The filtered, ordered query `get_roms_scalar` and `get_rom_ids` both run.""" order_by = kwargs.get("order_by", "") order_dir = kwargs.get("order_dir", "asc") @@ -1895,7 +1894,7 @@ class DBRomsHandler(DBBaseHandler): def get_roms_scalar( self, *, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] **kwargs, ) -> Sequence[Rom]: query = self._scoped_roms_query(session=session, **kwargs) @@ -1905,7 +1904,7 @@ class DBRomsHandler(DBBaseHandler): def get_rom_ids( self, *, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] **kwargs, ) -> list[int]: """Every matching rom id, in query order.""" @@ -1918,9 +1917,9 @@ class DBRomsHandler(DBBaseHandler): def get_hidden_rom_ids_among( self, rom_ids: Sequence[int], - hidden_platform_ids: Sequence[int] | None, - hidden_rom_ids: Sequence[int] | None, - session: Session = None, # type: ignore + hidden_platform_ids: abc.Collection[int] | None, + hidden_rom_ids: abc.Collection[int] | None, + session: Session = None, # type: ignore[assignment] ) -> set[int]: """Of `rom_ids`, the subset hidden from the caller (own hide or platform).""" candidates = set(rom_ids) @@ -1938,12 +1937,12 @@ class DBRomsHandler(DBBaseHandler): @begin_session def with_char_index( self, - query: Query, + query: RomSelect, order_by_attr: Any, *, cache_key: str | None = None, order_dir: str = "asc", - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[tuple[str, int]]: # Letter offsets only index a lexically ordered result. `Enum` subclasses # `String`, but the database orders native enums by declaration order. @@ -1974,9 +1973,7 @@ class DBRomsHandler(DBBaseHandler): descending = order_dir.lower() == "desc" letter = func.substring(order_by_attr, 1, 1) counts = ( - query.with_only_columns( # type: ignore - letter.label("letter"), func.count().label("count") - ) + query.with_only_columns(letter.label("letter"), func.count().label("count")) .group_by(letter) .order_by(letter.desc() if descending else letter.asc()) ) @@ -1997,10 +1994,10 @@ class DBRomsHandler(DBBaseHandler): @begin_session def get_rom_id_index( self, - query: Query, + query: RomSelect, *, cache_key: str | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[int]: """Return every matching rom id in query order. @@ -2019,7 +2016,7 @@ class DBRomsHandler(DBBaseHandler): if cached is not None: return json.loads(cached) - ids = list(session.scalars(query.with_only_columns(Rom.id)).all()) # type: ignore + ids = list(session.scalars(query.with_only_columns(Rom.id)).all()) if redis_key is not None and version is not None: _store_versioned_cache(redis_key, version, ids) @@ -2028,9 +2025,9 @@ class DBRomsHandler(DBBaseHandler): @begin_session def get_rom_count( self, - query: Query, + query: RomSelect, *, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: """Count matching roms without materialising their ids. @@ -2048,9 +2045,9 @@ class DBRomsHandler(DBBaseHandler): @begin_session def get_random_rom_id( self, - query: Query, + query: RomSelect, *, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int | None: """Pick one rom id at random, uniformly, from a filtered query. @@ -2065,7 +2062,7 @@ class DBRomsHandler(DBBaseHandler): in it. That reads no rows, only index entries, since the statement selects nothing but the id. """ - id_query = query.order_by(None).with_only_columns(Rom.id) # type: ignore + id_query = query.order_by(None).with_only_columns(Rom.id) # Bounds come from the table rather than the filtered set: they only # need to cover it, and MIN/MAX over an untouched primary key are two @@ -2096,7 +2093,7 @@ class DBRomsHandler(DBBaseHandler): platform_id: int, fs_names: Iterable[str], with_files: bool = False, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> dict[str, Rom]: """Retrieve a dictionary of roms keyed by their full path (fs_path/fs_name). @@ -2138,7 +2135,7 @@ class DBRomsHandler(DBBaseHandler): def get_roms_by_fs_names_no_ext( self, fs_names_no_ext: Iterable[str], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[Rom]: """ROMs on any platform with one of these extensionless file names.""" names = list(dict.fromkeys(fs_names_no_ext)) @@ -2158,13 +2155,13 @@ class DBRomsHandler(DBBaseHandler): self, id: int, data: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Rom: if "name" in data and "name_sort_key" not in data: # Re-derive the key from the new name, but only when the stored key # is still the derived value (i.e. not a manual override). Mirrors # the `@validates` logic, which the bulk update() bypasses. - existing = session.query(Rom).filter_by(id=id).one() + existing = session.scalars(select(Rom).filter_by(id=id)).one() if ( existing.name_sort_key is None or existing.name_sort_key == compute_name_sort_key(existing.name) @@ -2183,7 +2180,7 @@ class DBRomsHandler(DBBaseHandler): if "fs_name" in data or "fs_path" in data: # The unique index reads the digest, so whichever half the caller # left out has to come from the stored row. - stored = session.query(Rom).filter_by(id=id).one() + stored = session.scalars(select(Rom).filter_by(id=id)).one() data = { **data, "full_path_hash": compute_full_path_hash( @@ -2198,7 +2195,7 @@ class DBRomsHandler(DBBaseHandler): .values(**data) .execution_options(synchronize_session="evaluate") ) - return session.query(Rom).filter_by(id=id).one() + return session.scalars(select(Rom).filter_by(id=id)).one() @begin_session def convert_rom_to_folder( @@ -2206,10 +2203,10 @@ class DBRomsHandler(DBBaseHandler): id: int, folder: str, file_path: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: parts = compute_file_name_parts(folder) - stored = session.query(Rom).filter_by(id=id).one() + stored = session.scalars(select(Rom).filter_by(id=id)).one() session.execute( update(Rom) .where(Rom.id == id) @@ -2229,7 +2226,7 @@ class DBRomsHandler(DBBaseHandler): def delete_rom( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(Rom) @@ -2241,7 +2238,7 @@ class DBRomsHandler(DBBaseHandler): def get_missing_rom_ids( self, platform_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> set[int]: """Return the ids of a platform's ROMs currently flagged missing.""" return set( @@ -2260,7 +2257,7 @@ class DBRomsHandler(DBBaseHandler): self, platform_id: int, rom_ids: list[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: """Bulk set missing_from_fs=False for a list of ROM IDs. @@ -2291,7 +2288,7 @@ class DBRomsHandler(DBBaseHandler): self, platform_id: int, fs_roms_to_keep: list[str], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Rom]: """Sync `missing_from_fs` for a platform against the keep-list. @@ -2352,7 +2349,7 @@ class DBRomsHandler(DBBaseHandler): self, rom_id: int, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomUser: rom_user = session.merge(RomUser(rom_id=rom_id, user_id=user_id)) session.flush() @@ -2366,7 +2363,7 @@ class DBRomsHandler(DBBaseHandler): self, rom_id: int, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomUser | None: return session.scalar( select(RomUser).filter_by(rom_id=rom_id, user_id=user_id).limit(1) @@ -2376,7 +2373,7 @@ class DBRomsHandler(DBBaseHandler): def get_rom_user_by_id( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomUser | None: return session.scalar(select(RomUser).filter_by(id=id).limit(1)) @@ -2385,7 +2382,7 @@ class DBRomsHandler(DBBaseHandler): self, id: int, data: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomUser | None: session.execute( update(RomUser) @@ -2394,7 +2391,7 @@ class DBRomsHandler(DBBaseHandler): .execution_options(synchronize_session="evaluate") ) - rom_user = session.query(RomUser).filter_by(id=id).one_or_none() + rom_user = session.scalars(select(RomUser).filter_by(id=id)).one_or_none() if not rom_user: return None @@ -2432,7 +2429,7 @@ class DBRomsHandler(DBBaseHandler): def add_rom_file( self, rom_file: RomFile, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomFile: merged = session.merge(rom_file) session.flush() @@ -2481,7 +2478,7 @@ class DBRomsHandler(DBBaseHandler): self, rom_id: int, scanned_files: Sequence[RomFile], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> SyncedRomFiles: """Reconcile a ROM's file rows against a fresh scan, preserving row ids. @@ -2572,7 +2569,7 @@ class DBRomsHandler(DBBaseHandler): def get_rom_file_by_id( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomFile | None: return session.scalar( select(RomFile) @@ -2591,7 +2588,7 @@ class DBRomsHandler(DBBaseHandler): def get_rom_files_by_ids( self, ids: Sequence[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[RomFile]: if not ids: return [] @@ -2614,7 +2611,7 @@ class DBRomsHandler(DBBaseHandler): rom_id: int, file_path: str, file_name: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomFile | None: return session.scalar( select(RomFile) @@ -2628,7 +2625,7 @@ class DBRomsHandler(DBBaseHandler): self, rom_id: int, category: RomFileCategory, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[RomFile]: """Return the ROM's files for a single category, ordered by file_name.""" return ( @@ -2648,7 +2645,7 @@ class DBRomsHandler(DBBaseHandler): def rom_files_for_rom_id( self, rom_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[RomFile]: """Fetch a ROM's files on demand, with the `RomFile.rom` backref loaded.""" return list( @@ -2669,7 +2666,7 @@ class DBRomsHandler(DBBaseHandler): self, id: int, data: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomFile | None: session.execute( update(RomFile) @@ -2678,7 +2675,7 @@ class DBRomsHandler(DBBaseHandler): .execution_options(synchronize_session="evaluate") ) - return session.query(RomFile).filter_by(id=id).one_or_none() + return session.scalars(select(RomFile).filter_by(id=id)).one_or_none() @begin_session def upsert_track_meta( @@ -2686,7 +2683,7 @@ class DBRomsHandler(DBBaseHandler): rom_file_id: int, rom_id: int, values: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> TrackMeta: existing = session.get(TrackMeta, rom_file_id) if existing: @@ -2704,7 +2701,7 @@ class DBRomsHandler(DBBaseHandler): def delete_track_meta( self, rom_file_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute(delete(TrackMeta).where(TrackMeta.rom_file_id == rom_file_id)) @@ -2716,7 +2713,7 @@ class DBRomsHandler(DBBaseHandler): rom_file_id: int, rom_id: int, values: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomFileDocMeta: """Create or update the provenance sidecar for a document file.""" existing = session.get(RomFileDocMeta, rom_file_id) @@ -2738,7 +2735,7 @@ class DBRomsHandler(DBBaseHandler): self, rom_file_id: int, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomFileUser | None: return session.scalar( select(RomFileUser) @@ -2752,7 +2749,7 @@ class DBRomsHandler(DBBaseHandler): rom_file_id: int, user_id: int, values: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomFileUser: """Create or update a user's reading progress for a document file.""" select_state = ( @@ -2788,8 +2785,8 @@ class DBRomsHandler(DBBaseHandler): def _music_where( self, *, - hidden_platform_ids: Sequence[int] | None, - hidden_rom_ids: Sequence[int] | None, + hidden_platform_ids: abc.Collection[int] | None, + hidden_rom_ids: abc.Collection[int] | None, search: str | None = None, artist: str | None = None, album: str | None = None, @@ -2853,8 +2850,8 @@ class DBRomsHandler(DBBaseHandler): def get_music_tracks( self, *, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, + hidden_platform_ids: abc.Collection[int] | None = None, + hidden_rom_ids: abc.Collection[int] | None = None, search: str | None = None, artist: str | None = None, album: str | None = None, @@ -2874,7 +2871,7 @@ class DBRomsHandler(DBBaseHandler): is_favorite_user_id: int | None = None, only_favorites: bool = False, playlist_id: int | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> tuple[Sequence[Any], int]: if only_favorites and is_favorite_user_id is None: return [], 0 @@ -2981,8 +2978,8 @@ class DBRomsHandler(DBBaseHandler): self, *, field: str, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, + hidden_platform_ids: abc.Collection[int] | None = None, + hidden_rom_ids: abc.Collection[int] | None = None, search: str | None = None, artist: str | None = None, album: str | None = None, @@ -2995,7 +2992,7 @@ class DBRomsHandler(DBBaseHandler): order_dir: str = "desc", limit: int = 50, offset: int = 0, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> tuple[Sequence[Any], int]: facet_columns = { "artists": (TrackMeta.artist, "artist"), @@ -3037,6 +3034,7 @@ class DBRomsHandler(DBBaseHandler): .group_by(col) ) total = session.scalar(select(func.count()).select_from(base.subquery())) or 0 + primary: UnaryExpression[Any] if order_by == "value": primary = col.asc() if order_dir != "desc" else col.desc() else: @@ -3059,9 +3057,9 @@ class DBRomsHandler(DBBaseHandler): def get_music_stats( self, *, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, - session: Session = None, # type: ignore + hidden_platform_ids: abc.Collection[int] | None = None, + hidden_rom_ids: abc.Collection[int] | None = None, + session: Session = None, # type: ignore[assignment] ) -> tuple[int, float]: """Total track count and total duration, for the jukebox home cards. @@ -3089,8 +3087,8 @@ class DBRomsHandler(DBBaseHandler): def get_music_game_genre_facet( self, *, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, + hidden_platform_ids: abc.Collection[int] | None = None, + hidden_rom_ids: abc.Collection[int] | None = None, search: str | None = None, artist: str | None = None, album: str | None = None, @@ -3105,7 +3103,7 @@ class DBRomsHandler(DBBaseHandler): order_dir: str = "desc", limit: int = 50, offset: int = 0, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> tuple[Sequence[Any], int]: """Distinct *game* genres over the tracked roms, with track counts. @@ -3171,8 +3169,8 @@ class DBRomsHandler(DBBaseHandler): def get_music_platform_facet( self, *, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, + hidden_platform_ids: abc.Collection[int] | None = None, + hidden_rom_ids: abc.Collection[int] | None = None, search: str | None = None, artist: str | None = None, album: str | None = None, @@ -3187,7 +3185,7 @@ class DBRomsHandler(DBBaseHandler): order_dir: str = "asc", limit: int = 50, offset: int = 0, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> tuple[Sequence[Any], int]: """Platforms that have soundtrack tracks, with per-platform counts.""" where = self._music_where( @@ -3221,6 +3219,7 @@ class DBRomsHandler(DBBaseHandler): ).where(*where) base = base.group_by(Platform.id, Platform.slug, Platform.name) total = session.scalar(select(func.count()).select_from(base.subquery())) or 0 + primary: UnaryExpression[Any] if order_by == "count": primary = count_col.asc() if order_dir == "asc" else count_col.desc() else: @@ -3236,8 +3235,8 @@ class DBRomsHandler(DBBaseHandler): def get_music_game_facet( self, *, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, + hidden_platform_ids: abc.Collection[int] | None = None, + hidden_rom_ids: abc.Collection[int] | None = None, search: str | None = None, artist: str | None = None, album: str | None = None, @@ -3253,7 +3252,7 @@ class DBRomsHandler(DBBaseHandler): order_dir: str = "asc", limit: int = 50, offset: int = 0, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> tuple[Sequence[Any], int]: """Games that have soundtrack tracks -- the jukebox's album list.""" where = self._music_where( @@ -3302,6 +3301,7 @@ class DBRomsHandler(DBBaseHandler): Platform.name, ) total = session.scalar(select(func.count()).select_from(base.subquery())) or 0 + primary: UnaryExpression[Any] if order_by == "count": primary = count_col.asc() if order_dir == "asc" else count_col.desc() else: @@ -3315,7 +3315,7 @@ class DBRomsHandler(DBBaseHandler): def delete_rom_file( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(RomFile) @@ -3333,8 +3333,8 @@ class DBRomsHandler(DBBaseHandler): search: str | None = "", tags: list[str] | None = None, session: Session, - ) -> Query[RomNote]: - query = session.query(RomNote).filter(RomNote.rom_id == rom_id) + ) -> Select[tuple[RomNote]]: + query = select(RomNote).filter(RomNote.rom_id == rom_id) if public_only: query = query.filter(RomNote.is_public) @@ -3363,15 +3363,17 @@ class DBRomsHandler(DBBaseHandler): public_only: bool = False, search: str | None = "", tags: list[str] | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[RomNote]: - return self._rom_notes_query( - rom_id=rom_id, - user_id=user_id, - public_only=public_only, - search=search, - tags=tags, - session=session, + return session.scalars( + self._rom_notes_query( + rom_id=rom_id, + user_id=user_id, + public_only=public_only, + search=search, + tags=tags, + session=session, + ) ).all() @begin_session @@ -3382,7 +3384,7 @@ class DBRomsHandler(DBBaseHandler): public_only: bool = False, search: str | None = "", tags: list[str] | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[int]: """Ids only, so no `RomNote` is built and no eager rom or user join fires.""" query = self._rom_notes_query( @@ -3393,7 +3395,7 @@ class DBRomsHandler(DBBaseHandler): tags=tags, session=session, ) - return [row[0] for row in query.with_entities(RomNote.id).all()] + return list(session.scalars(query.with_only_columns(RomNote.id)).all()) @begin_session def create_rom_note( @@ -3404,7 +3406,7 @@ class DBRomsHandler(DBBaseHandler): content: str = "", is_public: bool = False, tags: list[str] | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> dict: note = RomNote( rom_id=rom_id, @@ -3436,17 +3438,17 @@ class DBRomsHandler(DBBaseHandler): note_id: int, user_id: int, rom_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] **fields, ) -> dict | None: - note = ( - session.query(RomNote) + note = session.scalar( + select(RomNote) .filter( RomNote.id == note_id, RomNote.user_id == user_id, RomNote.rom_id == rom_id, ) - .first() + .limit(1) ) if not note: @@ -3477,7 +3479,7 @@ class DBRomsHandler(DBBaseHandler): note_id: int, user_id: int, rom_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> bool: result = session.execute( delete(RomNote).where( @@ -3508,8 +3510,8 @@ class DBRomsHandler(DBBaseHandler): csdb_id: int | None = None, steam_id: int | None = None, *, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: RomSelect = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Rom | None: """ Get a ROM by any metadata ID. @@ -3552,8 +3554,8 @@ class DBRomsHandler(DBBaseHandler): sha1_hash: str | None = None, ra_hash: str | None = None, *, - query: Query = None, # type: ignore - session: Session = None, # type: ignore + query: RomSelect = None, # type: ignore[assignment] + session: Session = None, # type: ignore[assignment] ) -> Rom | None: """ Get a ROM by calculated hash value. @@ -3590,7 +3592,7 @@ class DBRomsHandler(DBBaseHandler): md5_hash: str | None = None, sha1_hash: str | None = None, title_id: str | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Rom | None: """Find a ROM marked missing on a platform that identifies the file. @@ -3697,7 +3699,7 @@ class DBRomsHandler(DBBaseHandler): def refresh_identity_key_statistics( self, *, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: """Resample `rom_identity_keys` so the sibling join keeps its indexed plan. @@ -3722,10 +3724,10 @@ class DBRomsHandler(DBBaseHandler): @begin_session def with_filter_values( self, - query: Query, + query: RomSelect, *, cache_key: str | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomFiltersDict: """ Returns the list of filters given the current subset of ROMs in the query @@ -3739,7 +3741,7 @@ class DBRomsHandler(DBBaseHandler): if cached is not None: return json.loads(cached) - ids_subq = query.order_by(None).with_only_columns(Rom.id).scalar_subquery() # type: ignore + ids_subq = query.order_by(None).with_only_columns(Rom.id).scalar_subquery() statement = _FILTER_VALUES_SELECT.where(RomFacets.rom_id.in_(ids_subq)) @@ -3751,7 +3753,7 @@ class DBRomsHandler(DBBaseHandler): @begin_session def get_rom_filters( self, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> RomFiltersDict: """ Returns all filter values across all ROM metadata diff --git a/backend/handler/database/saves_handler.py b/backend/handler/database/saves_handler.py index 8203ec27b..4c3533950 100644 --- a/backend/handler/database/saves_handler.py +++ b/backend/handler/database/saves_handler.py @@ -17,7 +17,7 @@ class DBSavesHandler(DBBaseHandler): def add_save( self, save: Save, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Save: return session.merge(save) @@ -26,7 +26,7 @@ class DBSavesHandler(DBBaseHandler): self, user_id: int, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Save | None: return session.scalar(select(Save).filter_by(user_id=user_id, id=id).limit(1)) @@ -37,7 +37,7 @@ class DBSavesHandler(DBBaseHandler): rom_id: int, file_name: str, slot: str | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Save | None: query = select(Save).filter_by( rom_id=rom_id, user_id=user_id, file_name=file_name @@ -55,7 +55,7 @@ class DBSavesHandler(DBBaseHandler): rom_id: int, file_path: str, file_name: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Save | None: return session.scalars( select(Save) @@ -72,7 +72,7 @@ class DBSavesHandler(DBBaseHandler): rom_id: int, content_hash: str, slot: str | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Save | None: query = select(Save).filter_by( rom_id=rom_id, user_id=user_id, content_hash=content_hash @@ -138,7 +138,7 @@ class DBSavesHandler(DBBaseHandler): file_name_prefix: str | None = None, order_by: Literal["updated_at", "created_at"] | None = None, order_dir: Literal["asc", "desc"] = "desc", - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Save]: query = self._saves_query( user_id=user_id, @@ -163,7 +163,7 @@ class DBSavesHandler(DBBaseHandler): slot_not_null: bool = False, order_by: Literal["updated_at", "created_at"] | None = None, order_dir: Literal["asc", "desc"] = "desc", - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[int]: """Ids only, so no `Save` is built and no eager rom or user join fires.""" query = self._saves_query( @@ -181,7 +181,7 @@ class DBSavesHandler(DBBaseHandler): def get_save_by_id( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Save | None: """Fetch a save by id without scoping to an owner. Used for the visibility toggle and community downloads, where the caller may not own @@ -194,7 +194,7 @@ class DBSavesHandler(DBBaseHandler): rom_id: int, user_id: int, public_only: bool = False, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Save]: """Saves for a ROM visible to the requesting user: own (public + private) plus other users' public ones. Mirrors @@ -214,7 +214,7 @@ class DBSavesHandler(DBBaseHandler): self, user_id: int, rom_ids: Sequence[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> dict[int, Save]: """The most recent save per ROM for a user, keyed by `rom_id`. @@ -242,7 +242,7 @@ class DBSavesHandler(DBBaseHandler): id: int, data: dict, touch: bool = True, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Save: """Write `data` onto a save. @@ -258,7 +258,7 @@ class DBSavesHandler(DBBaseHandler): .values(**values) .execution_options(synchronize_session="evaluate") ) - return session.query(Save).filter_by(id=id).one() + return session.scalars(select(Save).filter_by(id=id)).one() @begin_session def prune_slot( @@ -267,7 +267,7 @@ class DBSavesHandler(DBBaseHandler): rom_id: int, slot: str, keep: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[tuple[str, str, str]]: """Delete every version of a slot past the ``keep`` newest. @@ -296,7 +296,7 @@ class DBSavesHandler(DBBaseHandler): def delete_save( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(Save) @@ -310,7 +310,7 @@ class DBSavesHandler(DBBaseHandler): rom_id: int, user_id: int, saves_to_keep: list[str], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Save]: missing_saves = session.scalars( select(Save).filter( @@ -342,7 +342,7 @@ class DBSavesHandler(DBBaseHandler): self, user_id: int, rom_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> dict: saves = session.scalars( select(Save) @@ -365,7 +365,7 @@ class DBSavesHandler(DBBaseHandler): @begin_session def count_saves_missing_content_hash( self, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: """Number of Save rows whose content_hash is NULL. Used at startup to decide whether the one-shot recompute task needs to be enqueued.""" @@ -381,7 +381,7 @@ class DBSavesHandler(DBBaseHandler): self, after_id: int, limit: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Save]: """Page Save rows by primary key. Returns up to ``limit`` rows with ``id > after_id``, ordered by id. Used by the diff --git a/backend/handler/database/screenshots_handler.py b/backend/handler/database/screenshots_handler.py index 5494f9a20..799ddc444 100644 --- a/backend/handler/database/screenshots_handler.py +++ b/backend/handler/database/screenshots_handler.py @@ -48,7 +48,7 @@ class DBScreenshotsHandler(DBBaseHandler): def add_screenshot( self, screenshot: Screenshot, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Screenshot: return session.merge(screenshot) @@ -58,7 +58,7 @@ class DBScreenshotsHandler(DBBaseHandler): *, user_id: int, rom_ids: Collection[int], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Screenshot]: return session.scalars( select(Screenshot).filter( @@ -74,7 +74,7 @@ class DBScreenshotsHandler(DBBaseHandler): user_id: int, file_name: str, file_name_no_ext: str | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Screenshot | None: query = self.filter( select(Screenshot), @@ -93,7 +93,7 @@ class DBScreenshotsHandler(DBBaseHandler): def get_screenshot_by_id( self, id, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Screenshot | None: return session.get(Screenshot, id) @@ -102,7 +102,7 @@ class DBScreenshotsHandler(DBBaseHandler): self, screenshot: Screenshot, ignoring: Save | State | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> bool: """Whether a save or state other than `ignoring` shows the screenshot as its thumbnail.""" @@ -133,7 +133,7 @@ class DBScreenshotsHandler(DBBaseHandler): def get_name_variants( self, screenshot: Screenshot, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Screenshot]: """Other screenshots in the same folder whose name differs only in case.""" query = self.filter( @@ -151,7 +151,7 @@ class DBScreenshotsHandler(DBBaseHandler): rom_id: int, user_id: int, public_only: bool = False, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Screenshot]: """Gallery (intentionally-uploaded) screenshots for a ROM, visible to the requesting user. Mirrors `db_rom_handler.get_rom_notes`: own @@ -177,7 +177,7 @@ class DBScreenshotsHandler(DBBaseHandler): self, id: int, data: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Screenshot: session.execute( update(Screenshot) @@ -185,13 +185,13 @@ class DBScreenshotsHandler(DBBaseHandler): .values(**with_file_name_parts(data)) .execution_options(synchronize_session="evaluate") ) - return session.query(Screenshot).filter_by(id=id).one() + return session.scalars(select(Screenshot).filter_by(id=id)).one() @begin_session def delete_screenshot( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(Screenshot) @@ -205,7 +205,7 @@ class DBScreenshotsHandler(DBBaseHandler): rom_id: int, user_id: int, screenshots_to_keep: list[str], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[Screenshot]: query_fn = partial( self.filter, diff --git a/backend/handler/database/states_handler.py b/backend/handler/database/states_handler.py index 909d71c23..a480ebc10 100644 --- a/backend/handler/database/states_handler.py +++ b/backend/handler/database/states_handler.py @@ -16,7 +16,7 @@ class DBStatesHandler(DBBaseHandler): def add_state( self, state: State, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> State: return session.merge(state) @@ -25,7 +25,7 @@ class DBStatesHandler(DBBaseHandler): self, user_id: int, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> State | None: return session.scalar(select(State).filter_by(user_id=user_id, id=id).limit(1)) @@ -35,7 +35,7 @@ class DBStatesHandler(DBBaseHandler): user_id: int, rom_id: int, file_name: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> State | None: return session.scalar( select(State) @@ -68,7 +68,7 @@ class DBStatesHandler(DBBaseHandler): user_id: int, rom_ids: Collection[int] | None = None, platform_id: int | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[State]: query = self._states_query( user_id=user_id, rom_ids=rom_ids, platform_id=platform_id @@ -81,7 +81,7 @@ class DBStatesHandler(DBBaseHandler): user_id: int, rom_ids: Collection[int] | None = None, platform_id: int | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> list[int]: """Ids only, so no `State` is built and no eager rom or user join fires.""" query = self._states_query( @@ -93,7 +93,7 @@ class DBStatesHandler(DBBaseHandler): def get_state_by_id( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> State | None: """Fetch a state by id without scoping to an owner. Used for the visibility toggle and community downloads, where the caller may not own @@ -106,7 +106,7 @@ class DBStatesHandler(DBBaseHandler): rom_id: int, user_id: int, public_only: bool = False, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[State]: """States for a ROM visible to the requesting user: own (public + private) plus other users' public ones. Mirrors @@ -127,7 +127,7 @@ class DBStatesHandler(DBBaseHandler): id: int, data: dict, touch: bool = True, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> State: """Write `data` onto a state. @@ -143,13 +143,13 @@ class DBStatesHandler(DBBaseHandler): .values(**values) .execution_options(synchronize_session="evaluate") ) - return session.query(State).filter_by(id=id).one() + return session.scalars(select(State).filter_by(id=id)).one() @begin_session def delete_state( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( delete(State) @@ -163,7 +163,7 @@ class DBStatesHandler(DBBaseHandler): rom_id: int, user_id: int, states_to_keep: list[str], - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[State]: missing_states = session.scalars( select(State).filter( diff --git a/backend/handler/database/stats_handler.py b/backend/handler/database/stats_handler.py index 2fdd22ec3..4762af160 100644 --- a/backend/handler/database/stats_handler.py +++ b/backend/handler/database/stats_handler.py @@ -1,6 +1,6 @@ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Collection from sqlalchemy import distinct, func, select from sqlalchemy.orm import InstrumentedAttribute, Session @@ -16,8 +16,8 @@ from .base_handler import DBBaseHandler def _exclude_hidden( query: Select, - hidden_platform_ids: Sequence[int] | None, - hidden_rom_ids: Sequence[int] | None, + hidden_platform_ids: Collection[int] | None, + hidden_rom_ids: Collection[int] | None, *, platform_id_col: InstrumentedAttribute = Rom.platform_id, rom_id_col: InstrumentedAttribute = Rom.id, @@ -38,9 +38,9 @@ class DBStatsHandler(DBBaseHandler): @begin_session def get_platforms_count( self, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, - session: Session = None, # type: ignore + hidden_platform_ids: Collection[int] | None = None, + hidden_rom_ids: Collection[int] | None = None, + session: Session = None, # type: ignore[assignment] ) -> int: """Get the number of platforms with any roms.""" query = _exclude_hidden( @@ -53,9 +53,9 @@ class DBStatsHandler(DBBaseHandler): @begin_session def get_roms_count( self, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, - session: Session = None, # type: ignore + hidden_platform_ids: Collection[int] | None = None, + hidden_rom_ids: Collection[int] | None = None, + session: Session = None, # type: ignore[assignment] ) -> int: query = _exclude_hidden( select(func.count()).select_from(Rom), @@ -67,30 +67,30 @@ class DBStatsHandler(DBBaseHandler): @begin_session def get_saves_count( self, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: return session.scalar(select(func.count()).select_from(Save)) or 0 @begin_session def get_states_count( self, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: return session.scalar(select(func.count()).select_from(State)) or 0 @begin_session def get_screenshots_count( self, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: return session.scalar(select(func.count()).select_from(Screenshot)) or 0 @begin_session def get_total_filesize( self, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, - session: Session = None, # type: ignore + hidden_platform_ids: Collection[int] | None = None, + hidden_rom_ids: Collection[int] | None = None, + session: Session = None, # type: ignore[assignment] ) -> int: """Get the total filesize of all roms in the database, in bytes.""" query = select(func.sum(RomFile.file_size_bytes)).select_from(RomFile) @@ -104,7 +104,7 @@ class DBStatsHandler(DBBaseHandler): def get_platform_filesize( self, platform_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> int: """Get the total filesize of all roms in the database, in bytes.""" return ( @@ -120,9 +120,9 @@ class DBStatsHandler(DBBaseHandler): @begin_session def get_metadata_coverage_by_platform( self, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, - session: Session = None, # type: ignore + hidden_platform_ids: Collection[int] | None = None, + hidden_rom_ids: Collection[int] | None = None, + session: Session = None, # type: ignore[assignment] ) -> dict[int, list[MetadataCoverageItem]]: """Get the count of ROMs matched per metadata source, grouped by platform. @@ -158,9 +158,9 @@ class DBStatsHandler(DBBaseHandler): @begin_session def get_region_breakdown_by_platform( self, - hidden_platform_ids: Sequence[int] | None = None, - hidden_rom_ids: Sequence[int] | None = None, - session: Session = None, # type: ignore + hidden_platform_ids: Collection[int] | None = None, + hidden_rom_ids: Collection[int] | None = None, + session: Session = None, # type: ignore[assignment] ) -> dict[int, list[RegionBreakdownItem]]: """Get the count of ROMs per region, grouped by platform. diff --git a/backend/handler/database/sync_sessions_handler.py b/backend/handler/database/sync_sessions_handler.py index 08627b731..a0116d648 100644 --- a/backend/handler/database/sync_sessions_handler.py +++ b/backend/handler/database/sync_sessions_handler.py @@ -1,7 +1,7 @@ from collections.abc import Sequence from datetime import datetime, timezone -from sqlalchemy import select, update +from sqlalchemy import and_, or_, select, update from sqlalchemy.exc import NoResultFound from sqlalchemy.orm import Session @@ -10,6 +10,10 @@ from models.sync_session import SyncSession, SyncSessionStatus from .base_handler import DBBaseHandler, affected_rows +# What a session nobody ever closed is recorded as. Sessions are opened by +# clients and by the server's own workers alike, so this names neither. +STALE_SESSION_MESSAGE = "No completion was reported before this session expired" + class DBSyncSessionsHandler(DBBaseHandler): @begin_session @@ -17,7 +21,7 @@ class DBSyncSessionsHandler(DBBaseHandler): self, device_id: str, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> SyncSession: sync_session = SyncSession( device_id=device_id, @@ -34,7 +38,7 @@ class DBSyncSessionsHandler(DBBaseHandler): self, session_id: int, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> SyncSession | None: return session.scalar( select(SyncSession).filter_by(id=session_id, user_id=user_id).limit(1) @@ -45,7 +49,7 @@ class DBSyncSessionsHandler(DBBaseHandler): self, device_id: str, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> SyncSession | None: return session.scalar( select(SyncSession) @@ -68,7 +72,7 @@ class DBSyncSessionsHandler(DBBaseHandler): self, session_id: int, data: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> SyncSession: session.execute( update(SyncSession) @@ -86,7 +90,7 @@ class DBSyncSessionsHandler(DBBaseHandler): self, session_id: int, user_id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> None: session.execute( update(SyncSession) @@ -103,30 +107,62 @@ class DBSyncSessionsHandler(DBBaseHandler): session_id: int, operations_completed: int = 0, operations_failed: int = 0, - session: Session = None, # type: ignore - ) -> SyncSession: - session.execute( - update(SyncSession) - .where(SyncSession.id == session_id) - .values( - status=SyncSessionStatus.COMPLETED, - completed_at=datetime.now(timezone.utc), - operations_completed=operations_completed, - operations_failed=operations_failed, + session: Session = None, # type: ignore[assignment] + ) -> SyncSession | None: + """Complete a session that is still open, or that the cleanup expired. + + Args: + session_id: The session to close. + operations_completed: How many operations its owner finished. + operations_failed: How many it could not. + + Returns: + The completed session, or None when it was already closed. + """ + # Decided in the statement rather than before it, so a completion and + # the cleanup landing together cannot both win. The cleanup's own + # failure is the one closed state a completion may reopen: it says + # nobody reported this, and somebody just has. A session cancelled, or + # failed by whatever ran it, was closed on purpose. + updated = affected_rows( + session.execute( + update(SyncSession) + .where( + SyncSession.id == session_id, + or_( + SyncSession.status.in_( + [SyncSessionStatus.PENDING, SyncSessionStatus.IN_PROGRESS] + ), + and_( + SyncSession.status == SyncSessionStatus.FAILED, + SyncSession.error_message == STALE_SESSION_MESSAGE, + ), + ), + ) + .values( + status=SyncSessionStatus.COMPLETED, + completed_at=datetime.now(timezone.utc), + operations_completed=operations_completed, + operations_failed=operations_failed, + # A session the cleanup gave up on, then closed by its owner, + # is a completed session rather than one still carrying why it + # was given up on. + error_message=None, + ) + .execution_options(synchronize_session="evaluate") ) - .execution_options(synchronize_session="evaluate") ) result = session.scalar(select(SyncSession).filter_by(id=session_id)) if not result: raise NoResultFound(f"SyncSession {session_id} not found after complete") - return result + return result if updated else None @begin_session def fail_session( self, session_id: int, error_message: str | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> SyncSession: session.execute( update(SyncSession) @@ -144,18 +180,23 @@ class DBSyncSessionsHandler(DBBaseHandler): return result @begin_session - def cancel_active_sessions( + def fail_stale_sessions( self, - device_id: str, - user_id: int, - session: Session = None, # type: ignore + older_than: datetime, + session: Session = None, # type: ignore[assignment] ) -> int: - """Cancel all active sessions for a device. Returns count of cancelled sessions.""" + """Fail every session opened before ``older_than`` and never closed. + + Args: + older_than: The moment a session still open is past accounting for. + + Returns: + How many rows were failed. + """ result = session.execute( update(SyncSession) .where( - SyncSession.device_id == device_id, - SyncSession.user_id == user_id, + SyncSession.initiated_at < older_than, SyncSession.status.in_( [ SyncSessionStatus.PENDING, @@ -164,8 +205,9 @@ class DBSyncSessionsHandler(DBBaseHandler): ), ) .values( - status=SyncSessionStatus.CANCELLED, + status=SyncSessionStatus.FAILED, completed_at=datetime.now(timezone.utc), + error_message=STALE_SESSION_MESSAGE, ) .execution_options(synchronize_session="evaluate") ) @@ -178,7 +220,7 @@ class DBSyncSessionsHandler(DBBaseHandler): device_id: str | None = None, status: SyncSessionStatus | None = None, limit: int = 50, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[SyncSession]: query = select(SyncSession).filter_by(user_id=user_id) diff --git a/backend/handler/database/users_handler.py b/backend/handler/database/users_handler.py index 935118ede..015970a1e 100644 --- a/backend/handler/database/users_handler.py +++ b/backend/handler/database/users_handler.py @@ -41,7 +41,7 @@ class DBUsersHandler(DBBaseHandler): def add_user( self, user: User, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> User: return session.merge(user) @@ -49,7 +49,7 @@ class DBUsersHandler(DBBaseHandler): def get_user_by_username( self, username: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> User | None: query = self.filter(select(User), usernames=[username]) return session.scalar(query.limit(1)) @@ -58,7 +58,7 @@ class DBUsersHandler(DBBaseHandler): def get_user_by_email( self, email: str, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> User | None: query = self.filter(select(User), emails=[email]) return session.scalar(query.limit(1)) @@ -67,7 +67,7 @@ class DBUsersHandler(DBBaseHandler): def get_user( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> User | None: return session.get(User, id) @@ -76,7 +76,7 @@ class DBUsersHandler(DBBaseHandler): self, id: int, data: dict, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> User: session.execute( update(User) @@ -84,7 +84,7 @@ class DBUsersHandler(DBBaseHandler): .values(**data) .execution_options(synchronize_session="evaluate") ) - return session.query(User).filter_by(id=id).one() + return session.scalars(select(User).filter_by(id=id)).one() @begin_session def get_users( @@ -95,7 +95,7 @@ class DBUsersHandler(DBBaseHandler): roles: Sequence[Role] = (), has_ra_username: bool | None = None, only_fields: Sequence[QueryableAttribute] | None = None, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[User]: query = self.filter( select(User), @@ -114,7 +114,7 @@ class DBUsersHandler(DBBaseHandler): def delete_user( self, id: int, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ): return session.execute( delete(User) @@ -125,7 +125,7 @@ class DBUsersHandler(DBBaseHandler): @begin_session def get_admin_users( self, - session: Session = None, # type: ignore + session: Session = None, # type: ignore[assignment] ) -> Sequence[User]: query = self.filter(select(User), roles=[Role.ADMIN]) return session.scalars(query).all() diff --git a/backend/handler/metadata/gamelist_handler.py b/backend/handler/metadata/gamelist_handler.py index 8b88ffe7d..5b85f5cc8 100644 --- a/backend/handler/metadata/gamelist_handler.py +++ b/backend/handler/metadata/gamelist_handler.py @@ -564,7 +564,7 @@ class GamelistHandler(MetadataHandler): # Populate ROM-specific paths using the actual rom object if gamelist_metadata: rom_specific_paths = populate_rom_specific_paths(gamelist_metadata, rom) - gamelist_metadata.update(**rom_specific_paths) # type: ignore + gamelist_metadata.update(**rom_specific_paths) # type: ignore[call-arg] matched_rom["gamelist_metadata"] = gamelist_metadata return matched_rom diff --git a/backend/handler/metadata/ss_handler.py b/backend/handler/metadata/ss_handler.py index 684d5e442..72ea96997 100644 --- a/backend/handler/metadata/ss_handler.py +++ b/backend/handler/metadata/ss_handler.py @@ -739,9 +739,7 @@ def extract_tags_from_ss_dump(dump: SSGameRom) -> list[str]: """Tags of one dump, from the flags it raises.""" # ScreenScraper sends these flags as "1", not 1. return [ - tag - for key, tag in _SS_DUMP_FLAG_TAGS - if str(dump.get(key, "")).strip() == "1" # type: ignore[literal-required] + tag for key, tag in _SS_DUMP_FLAG_TAGS if str(dump.get(key, "")).strip() == "1" ] diff --git a/backend/handler/notification_channels/__init__.py b/backend/handler/notification_channels/__init__.py index 5008cecfb..d4be3f7b9 100644 --- a/backend/handler/notification_channels/__init__.py +++ b/backend/handler/notification_channels/__init__.py @@ -1 +1 @@ -"""Forwarding a user's notifications to their webhooks and email addresses.""" +"""Forwarding a user's notifications to Apprise services, webhooks and email addresses.""" diff --git a/backend/handler/notification_channels/apprise_channel.py b/backend/handler/notification_channels/apprise_channel.py new file mode 100644 index 000000000..e5ad60a32 --- /dev/null +++ b/backend/handler/notification_channels/apprise_channel.py @@ -0,0 +1,761 @@ +"""Deliveries through Apprise, which reaches 100+ services from a URL built from their fields.""" + +import json +import logging +import re +from collections.abc import Mapping +from contextvars import ContextVar +from dataclasses import dataclass +from functools import cache, cached_property +from typing import Any, Final, Literal, get_args +from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit + +from apprise import ( + Apprise, + AppriseAsset, + NotificationManager, + NotifyBase, + NotifyFormat, + NotifyType, +) +from apprise.utils.parse import parse_bool + +from logger.logger import log +from models.notification import NotificationLevel + +from .messages import OutboundMessage +from .webhook import ERROR_DETAIL_CHARS + +ADMINS_ONLY: Final = "Only admins can use Apprise channels" + +# A service can ask for longer (?cto=, ?rto=), which would hold a worker. +CONNECT_TIMEOUT_SECONDS: Final = 10.0 +READ_TIMEOUT_SECONDS: Final = 15.0 + +# Schemas that act on the machine running RomM instead of reaching a service, +# and FCM, which opens its key file from a path or URL itself. +EXCLUDED_SCHEMAS: Final = frozenset( + { + "syslog", + "windows", + "macosx", + "dbus", + "gnome", + "kde", + "qt", + "glib", + "blink1", + "fcm", + } +) +# Options Apprise loads as a local file or a URL it fetches. +FILE_OPTIONS: Final = frozenset( + {"template", "keyfile", "subfile", "pgppub", "pgpkey", "pgpprv"} +) +# Options every service shares that are set here or don't apply. +MANAGED_OPTIONS: Final = frozenset( + { + "cto", + "rto", + "retry", + "wait", + "redirect", + "store", + "optional", + "overflow", + "format", + "emojis", + "tz", + } +) +# Where Apprise's setup guides live, one page per service. +WIKI_PAGE: Final = "https://github.com/caronc/apprise/wiki/Notify_{}" +# Services Apprise reads a URL of their own for (a Discord webhook's), whose +# native URL only covers a corner of what they do, so they keep their fields. +FIELD_SERVICES: Final = frozenset({"matrix", "lametric", "46elks", "wechat"}) +# Where a URL points and whom it signs in as. +_URL_PARTS: Final = frozenset( + {"schema", "host", "port", "user", "password", "path", "fullpath"} +) +# Services that post to any path on their host, which no token names. +FREE_PATH_SERVICES: Final = frozenset({"json", "xml", "form"}) +# Tokens Apprise doesn't mark private although they are credentials. +_SECRET_NAME: Final = re.compile(r"token|key|secret|pass|webhook|auth|sid", re.I) +# Chat services turn these into pings of a whole server or a role. +_MENTIONS: Final = re.compile(r"@(everyone|here)\b|<[@!]") + +NOTIFY_TYPES: Final[dict[str, NotifyType]] = { + NotificationLevel.INFO: NotifyType.INFO, + NotificationLevel.SUCCESS: NotifyType.SUCCESS, + NotificationLevel.WARNING: NotifyType.WARNING, + NotificationLevel.ERROR: NotifyType.FAILURE, +} + +# What a service shows as the sender's picture, such as Discord's avatar; it +# fetches it itself, so it has to be public. +ROMM_ICON_URL: Final = ( + "https://raw.githubusercontent.com/rommapp/romm/master/" + "frontend/public/android-chrome-512x512.png" +) + +_ASSET: Final = AppriseAsset( + app_id="RomM", + app_desc="RomM", + app_url="https://romm.app", + image_url_mask=ROMM_ICON_URL, + image_url_logo=ROMM_ICON_URL, + # Nothing a plugin keeps (tokens, generated keys) is written to disk. + storage_mode="memory", + pgp_autogen=False, + pem_autogen=False, + http_redirects=False, + secure_logging=True, +) + +_PLACEHOLDER: Final = re.compile(r"{(\w+)}") +# A hostname, an IPv4 address or a bracketed IPv6 one. +_HOST: Final = re.compile(r"\[[0-9a-f:.]+\]|[\w.-]+", re.I) +# A token that is a URL path, which Apprise wants between slashes. +_PATH_TOKEN: Final = "path" + +FieldType = Literal["string", "int", "float", "bool", "choice", "list"] +FieldValue = str | int | float | bool | list[str] + +# What Apprise logs about the send running in this context: its warnings, and +# the start of a refusal's reply, which says why (Discord's "Invalid Form Body"). +_collected: ContextVar[list[str] | None] = ContextVar("apprise_log", default=None) +_REPLY: Final = "Response Details:" + + +class _Collector(logging.Handler): + def emit(self, record: logging.LogRecord) -> None: + collected = _collected.get() + if record.levelno >= logging.WARNING: + if collected is None: + # No send reports it, so it goes to the server log. + log.warning(f"Apprise: {record.getMessage()}") + else: + collected.append(record.getMessage()) + elif collected is not None and str(record.msg).startswith(_REPLY): + reply = record.getMessage().removeprefix(_REPLY).strip() + # Apprise logs the body as a bytes repr, b'...'. + if reply[:2] in ("b'", 'b"'): + reply = reply[2:-1] + if reply: + collected.append(f"Reply: {reply[:ERROR_DETAIL_CHARS]}") + + +_apprise_log = logging.getLogger("apprise") +# Down to debug, where the replies are, and past the server log: a send's +# failure is logged once, as the delivery's error. +_apprise_log.setLevel(logging.DEBUG) +_apprise_log.propagate = False +_apprise_log.addHandler(_Collector()) + + +class AppriseError(RuntimeError): + """The service refused the notification or could not be reached.""" + + +@dataclass(frozen=True) +class AppriseField: + key: str + label: str + type: FieldType + required: bool + private: bool + # An option sent as a query argument rather than part of the URL itself. + advanced: bool + default: str | int | float | bool | None = None + values: tuple[str | int, ...] | None = None + min: float | None = None + max: float | None = None + # Separates a list's items in the URL. + delimiter: str = "," + # Singular tokens a template can take instead of this list. + members: tuple[str, ...] = () + + +@dataclass(frozen=True) +class AppriseService: + id: str + name: str + setup_url: str | None + schemas: tuple[str, ...] + default_schema: str + templates: tuple[str, ...] + fields: tuple[AppriseField, ...] + # The fields the URL a service gives out (a Discord webhook's) fills in, + # when it's set up from that URL; empty for a service without one. + url_fields: tuple[str, ...] = () + + @cached_property + def _by_key(self) -> dict[str, AppriseField]: + return {field.key: field for field in self.fields} + + @cached_property + def owners(self) -> dict[str, AppriseField]: + """The list each singular token belongs to.""" + return {member: field for field in self.fields for member in field.members} + + @cached_property + def patterns(self) -> tuple[re.Pattern[str], ...]: + """Each template as a pattern for the URL Apprise writes, fullest first.""" + ordered = sorted( + self.templates, key=lambda t: len(_PLACEHOLDER.findall(t)), reverse=True + ) + return tuple(_template_pattern(self, template) for template in ordered) + + @cached_property + def secrets(self) -> frozenset[str]: + return frozenset(field.key for field in self.fields if field.private) + + def field(self, key: str) -> AppriseField | None: + return self._by_key.get(key) + + +def _setup_url(url: str | None) -> str | None: + """The service's guide on Apprise's wiki, when Apprise points at appriseit.com.""" + parts = urlsplit(url or "") + if parts.hostname != "appriseit.com": + return url + slug = parts.path.rstrip("/").rsplit("/", 1)[-1] + return WIKI_PAGE.format(slug) if slug else None + + +def _field( + key: str, meta: dict[str, Any], *, advanced: bool, required: bool = False +) -> AppriseField | None: + # Apprise's `choice:string` or `list:int`, by the form control it needs. + kind = meta.get("type", "string").split(":", 1)[0] + if kind not in get_args(FieldType): + return None + values = meta.get("values") + private = bool(meta.get("private")) or ( + not advanced and kind == "string" and bool(_SECRET_NAME.search(key)) + ) + return AppriseField( + key=key, + label=meta.get("name") or key, + type=kind, + required=required, + private=private, + advanced=advanced, + default=meta.get("default"), + values=tuple(values) if values else None, + min=meta.get("min"), + max=meta.get("max"), + delimiter=(meta.get("delim") or [","])[0], + members=tuple(sorted(meta.get("group") or ())), + ) + + +def _service(entry: dict[str, Any]) -> AppriseService | None: + details = entry["details"] + tokens: dict[str, dict[str, Any]] = details["tokens"] + templates = tuple(details["templates"]) + placeholders = [set(_PLACEHOLDER.findall(template)) for template in templates] + protocols = [ + *(entry.get("protocols") or []), + *(entry.get("secure_protocols") or []), + ] + if not protocols or not templates or EXCLUDED_SCHEMAS & set(protocols): + return None + + secure = entry.get("secure_protocols") or [] + default_schema = secure[0] if secure else protocols[0] + members = {member for meta in tokens.values() for member in meta.get("group") or ()} + fields: list[AppriseField] = [] + if len(protocols) > 1: + fields.append( + AppriseField( + key="schema", + label=tokens.get("schema", {}).get("name") or "Schema", + type="choice", + required=True, + private=False, + advanced=False, + default=default_schema, + values=tuple(protocols), + ) + ) + for key, meta in tokens.items(): + if key == "schema" or key in members: + continue + spelled = {key, *(meta.get("group") or ())} + # Alternative credentials are each required somewhere, so only what + # every template needs is required. + required = all(spelled & needed for needed in placeholders) + field = _field(key, meta, advanced=False, required=required) + if field: + fields.append(field) + + if protocols[0] in FREE_PATH_SERVICES: + # A webhook's path often carries its token. + fields.append( + AppriseField( + key=_PATH_TOKEN, + label="Path", + type="string", + required=False, + private=True, + advanced=False, + ) + ) + + shown = {field.key for field in fields} + for key, meta in details["args"].items(): + if ( + "alias_of" in meta + or key in shown + or key in tokens + or key in FILE_OPTIONS + or key in MANAGED_OPTIONS + ): + continue + field = _field(key, meta, advanced=True) + if field: + fields.append(field) + + plugin = NotificationManager()[protocols[0]] + native = ( + protocols[0] not in FIELD_SERVICES + and plugin.parse_native_url is not NotifyBase.parse_native_url + ) + # Such a URL holds what the service needs, where and whom it signs in as; + # what it lacks (a Discord bot name) stays a field. + url_fields = tuple( + field.key + for field in fields + if native + and not field.advanced + and (field.required or field.private or field.key in _URL_PARTS) + ) + return AppriseService( + url_fields=url_fields, + id=protocols[0], + name=entry.get("service_name") or protocols[0], + setup_url=_setup_url(entry.get("setup_url")), + schemas=tuple(protocols), + default_schema=default_schema, + templates=templates, + fields=tuple(fields), + ) + + +@cache +def services() -> tuple[AppriseService, ...]: + """Every service Apprise can reach from here, by name.""" + # Apprise's own serializer, as its details hold sets; it answers False + # when it can't serialize them. + serialized = Apprise().json() + if not isinstance(serialized, str): + return () + found = (_service(entry) for entry in json.loads(serialized)["schemas"]) + return tuple(sorted((s for s in found if s), key=lambda s: s.name.lower())) + + +@cache +def _services_by_id() -> dict[str, AppriseService]: + return {service.id: service for service in services()} + + +def find_service(service_id: str) -> AppriseService: + """Raises: + ValueError: RomM has no such Apprise service. + """ + service = _services_by_id().get(service_id) + if service is None: + raise ValueError("Apprise has no such service") + return service + + +def _blank(value: object) -> bool: + return value is None or value == "" or value == [] + + +def known_fields( + service: AppriseService, fields: Mapping[str, FieldValue] +) -> dict[str, FieldValue]: + """The fields the service takes that were filled in, defaults left out.""" + return { + key: value + for key, value in fields.items() + if (field := service.field(key)) is not None + and not _blank(value) + and value != field.default + } + + +def _scrub(text: str, service: AppriseService, fields: Mapping[str, FieldValue]) -> str: + """The text with the channel's secrets hidden, as Apprise may quote them.""" + for key in service.secrets: + value = fields.get(key) + if value is None or _blank(value): + continue + for secret in value if isinstance(value, list) else [value]: + for form in {str(secret), quote(str(secret), safe="")}: + text = text.replace(form, "****") + return text + + +def _text(field: AppriseField, value: FieldValue) -> str: + if isinstance(value, bool): + return "yes" if value else "no" + if isinstance(value, list): + return field.delimiter.join(str(item) for item in value) + return str(value) + + +def _segment(field: AppriseField, value: FieldValue) -> str: + """A token's value as it sits in the URL.""" + if field.key == "host": + text = str(value).strip() + if not _HOST.fullmatch(text): + raise ValueError(f"{field.label} isn't a hostname") + return text + if field.key == _PATH_TOKEN: + # Gotify's {host}{path}{token} needs the path between slashes. + path = str(value).strip("/") + return f"/{quote(path)}/" if path else "/" + if isinstance(value, list): + return field.delimiter.join(quote(str(item), safe="") for item in value) + return quote(str(value), safe="") + + +def _fill( + service: AppriseService, template: str, tokens: dict[str, FieldValue] +) -> tuple[str, set[str]] | None: + """The template with its tokens filled in and the tokens it took, or None + when it needs one that wasn't given.""" + filled, used = template, set() + for key in _PLACEHOLDER.findall(template): + field = service.field(key) + if field is not None and key in tokens: + text = _segment(field, tokens[key]) + used.add(key) + elif (owner := service.owners.get(key)) is not None: + # A singular token can come from its list when that holds one item. + items = tokens.get(owner.key) + if not isinstance(items, list) or len(items) != 1: + return None + text = quote(str(items[0]), safe="") + used.add(owner.key) + elif key == "schema": + continue + else: + return None + filled = filled.replace(f"{{{key}}}", text, 1) + return filled, used + + +def build_url(service: AppriseService, fields: Mapping[str, FieldValue]) -> str: + """The Apprise URL for a service's fields. + + Raises: + ValueError: With a reason fit to show the user. + """ + tokens: dict[str, FieldValue] = {} + options: dict[str, str] = {} + for key, value in known_fields(service, fields).items(): + field = service.field(key) + if field is None or key == "schema": + continue + if field.advanced: + options[key] = _text(field, value) + else: + tokens[key] = value + schema = str(fields.get("schema") or service.default_schema) + if schema not in service.schemas: + raise ValueError(f"{service.name} doesn't take {schema}://") + + extra_path = ( + tokens.pop(_PATH_TOKEN, None) if service.id in FREE_PATH_SERVICES else None + ) + fit = next( + ( + filled + for template in service.templates + if (filled := _fill(service, template, tokens)) and filled[1] == set(tokens) + ), + None, + ) + if fit is None: + missing = [ + f.label + for f in service.fields + if f.required and f.key != "schema" and f.key not in tokens + ] + raise ValueError( + f"{service.name} needs {', '.join(missing)}" + if missing + else f"{service.name} can't take these fields together" + ) + + url = fit[0].replace("{schema}", schema, 1) + if extra_path: + url += "/" + quote(str(extra_path).lstrip("/")) + return f"{url}?{urlencode(options)}" if options else url + + +def _plugin(service: AppriseService, fields: Mapping[str, FieldValue]) -> NotifyBase: + """Raises: + ValueError: With a reason fit to show the user, secrets hidden. + """ + try: + plugin = Apprise.instantiate( + build_url(service, fields), asset=_ASSET, suppress_exceptions=False + ) + except Exception as exc: # noqa: BLE001 - a plugin says why it refused the URL + reason = str(exc) or "Apprise can't use these fields" + raise ValueError(_scrub(reason, service, fields)) from exc + if plugin is None: + raise ValueError("Apprise can't use these fields") + return plugin + + +def checked_fields( + service_id: str, fields: Mapping[str, FieldValue] +) -> dict[str, FieldValue]: + """The fields to keep, once Apprise can deliver with them. + + Raises: + ValueError: With a reason fit to show the user. + """ + service = find_service(service_id) + kept = known_fields(service, fields) + _plugin(service, kept) + return kept + + +def describe( + service_id: str, fields: Mapping[str, FieldValue] +) -> tuple[str | None, str]: + """The service's name, and its URL with the secrets and options hidden.""" + try: + service = find_service(service_id) + plugin = _plugin(service, fields) + except ValueError: + return None, "" + scheme, netloc, path, _, _ = urlsplit(plugin.url(privacy=True)) + target = urlunsplit((scheme, netloc, path, "", "")) + return service.name, _scrub(target, service, fields) + + +def split_fields( + service_id: str, fields: Mapping[str, FieldValue] +) -> tuple[dict[str, FieldValue], list[str]]: + """The fields that aren't secrets, for the owner's form, and which secrets are set.""" + try: + service = find_service(service_id) + except ValueError: + return {}, [] + kept = known_fields(service, fields) + public = {k: v for k, v in kept.items() if k not in service.secrets} + return public, [key for key in kept if key in service.secrets] + + +# What each kind of template token matches in the URL Apprise writes. +_TOKEN_PATTERNS: Final = { + "schema": r"[a-z0-9+.-]+", + "host": _HOST.pattern, + "port": r"\d+", + "user": r"[^/:@?#]+", + _PATH_TOKEN: r"/(?:[^?#]*/)?", +} + + +def _token_pattern(service: AppriseService, key: str) -> str: + if key in _TOKEN_PATTERNS: + return _TOKEN_PATTERNS[key] + field = service.field(key) + return r".+" if field is not None and field.type == "list" else r"[^/@?#]+" + + +def _template_pattern(service: AppriseService, template: str) -> re.Pattern[str]: + template = template.rstrip("/") + pattern, end = "", 0 + for match in _PLACEHOLDER.finditer(template): + key = match.group(1) + pattern += re.escape(template[end : match.start()]) + pattern += f"(?P<{key}>{_token_pattern(service, key)})" + end = match.end() + return re.compile(pattern + re.escape(template[end:]), re.I) + + +def _read(field: AppriseField, text: str, quoted: bool) -> FieldValue | None: + """A value as it sits in the URL, back in the field's type.""" + if field.type == "list": + items = re.split(rf"[{re.escape(field.delimiter)},\s]+", text) + return [unquote(item) if quoted else item for item in items if item] + text = unquote(text) if quoted else text + if field.type == "bool": + return parse_bool(text) + if field.type in ("int", "float"): + try: + return int(text) if field.type == "int" else float(text) + except ValueError: + return None + return text + + +def fields_from_url(url: str) -> tuple[AppriseService, dict[str, FieldValue]]: + """The service and fields behind an Apprise URL or a service's own, such as + a Discord webhook's. + + Raises: + ValueError: With a reason fit to show the user. + """ + url = url.strip() + if not url or any(char.isspace() for char in url): + raise ValueError("Paste one URL, without spaces") + pasted = urlsplit(url) + if pasted.scheme.lower() in EXCLUDED_SCHEMAS: + raise ValueError("RomM doesn't offer that service") + if {key.lower() for key, _ in parse_qsl(pasted.query)} & FILE_OPTIONS: + raise ValueError("RomM doesn't take the options that read local files") + try: + plugin = Apprise.instantiate(url, asset=_ASSET, suppress_exceptions=False) + except Exception as exc: # noqa: BLE001 - a plugin says why it refused the URL + raise ValueError(str(exc) or "Apprise can't read this URL") from exc + if plugin is None: + raise ValueError("Apprise can't read this URL") + + parts = urlsplit(plugin.url(privacy=False)) + service = next((s for s in services() if parts.scheme in s.schemas), None) + if service is None: + raise ValueError("RomM doesn't offer that service") + + fields: dict[str, FieldValue] = {} + base = f"{parts.scheme}://{parts.netloc}{parts.path}".rstrip("/") + if service.id in FREE_PATH_SERVICES: + fields[_PATH_TOKEN] = unquote(parts.path.strip("/")) + base = f"{parts.scheme}://{parts.netloc}" + match = next((m for p in service.patterns if (m := p.fullmatch(base))), None) + if match is None: + raise ValueError(f"RomM can't read the {service.name} fields from this URL") + + for key, text in match.groupdict().items(): + field = service.owners.get(key) or service.field(key) + if field is None or key == "schema" or not text: + continue + if (value := _read(field, text, quoted=True)) is not None: + fields[field.key] = value + for key, text in parse_qsl(parts.query, keep_blank_values=True): + field = service.field(key) + if field is None or not field.advanced: + continue + if (value := _read(field, text, quoted=False)) is not None: + fields[key] = value + if len(service.schemas) > 1: + fields["schema"] = parts.scheme + fields = known_fields(service, fields) + # The fields must make the same URL again, or a token was misread. + if _address(_plugin(service, fields).url(privacy=False)) != _address( + plugin.url(privacy=False) + ): + raise ValueError(f"RomM can't read the {service.name} fields from this URL") + return service, fields + + +def _address(url: str) -> tuple[str, str, str]: + """A URL's scheme, authority and path, as Apprise writes it.""" + parts = urlsplit(url) + return parts.scheme.lower(), parts.netloc, unquote(parts.path).rstrip("/") + + +def _destination(service: AppriseService, fields: Mapping[str, FieldValue]) -> Any: + """Where the fields send to, as Apprise tells its URLs apart, or None.""" + try: + return _plugin(service, fields).url_identifier or None + except ValueError: + return None + + +def merge_fields( + service_id: str, + stored: Mapping[str, FieldValue], + given: Mapping[str, FieldValue], +) -> dict[str, FieldValue]: + """The fields after an edit: a secret left out keeps its value, an empty one goes. + + Raises: + ValueError: A secret would stay while the address it goes to changes. + """ + service = find_service(service_id) + merged = known_fields(service, given) + kept = { + key: value + for key, value in stored.items() + if key in service.secrets and key not in given + } + if kept: + secrets = {k: v for k, v in stored.items() if k in service.secrets} + before = {k: v for k, v in stored.items() if k not in service.secrets} + after = {k: v for k, v in merged.items() if k not in service.secrets} + # The same secrets on both sides, so only a new address counts. + was = _destination(service, {**before, **secrets}) + now = _destination(service, {**after, **secrets}) + moved = was != now if was is not None and now is not None else before != after + if moved: + labels = ", ".join( + field.label for field in service.fields if field.key in kept + ) + raise ValueError( + f"Enter {labels} again for the new address, " + f"or remove {'it' if len(kept) == 1 else 'them'}" + ) + return {**merged, **kept} + + +def _defuse_mentions(text: str) -> str: + """The text with its mentions broken by a zero-width space, so they ping nobody.""" + return _MENTIONS.sub(lambda m: m.group(0)[0] + "\u200b" + m.group(0)[1:], text) + + +def _bounded(plugin: NotifyBase) -> NotifyBase: + plugin.redirects = False + # RQ retries a failed delivery on its own schedule. + plugin.retry = 0 + plugin.socket_connect_timeout = min( + plugin.socket_connect_timeout or CONNECT_TIMEOUT_SECONDS, + CONNECT_TIMEOUT_SECONDS, + ) + plugin.socket_read_timeout = min( + plugin.socket_read_timeout or READ_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS + ) + return plugin + + +def send( + service_id: str, fields: Mapping[str, FieldValue], message: OutboundMessage +) -> None: + """Deliver the message through Apprise; blocks until the service answers. + + Raises: + ValueError: The fields no longer make a URL Apprise can use. + AppriseError: The service refused it, or could not be reached. + """ + service = find_service(service_id) + plugin = _bounded(_plugin(service, fields)) + apprise = Apprise(asset=_ASSET) + apprise.add(plugin) + + collected: list[str] = [] + token = _collected.set(collected) + try: + sent = apprise.notify( + body=_defuse_mentions(message.text), + title=_defuse_mentions(message.title), + notify_type=NOTIFY_TYPES.get(message.notification.level, NotifyType.INFO), + body_format=NotifyFormat.TEXT, + ) + finally: + _collected.reset(token) + + if not sent: + reason = " ".join(dict.fromkeys(collected)) + raise AppriseError( + _scrub(reason, service, fields) + or f"{plugin.service_name} did not take the notification" + ) diff --git a/backend/handler/notification_channels/channels.py b/backend/handler/notification_channels/channels.py index 684b1a2b9..4eba96c79 100644 --- a/backend/handler/notification_channels/channels.py +++ b/backend/handler/notification_channels/channels.py @@ -1,6 +1,7 @@ """Adding, changing, testing and confirming a user's notification channels.""" -from collections.abc import Sequence +import asyncio +from collections.abc import Mapping, Sequence from datetime import datetime, timezone from typing import Any @@ -12,13 +13,22 @@ from models.notification_channel import ( NotificationChannel, NotificationChannelMinLevel, NotificationChannelType, - WebhookFormat, ) from models.user import User -from .config import EmailConfig, WebhookConfig, origin, read_config, seal_config +from . import apprise_channel +from .apprise_channel import FieldValue +from .config import ( + AppriseConfig, + EmailConfig, + WebhookConfig, + origin, + read_config, + seal_config, +) from .confirmation import check_code, issue_code from .delivery import ( + DELIVERY_TIMEOUT_SECONDS, describe_error, may_reach_private_network, sample_message, @@ -31,16 +41,30 @@ class ChannelError(ValueError): """A change the channel can't take, worded for the user.""" -def _webhook_config( - url: str, format: WebhookFormat, secret: str | None, user: User -) -> WebhookConfig: - """A webhook's config once its URL checks out; Discord takes no secret.""" +def _require_apprise(user: User) -> None: + if not may_reach_private_network(user.role): + raise ChannelError(apprise_channel.ADMINS_ONLY) + + +def _apprise_config( + service: str, fields: Mapping[str, FieldValue], user: User +) -> AppriseConfig: + """An Apprise channel's config once its owner and fields check out.""" + _require_apprise(user) try: - check_url(url, format, allow_private=may_reach_private_network(user.role)) + kept = apprise_channel.checked_fields(service, fields) except ValueError as exc: raise ChannelError(str(exc)) from exc - secret = None if format == WebhookFormat.DISCORD else secret - return WebhookConfig(url=url, format=format, secret=secret or None) + return AppriseConfig(service=service, fields=kept) + + +def _webhook_config(url: str, secret: str | None, user: User) -> WebhookConfig: + """A webhook's config once its URL checks out.""" + try: + check_url(url, allow_private=may_reach_private_network(user.role)) + except ValueError as exc: + raise ChannelError(str(exc)) from exc + return WebhookConfig(url=url, secret=secret or None) def _require_email() -> None: @@ -56,9 +80,10 @@ async def create_channel( topics: Sequence[NotificationTopic] | None, *, url: str | None = None, - format: WebhookFormat = WebhookFormat.JSON, secret: str | None = None, address: str | None = None, + service: str | None = None, + fields: Mapping[str, FieldValue] | None = None, ) -> NotificationChannel: """Add a channel; an email address gets a code to confirm it with first. @@ -67,18 +92,23 @@ async def create_channel( CodeCooldownError, EmailError: The confirmation code could not go out, in which case the channel is not kept. """ - config: WebhookConfig | EmailConfig - if type == NotificationChannelType.EMAIL: - _require_email() - if not address: - raise ChannelError("An email channel needs an address") - config = EmailConfig(address=address) - confirmed_at = None - else: - if not url: - raise ChannelError("A webhook needs a URL") - config = _webhook_config(url, format, secret, user) - confirmed_at = datetime.now(timezone.utc) + config: AppriseConfig | WebhookConfig | EmailConfig + confirmed_at: datetime | None = datetime.now(timezone.utc) + match type: + case NotificationChannelType.EMAIL: + _require_email() + if not address: + raise ChannelError("An email channel needs an address") + config = EmailConfig(address=address) + confirmed_at = None + case NotificationChannelType.APPRISE: + if not service: + raise ChannelError("An Apprise channel needs a service") + config = _apprise_config(service, fields or {}, user) + case _: + if not url: + raise ChannelError("A webhook needs a URL") + config = _webhook_config(url, secret, user) channel = db_notification_channel_handler.add_channel( NotificationChannel( @@ -114,16 +144,17 @@ async def update_channel( changes: dict[str, Any], *, url: str | None = None, - format: WebhookFormat | None = None, secret: str | None = None, secret_given: bool = False, address: str | None = None, + fields: Mapping[str, FieldValue] | None = None, ) -> NotificationChannel: """Change a channel; a new email address has to be confirmed again. Args: changes: New values for the name, `enabled`, `min_level` and `topics`. secret_given: Whether `secret` was sent, since an empty one drops it. + fields: An Apprise channel's fields, where a secret left out stays. Raises: ChannelError: The change can't be made as asked. @@ -136,33 +167,38 @@ async def update_channel( changes["consecutive_failures"] = 0 config = read_config(channel.config) - if channel.type == NotificationChannelType.EMAIL: - if address and address != config.get("address"): - _require_email() - # The code goes out first, so an address it can't reach isn't kept. - await issue_code(channel.id, user.id, address) - changes["config"] = seal_config(EmailConfig(address=address)) - changes["confirmed_at"] = None - elif url or format or secret_given: - new_url = url or config.get("url") - new_format = WebhookFormat(format or config.get("format") or WebhookFormat.JSON) - if not new_url: - raise ChannelError("The channel needs its URL again") - new_config = _webhook_config( - new_url, - new_format, - secret if secret_given else config.get("secret"), - user, - ) - moved = new_format != config.get("format") or origin(new_url) != origin( - config.get("url", "") - ) - # A kept secret only goes where it was given for. - if moved and not secret_given and new_config.get("secret"): - raise ChannelError( - "Enter the secret again for the new URL or format, or remove it" + match channel.type: + case NotificationChannelType.EMAIL: + if address and address != config.get("address"): + _require_email() + # The code goes out first, so an address it can't reach isn't kept. + await issue_code(channel.id, user.id, address) + changes["config"] = seal_config(EmailConfig(address=address)) + changes["confirmed_at"] = None + case NotificationChannelType.APPRISE: + if fields is not None: + service = config.get("service", "") + try: + merged = apprise_channel.merge_fields( + service, config.get("fields", {}), fields + ) + except ValueError as exc: + raise ChannelError(str(exc)) from exc + changes["config"] = seal_config(_apprise_config(service, merged, user)) + case _ if url or secret_given: + new_url = url or config.get("url") + if not new_url: + raise ChannelError("The channel needs its URL again") + new_config = _webhook_config( + new_url, secret if secret_given else config.get("secret"), user ) - changes["config"] = seal_config(new_config) + moved = origin(new_url) != origin(config.get("url", "")) + # A kept secret only goes where it was given for. + if moved and not secret_given and new_config.get("secret"): + raise ChannelError( + "Enter the secret again for the new URL, or remove it" + ) + changes["config"] = seal_config(new_config) if not changes: return channel @@ -181,11 +217,12 @@ async def send_sample(channel: NotificationChannel, user: User) -> str | None: if channel.confirmed_at is None: raise ChannelError("Confirm the email address first") try: - await send_to_channel( - channel, - sample_message(), - allow_private=may_reach_private_network(user.role), - ) + async with asyncio.timeout(DELIVERY_TIMEOUT_SECONDS): + await send_to_channel( + channel, + sample_message(), + allow_private=may_reach_private_network(user.role), + ) except Exception as exc: # noqa: BLE001 - the error goes back to the user error = describe_error(exc) db_notification_channel_handler.record_failure(channel.id, error, counts=False) diff --git a/backend/handler/notification_channels/config.py b/backend/handler/notification_channels/config.py index 8334aaa7c..8caf8411b 100644 --- a/backend/handler/notification_channels/config.py +++ b/backend/handler/notification_channels/config.py @@ -6,10 +6,15 @@ from urllib.parse import urlsplit from utils.secret_box import UnsealError, seal, unseal +class AppriseConfig(TypedDict): + service: str + # What the owner filled in, which the Apprise URL is built from. + fields: dict[str, Any] + + class WebhookConfig(TypedDict): url: str - format: str - # The HMAC key of a JSON webhook, or the access token of an ntfy topic. + # The key the payload is signed with. secret: NotRequired[str | None] @@ -17,7 +22,7 @@ class EmailConfig(TypedDict): address: str -def seal_config(config: WebhookConfig | EmailConfig) -> str: +def seal_config(config: AppriseConfig | WebhookConfig | EmailConfig) -> str: return seal(dict(config)) diff --git a/backend/handler/notification_channels/delivery.py b/backend/handler/notification_channels/delivery.py index aec68f602..5fa6e86bf 100644 --- a/backend/handler/notification_channels/delivery.py +++ b/backend/handler/notification_channels/delivery.py @@ -30,7 +30,8 @@ _LEVEL_RANK: Final[dict[str, int]] = { NotificationLevel.ERROR: 2, } _RETRY: Final = Retry(max=3, interval=[30, 120, 600]) -_JOB_TIMEOUT_SECONDS: Final = 60 +# A delivery, queued or tried from the channel's test button, gets this long. +DELIVERY_TIMEOUT_SECONDS: Final = 60 def may_reach_private_network(role: str) -> bool: @@ -39,6 +40,8 @@ def may_reach_private_network(role: str) -> bool: def describe_error(exc: Exception) -> str: + if isinstance(exc, TimeoutError): + return f"No answer within {DELIVERY_TIMEOUT_SECONDS} seconds" return str(exc) or type(exc).__name__ @@ -74,7 +77,7 @@ def enqueue_channel_deliveries( deliver_to_channel, kwargs={"channel_id": channel.id, "notification": payload}, retry=_RETRY, - job_timeout=_JOB_TIMEOUT_SECONDS, + job_timeout=DELIVERY_TIMEOUT_SECONDS, result_ttl=0, meta={"task_name": "Notification delivery"}, ) @@ -89,26 +92,30 @@ async def send_to_channel( Raises: UnsealError: ROMM_AUTH_SECRET_KEY changed since the channel was saved. - WebhookError, EmailError: The delivery failed. + AppriseError, WebhookError, EmailError: The delivery failed. """ config = unseal(channel.config) - if channel.type == NotificationChannelType.EMAIL: - text = "\n\n".join(part for part in (message.body, message.url) if part) - await asyncio.to_thread( - send_email, - config["address"], - f"[RomM] {message.title}", - text or message.title, - ) - else: - await webhook.send( - WebhookConfig( - url=config["url"], format=config["format"], secret=config.get("secret") - ), - message, - allow_private=allow_private, - channel_name=channel.name, - ) + match channel.type: + case NotificationChannelType.APPRISE: + # Here, so jobs for other channels don't load Apprise's plugins. + from . import apprise_channel + + # Apprise opens its own connections, past the SSRF guard. + if not allow_private: + raise apprise_channel.AppriseError(apprise_channel.ADMINS_ONLY) + await asyncio.to_thread( + apprise_channel.send, config["service"], config["fields"], message + ) + case NotificationChannelType.EMAIL: + await asyncio.to_thread( + send_email, config["address"], f"[RomM] {message.title}", message.text + ) + case _: + await webhook.send( + WebhookConfig(url=config["url"], secret=config.get("secret")), + message, + allow_private=allow_private, + ) def sample_message() -> OutboundMessage: diff --git a/backend/handler/notification_channels/messages.py b/backend/handler/notification_channels/messages.py index d92572afd..7e6f2e674 100644 --- a/backend/handler/notification_channels/messages.py +++ b/backend/handler/notification_channels/messages.py @@ -16,6 +16,11 @@ class OutboundMessage: # Absolute, or None when ROMM_BASE_URL doesn't point anywhere shareable. url: str | None + @property + def text(self) -> str: + """The body and link as plain text, or the title when there are neither.""" + return "\n\n".join(part for part in (self.body, self.url) if part) or self.title + def _text(value: Any) -> str | None: return value if isinstance(value, str) and value else None diff --git a/backend/handler/notification_channels/webhook.py b/backend/handler/notification_channels/webhook.py index 373412078..7ca782ca7 100644 --- a/backend/handler/notification_channels/webhook.py +++ b/backend/handler/notification_channels/webhook.py @@ -1,4 +1,4 @@ -"""Webhook deliveries: RomM's own JSON, a Discord embed or an ntfy message.""" +"""Webhook deliveries: RomM's own JSON, signed when the channel has a secret.""" import asyncio import hashlib @@ -6,13 +6,11 @@ import hmac import json from dataclasses import dataclass from typing import Any, Final -from urllib.parse import urlsplit, urlunsplit +from urllib.parse import urlsplit import httpx from config import has_proxy_env -from models.notification import NotificationLevel -from models.notification_channel import WebhookFormat from utils.context import create_httpx_async_client from utils.ssrf import validate_url_for_http_request from utils.validation import ValidationError @@ -26,22 +24,6 @@ SIGNATURE_HEADER: Final = "X-RomM-Signature" ERROR_DETAIL_BYTES: Final = 1024 ERROR_DETAIL_CHARS: Final = 200 -DISCORD_COLORS: Final[dict[str, int]] = { - NotificationLevel.INFO: 0x3498DB, - NotificationLevel.SUCCESS: 0x2ECC71, - NotificationLevel.WARNING: 0xF1C40F, - NotificationLevel.ERROR: 0xE74C3C, -} -NTFY_TAGS: Final[dict[str, str]] = { - NotificationLevel.INFO: "information_source", - NotificationLevel.SUCCESS: "white_check_mark", - NotificationLevel.WARNING: "warning", - NotificationLevel.ERROR: "rotating_light", -} -# ntfy's scale runs 1 to 5, where 3 is the default and 4 is high. -NTFY_ERROR_PRIORITY: Final = 4 -NTFY_DEFAULT_PRIORITY: Final = 3 - class WebhookError(RuntimeError): """The destination refused the delivery or could not be reached.""" @@ -54,22 +36,7 @@ class WebhookRequest: headers: dict[str, str] -def split_ntfy_url(url: str) -> tuple[str, str]: - """The server a topic URL points at and the topic, for ntfy's JSON publishing. - - Raises: - ValueError: The URL names no topic. - """ - parts = urlsplit(url) - base_path, _, topic = parts.path.rstrip("/").rpartition("/") - if not topic: - raise ValueError( - "An ntfy URL ends with its topic, such as https://ntfy.sh/romm" - ) - return urlunsplit((parts.scheme, parts.netloc, base_path or "/", "", "")), topic - - -def check_url(url: str, format: WebhookFormat, allow_private: bool) -> None: +def check_url(url: str, allow_private: bool) -> None: """Refuse a webhook URL that can never be delivered to. Args: @@ -93,8 +60,6 @@ def check_url(url: str, format: WebhookFormat, allow_private: bool) -> None: validate_url_for_http_request(url) except ValidationError as exc: raise ValueError(exc.message) from exc - if format == WebhookFormat.NTFY: - split_ntfy_url(url) def _json_payload(message: OutboundMessage) -> dict[str, Any]: @@ -113,77 +78,20 @@ def _json_payload(message: OutboundMessage) -> dict[str, Any]: } -def _discord_payload(message: OutboundMessage, channel_name: str) -> dict[str, Any]: - n = message.notification - embed: dict[str, Any] = { - # Discord's own limits on an embed's title and description. - "title": message.title[:256], - "color": DISCORD_COLORS.get(n.level, DISCORD_COLORS[NotificationLevel.INFO]), - "timestamp": n.created_at.isoformat(), - } - if message.body: - embed["description"] = message.body[:4096] - if message.url: - embed["url"] = message.url - footer = [channel_name, f"From {n.actor.username}" if n.actor else ""] - embed["footer"] = {"text": " · ".join(part for part in footer if part)[:2048]} - # A user's own text must not ping @everyone or a role. - return {"username": "RomM", "embeds": [embed], "allowed_mentions": {"parse": []}} - - -def _ntfy_payload(message: OutboundMessage, topic: str) -> dict[str, Any]: - n = message.notification - payload: dict[str, Any] = { - "topic": topic, - "title": message.title, - "message": message.body or message.title, - "priority": ( - NTFY_ERROR_PRIORITY - if n.level == NotificationLevel.ERROR - else NTFY_DEFAULT_PRIORITY - ), - "tags": [NTFY_TAGS.get(n.level, NTFY_TAGS[NotificationLevel.INFO])], - } - if message.url: - payload["click"] = message.url - return payload - - -def build_request( - config: WebhookConfig, message: OutboundMessage, channel_name: str = "" -) -> WebhookRequest: - """The request a webhook gets for a message. - - Args: - channel_name: What the owner called the channel, which a Discord embed - shows in its footer. - """ +def build_request(config: WebhookConfig, message: OutboundMessage) -> WebhookRequest: + """The request a webhook gets for a message.""" # Identity, so a refusal's body is read as sent rather than decompressed. headers = { "Content-Type": "application/json", "User-Agent": "RomM", "Accept-Encoding": "identity", } + content = json.dumps(_json_payload(message)).encode() secret = config.get("secret") - url = config["url"] - - match config["format"]: - case WebhookFormat.DISCORD: - payload = _discord_payload(message, channel_name) - case WebhookFormat.NTFY: - # JSON publishing takes non-ASCII titles that headers can't carry. - url, topic = split_ntfy_url(url) - payload = _ntfy_payload(message, topic) - if secret: - headers["Authorization"] = f"Bearer {secret}" - case _: - payload = _json_payload(message) - - content = json.dumps(payload).encode() - if secret and config["format"] == WebhookFormat.JSON: + if secret: digest = hmac.new(secret.encode(), content, hashlib.sha256).hexdigest() headers[SIGNATURE_HEADER] = f"sha256={digest}" - return WebhookRequest(url=url, content=content, headers=headers) + return WebhookRequest(url=config["url"], content=content, headers=headers) def _client(allow_private: bool) -> httpx.AsyncClient: @@ -205,17 +113,14 @@ async def _error_detail(response: httpx.Response) -> str: async def send( - config: WebhookConfig, - message: OutboundMessage, - allow_private: bool, - channel_name: str = "", + config: WebhookConfig, message: OutboundMessage, allow_private: bool ) -> None: """POST the message to the webhook, giving it TIMEOUT_SECONDS in all. Raises: WebhookError: The destination refused it, or could not be reached. """ - request = build_request(config, message, channel_name) + request = build_request(config, message) host = urlsplit(request.url).hostname try: async with ( diff --git a/backend/handler/play_session_handler.py b/backend/handler/play_session_handler.py index 33c9ffac1..201ad1150 100644 --- a/backend/handler/play_session_handler.py +++ b/backend/handler/play_session_handler.py @@ -70,7 +70,6 @@ def ingest_play_sessions( username: str, entries: list[PlaySessionEntry], device_id: str | None = None, - sync_session_id: int | None = None, max_future_minutes: int = 5, perms: ResolvedPermissions | None, ) -> PlaySessionIngestSummary: @@ -140,7 +139,6 @@ def ingest_play_sessions( user_id=user_id, device_id=resolved_device_id, rom_id=resolved_rom_id, - sync_session_id=sync_session_id, save_slot=item.get("save_slot"), start_time=item["start_time"], end_time=item["end_time"], diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index 126085c59..64301b21f 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -23,6 +23,9 @@ class QueuePrio(Enum): # Scans have a queue and a worker of their own: a library scan runs for hours, # and one worker on one queue keeps two of them from ever running at once. SCAN_QUEUE_NAME: Final = "scans" +# Streaming teardowns and exit save pulls get one too: a sick broker can hold +# either for minutes. +STREAMING_QUEUE_NAME: Final = "streaming" redis_client = Redis.from_url(REDIS_URL) @@ -30,8 +33,15 @@ high_prio_queue = Queue(name=QueuePrio.HIGH.value, connection=redis_client) default_queue = Queue(name=QueuePrio.DEFAULT.value, connection=redis_client) low_prio_queue = Queue(name=QueuePrio.LOW.value, connection=redis_client) scan_queue = Queue(name=SCAN_QUEUE_NAME, connection=redis_client) +streaming_queue = Queue(name=STREAMING_QUEUE_NAME, connection=redis_client) -ALL_QUEUES: Final = (scan_queue, high_prio_queue, default_queue, low_prio_queue) +ALL_QUEUES: Final = ( + scan_queue, + streaming_queue, + high_prio_queue, + default_queue, + low_prio_queue, +) def __get_fake_server() -> Any: diff --git a/backend/handler/rom_files.py b/backend/handler/rom_files.py index ea1011901..2a6b19a1d 100644 --- a/backend/handler/rom_files.py +++ b/backend/handler/rom_files.py @@ -53,10 +53,16 @@ class RomFilesRefresh: new_files: int updated_files: int removed_files: int + identity_changed: bool = False @property def changed(self) -> bool: - return bool(self.new_files or self.updated_files or self.removed_files) + return bool( + self.new_files + or self.updated_files + or self.removed_files + or self.identity_changed + ) def loaded_rom_files(rom: Rom) -> list[RomFile]: @@ -81,6 +87,9 @@ async def refresh_rom_files(rom: Rom) -> RomFilesRefresh: async def _refresh(rom: Rom) -> RomFilesRefresh: existing = loaded_rom_files(rom) + # Extraction can settle a reused row's category in place, so that row is + # compared against the category it was loaded with. + reused_categories = {id(f): f.category for f in existing} cnfg = cm.get_config() calculate_hashes = not cnfg.SKIP_HASH_CALCULATION parsed = await fs_rom_handler.get_rom_files( @@ -98,11 +107,13 @@ async def _refresh(rom: Rom) -> RomFilesRefresh: return RomFilesRefresh(0, 0, 0) existing_keys = {rom_file_key(f) for f in existing} - reused_ids = {id(f) for f in existing} new_keys: set[RomFileKey] = set() updated_keys: set[RomFileKey] = set() for scanned in parsed.rom_files: - if id(scanned) in reused_ids: + if ( + id(scanned) in reused_categories + and reused_categories[id(scanned)] == scanned.category + ): continue key = rom_file_key(scanned) (updated_keys if key in existing_keys else new_keys).add(key) @@ -128,9 +139,12 @@ async def _refresh(rom: Rom) -> RomFilesRefresh: if value != (getattr(rom, column) or ""): rom_updates[column] = value # Only written when the parse actually read an id, so a refresh that read - # none (extraction disabled, or every file unchanged) leaves the stored - # triple alone rather than blanking it. - if parsed.identity.title_id and parsed.identity != RomIdentity.from_rom(rom): + # none (extraction disabled, or no readable file) leaves the stored triple + # alone rather than blanking it. + identity_changed = bool( + parsed.identity.title_id and parsed.identity != RomIdentity.from_rom(rom) + ) + if identity_changed: rom_updates.update(parsed.identity.as_rom_attrs()) if rom.missing_from_fs: rom_updates["missing_from_fs"] = False @@ -141,4 +155,5 @@ async def _refresh(rom: Rom) -> RomFilesRefresh: new_files=len(new_keys), updated_files=len(updated_keys), removed_files=len(removed_keys), + identity_changed=identity_changed, ) diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 0745cb0e5..d0e7b83a0 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -232,8 +232,8 @@ def get_main_platform_igdb_id(platform: Platform): if main_platform: main_platform_igdb_id = main_platform.igdb_id else: - main_platform = meta_igdb_handler.get_platform(main_platform_slug) - main_platform_igdb_id = main_platform["igdb_id"] + igdb_platform = meta_igdb_handler.get_platform(main_platform_slug) + main_platform_igdb_id = igdb_platform["igdb_id"] if not main_platform_igdb_id: main_platform_igdb_id = platform.igdb_id else: diff --git a/backend/handler/socket_handler.py b/backend/handler/socket_handler.py index 6a6adf48d..86ef4351b 100644 --- a/backend/handler/socket_handler.py +++ b/backend/handler/socket_handler.py @@ -1,6 +1,6 @@ import asyncio from collections.abc import Iterable -from typing import Any, Final +from typing import TYPE_CHECKING, Any, Final import socketio @@ -9,14 +9,13 @@ from handler.redis_handler import async_cache from logger.logger import log from utils import json_module +if TYPE_CHECKING: + from models.user import User + # Where a socket's own session records the login session that opened it. LOGIN_SESSION_ID_KEY: Final = "login_session_id" -def _login_session_sockets_key(session_id: str) -> str: - return f"session_sockets:{session_id}" - - class SocketHandler: def __init__(self, path: str, channel: str = "socketio") -> None: self.channel = channel @@ -38,6 +37,10 @@ class SocketHandler: self._write_manager: socketio.AsyncRedisManager | None = None self._write_manager_loop: asyncio.AbstractEventLoop | None = None + def _login_session_sockets_key(self, session_id: str) -> str: + # Per channel, since a sid only means something to the server that issued it. + return f"session_sockets:{self.channel}:{session_id}" + def write_manager(self) -> socketio.AsyncRedisManager: """A publish-only manager on this server's channel, usable from an RQ worker.""" # A Redis client is bound to the loop that made it, and a worker runs @@ -60,9 +63,36 @@ class SocketHandler: except Exception: # noqa: BLE001 log.warning(f"Failed to push {event} to user {user_id}", exc_info=True) + async def get_session(self, sid: str) -> dict[str, Any]: + """The socket's server-side session, empty once the socket is gone.""" + try: + return await self.socket_server.get_session(sid) or {} + except KeyError: + return {} + + async def authenticate(self, sid: str, environ: dict[str, Any]) -> "User | None": + """The enabled user behind a handshake's login session, binding the socket to it.""" + # Deferred: both import the auth middleware, which imports this module. + from handler.database import db_user_handler + from utils.auth import get_session_from_environ + + session = await get_session_from_environ(environ) + username = session.get("sub") + if session.get("iss") != "romm:auth" or not username: + return None + + user = db_user_handler.get_user_by_username(username) + if not user or not user.enabled: + return None + + session_id = session.get("session_id") + if session_id: + await self.bind_to_login_session(sid, session_id) + return user + async def bind_to_login_session(self, sid: str, session_id: str) -> None: """Record which login session opened a socket, so revoking it closes the socket.""" - key = _login_session_sockets_key(session_id) + key = self._login_session_sockets_key(session_id) await async_cache.sadd(key, sid) await async_cache.expire(key, SESSION_MAX_AGE_SECONDS) async with self.socket_server.session(sid) as session: @@ -71,10 +101,9 @@ class SocketHandler: async def unbind_from_login_session(self, sid: str) -> None: """Forget a disconnecting socket, logging a failure.""" try: - session = await self.socket_server.get_session(sid) - session_id = session.get(LOGIN_SESSION_ID_KEY) + session_id = (await self.get_session(sid)).get(LOGIN_SESSION_ID_KEY) if session_id: - await async_cache.srem(_login_session_sockets_key(session_id), sid) + await async_cache.srem(self._login_session_sockets_key(session_id), sid) except Exception: # noqa: BLE001 log.warning(f"Failed to unbind socket {sid}", exc_info=True) @@ -85,7 +114,7 @@ class SocketHandler: session would otherwise go on receiving its user's and the admins' events. """ for session_id in session_ids: - key = _login_session_sockets_key(session_id) + key = self._login_session_sockets_key(session_id) try: sids = await async_cache.smembers(key) await async_cache.delete(key) @@ -102,6 +131,15 @@ class SocketHandler: socket_handler = SocketHandler(path="/ws/socket.io") -# Netplay clients are unauthenticated and name their own rooms, so they must not -# share a channel where `user:{id}` and `admin` rooms are addressed. +# Netplay clients may be anonymous guests and name their own rooms, so they must +# not share a channel where `user:{id}` and `admin` rooms are addressed. netplay_socket_handler = SocketHandler(path="/netplay/socket.io", channel="netplay") + + +async def close_login_session_sockets(session_ids: Iterable[str]) -> None: + """Disconnect the sockets the given login sessions opened, on every server.""" + ids = list(session_ids) + await asyncio.gather( + socket_handler.close_login_sessions(ids), + netplay_socket_handler.close_login_sessions(ids), + ) diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index fefb2cbe4..dbc228ebe 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -12,7 +12,12 @@ from handler.streaming.config import ( containers_for_platform, entry_for_platform, ) -from handler.streaming.session_store import get_live_session +from handler.streaming.session_store import ( + get_live_session, + session_is_desktop, + session_platform_matches, +) +from logger.logger import log from models.rom import Rom from models.user import Role @@ -50,26 +55,40 @@ def rom_is_visible(request: Request, rom: Rom | None) -> bool: return get_permissions(request).can_see_rom(rom.id, rom.platform_id) -def _session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool: - """Can the caller see the ROM a session is running?""" +def session_rom(session: dict[str, Any]) -> Rom | None: + """The ROM a session is running, None for a desktop or a deleted entry.""" rom_id = session.get("rom_id") - if rom_id is None: - return True - return rom_is_visible(request, db_rom_handler.get_rom_simple(rom_id)) + return db_rom_handler.get_rom_simple(rom_id) if rom_id is not None else None + + +def session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool: + """Can the caller see the ROM a session is running?""" + return rom_is_visible(request, session_rom(session)) + + +def joinable_session_rom( + request: Request, session: dict[str, Any] +) -> tuple[bool, Rom | None]: + """Whether a live session is one this caller may ask to join (its host opted + into multiplayer, it is somebody else's, its ROM is not hidden), with that ROM.""" + if not session.get("multiplayer") or session.get("user_id") == request.user.id: + return False, None + rom = session_rom(session) + return rom_is_visible(request, rom), rom def assert_session_rom_visible( request: Request, session: dict[str, Any], *, not_found_detail: str ) -> None: """Raise 404 when the session's ROM is hidden from the caller.""" - if not _session_rom_is_visible(request, session): + if not session_rom_is_visible(request, session): raise HTTPException(status_code=404, detail=not_found_detail) def visible_rom_name(request: Request, session: dict[str, Any]) -> str | None: """The name of the ROM a session is running, blanked when the caller cannot see that ROM. "Busy" is safe to report to anyone; what is running is not.""" - if not session or not _session_rom_is_visible(request, session): + if not session or not session_rom_is_visible(request, session): return None name = session.get("rom_name") return str(name) if name else None @@ -89,19 +108,45 @@ def platform_is_visible(request: Request, platform_slug: str) -> bool: return get_permissions(request).can_see_platform(platform.id) +def session_in_scope( + session: dict[str, Any], + platform: str, + include_desktop: bool, + claimed_at: str | None = None, +) -> bool: + """Whether a stored session, or the notice it left, is the one a route asked + about: same platform, a desktop only if named, the given claim.""" + if not include_desktop and session_is_desktop(session): + return False + if claimed_at is not None and session.get("claimed_at") != claimed_at: + return False + return session_platform_matches(session, platform) + + async def find_session_for_user( - candidates: list[ResolvedContainer], user_id: int + candidates: list[ResolvedContainer], + user_id: int, + *, + platform: str, + include_desktop: bool = False, + claimed_at: str | None = None, ) -> tuple[ResolvedContainer, str, dict[str, Any]] | None: """The candidate holding this user's session, as (container, key, session). - With a pool the platform no longer identifies the container, the session - does. + With a pool the platform no longer identifies the container, the session does. + + Args: + platform: only sessions claimed for it match. + include_desktop: whether a desktop matches, only when its container is named. + claimed_at: only the one claim the caller was given matches. """ for candidate in candidates: session_key = candidate.key session = await get_live_session(session_key) if session is None: continue + if not session_in_scope(session, platform, include_desktop, claimed_at): + continue if session.get("user_id") == user_id: return candidate, session_key, session return None @@ -137,7 +182,7 @@ async def resolve_named_container( async def resolve_owned_session( platform: str, request: Request ) -> tuple[ResolvedContainer, str, dict[str, Any]]: - """Find the caller's session in the platform's first pool. + """Find the caller's session for this platform in its first pool. Returns (container, session_key, session). Raises 404 when the platform has no configured container or nothing is active, 403 when every active session @@ -156,6 +201,9 @@ async def resolve_owned_session( session = await get_live_session(session_key) if session is None: continue + # These routes act on a game; a desktop is reached by naming it. + if not session_in_scope(session, platform, include_desktop=False): + continue if session.get("user_id") == request.user.id: return candidate, session_key, session others.append((candidate, session_key, session)) @@ -182,6 +230,70 @@ async def resolve_owned_session( return others[0] +async def resolve_claim( + platform: str, + request: Request, + container_key: str | None, + claimed_at: str | None, + *, + game_only: bool, +) -> tuple[ResolvedContainer, str, dict[str, Any]] | None: + """The session a route acting on a claim reaches, or None when that claim is gone. + + Args: + container_key: the container the caller named, if any. + claimed_at: the stamp of the one claim the caller was given. + game_only: only a game of this platform matches a named container, while + a release ends whatever it holds. + """ + if container_key is not None: + container, session_key, session = await resolve_named_container( + platform, container_key + ) + if session is None: + return None + if game_only and not session_in_scope(session, platform, include_desktop=False): + return None + else: + try: + container, session_key, session = await resolve_owned_session( + platform, request + ) + except HTTPException as exc: + # Nothing of the caller's is active, so a stamped claim is gone and a + # repeated call from the same tab finds nothing: both are a no-op. + if exc.status_code != 404 and claimed_at is None: + raise + return None + + # A tab whose claim was replaced (a takeover, or Play pressed again elsewhere) + # must not act on the claim that took its place. + if claimed_at is not None and session.get("claimed_at") != claimed_at: + log.info("%s ignored for a replaced claim", request.url.path) + return None + # After the stamp check, so another player's takeover reads as a gone claim. + if container_key is not None: + assert_session_owner(session, request) + return container, session_key, session + + +async def require_claim( + platform: str, + request: Request, + container_key: str | None, + claimed_at: str | None, +) -> tuple[ResolvedContainer, str, dict[str, Any]]: + """The game a control route drives, raising 404 once the caller's claim is gone.""" + target = await resolve_claim( + platform, request, container_key, claimed_at, game_only=True + ) + if target is None: + raise HTTPException( + status_code=404, detail=f"No active session for platform '{platform}'" + ) + return target + + def container_by_key(container_key: str) -> tuple[ResolvedContainer, str]: """A configured container named by its key, plus the platform to file its sessions under. diff --git a/backend/handler/streaming/background.py b/backend/handler/streaming/background.py index c292d89af..cdf3d3c72 100644 --- a/backend/handler/streaming/background.py +++ b/backend/handler/streaming/background.py @@ -3,11 +3,8 @@ import asyncio from typing import Any -_sync_tasks: set[asyncio.Task] = set() +from utils.background_tasks import fire_and_forget def spawn_sync_task(coro: Any) -> asyncio.Task: - task = asyncio.get_running_loop().create_task(coro) - _sync_tasks.add(task) - task.add_done_callback(_sync_tasks.discard) - return task + return fire_and_forget(coro) diff --git a/backend/handler/streaming/broker.py b/backend/handler/streaming/broker.py index cd76ee399..4ab40738e 100644 --- a/backend/handler/streaming/broker.py +++ b/backend/handler/streaming/broker.py @@ -19,6 +19,7 @@ from typing import Any, NoReturn from fastapi import HTTPException +from endpoints.responses.streaming import ImportRefusalSchema from handler.streaming.config import ResolvedContainer from logger.logger import log @@ -95,8 +96,9 @@ def broker_headers(container: ResolvedContainer) -> dict[str, str]: _BROKER_READ_CHUNK = 1024 * 1024 # Control responses are small; a JSON body past this is a broker fault. _BROKER_JSON_MAX_BYTES = 4 * 1024 * 1024 -# An error body only ever reaches a log line and a 502 detail. -_BROKER_ERROR_MAX_BYTES = 8 * 1024 +# An error body only ever reaches a log line and a 502 detail, except an +# import refusal, which can carry one entry per rejected member. +_BROKER_ERROR_MAX_BYTES = 64 * 1024 def broker_error_body(exc: urllib.error.HTTPError) -> str: @@ -292,14 +294,52 @@ def put_binary( return bool(body and body.get("status") == "ok") +class ImportRefusedError(Exception): + """The broker refused one or more members of a declared import.""" + + def __init__(self, refusals: list[ImportRefusalSchema], truncated: int) -> None: + self.refusals = refusals + self.truncated = truncated + super().__init__(f"import refused: {len(refusals)} refusal(s)") + + +def _str_or_none(value: Any) -> str | None: + """Coerce one unvalidated broker-JSON field to `str | None`.""" + return value if isinstance(value, str) or value is None else str(value) + + def raise_http_error(exc: urllib.error.HTTPError) -> NoReturn: - """Translate a broker error response into the 502 the frontend parses.""" + """Translate a broker error response into the 502 the frontend parses, or + an ImportRefusedError when the broker refused a declared import.""" error_body = broker_error_body(exc) log.error("broker HTTP error %d: %s", exc.code, error_body) try: - detail = json.loads(error_body) + detail: Any = json.loads(error_body) except Exception: detail = error_body + refusal = None + if isinstance(detail, dict): + wrapped = detail.get("detail") + if isinstance(wrapped, dict) and wrapped.get("error") == "import_refused": + refusal = wrapped + elif detail.get("error") == "import_refused": + refusal = detail + if refusal is not None and isinstance(refusal.get("refusals"), list): + refusals = [ + ImportRefusalSchema( + reason=str(r.get("reason", "")), + member=_str_or_none(r.get("member")), + expected=_str_or_none(r.get("expected")), + detail=_str_or_none(r.get("detail")), + suggest_emulator=_str_or_none(r.get("suggest_emulator")), + docs=_str_or_none(r.get("docs")), + ) + for r in refusal["refusals"] + if isinstance(r, dict) + ] + truncated_raw = refusal.get("truncated", 0) + truncated = truncated_raw if isinstance(truncated_raw, int) else 0 + raise ImportRefusedError(refusals, truncated) from exc raise HTTPException( status_code=502, detail=f"Broker returned {exc.code}: {detail}" ) from exc diff --git a/backend/handler/streaming/capabilities.py b/backend/handler/streaming/capabilities.py index b55af2556..d93d3149e 100644 --- a/backend/handler/streaming/capabilities.py +++ b/backend/handler/streaming/capabilities.py @@ -172,6 +172,10 @@ _SAVE_PICKER_EMULATORS = frozenset( {"eden", "retroarch", "rpcs3", "shadps4", "xemu", "xenia"} ) +# Emulators whose webstation broker writes a state only on exit and refuses one +# pushed in, so a resume is the slot on the activate plus the save archive. +_EXIT_STATE_EMULATORS = frozenset({"duckstation", "rpcs3"}) + def slot_capabilities(platform: str, emulator: str = "") -> PlatformCapabilities: """Save-state and disc capabilities for a platform, or a no-slots default. @@ -201,6 +205,12 @@ def emulator_clears_saves(emulator: str) -> bool: return emulator.strip().lower() in _SAVE_PICKER_EMULATORS +def emulator_resumes_from_archive(emulator: str) -> bool: + """Whether this emulator resumes from the state its save archive restores + rather than from a state file pushed into the container.""" + return emulator.strip().lower() in _EXIT_STATE_EMULATORS + + def known_to_lack_memory_card(platform: str) -> bool: """True only for a platform listed above as having no memory card. diff --git a/backend/handler/streaming/commands.py b/backend/handler/streaming/commands.py index 6f8b148a8..018544571 100644 --- a/backend/handler/streaming/commands.py +++ b/backend/handler/streaming/commands.py @@ -5,7 +5,7 @@ for the effect and never for the route that produces it. """ import urllib.error -from typing import Any +from typing import Any, NamedTuple from config import STREAMING_SAVE_TIMEOUT from handler.streaming import broker, webstation @@ -50,14 +50,23 @@ def launch( ) +class SaveAndExitOutcome(NamedTuple): + """What a save-and-exit reports back to the route.""" + + saved: bool + slot: int + # The broker answered once the emulator was done writing its saves. + settled: bool + + def save_and_exit( container: ResolvedContainer, slot: int = 0, wait: bool = True -) -> tuple[bool, int]: +) -> SaveAndExitOutcome: """ POST /save-and-exit to the broker. Best-effort, logs but never raises. With wait=True the call blocks until save+kill completes (use for button press). With wait=False the broker fires save+kill in the background (use for navigation away). - Returns (saved, slot). Brokers resolve slot 0 to their default autosave + Returns (saved, slot, settled). Brokers resolve slot 0 to their default autosave slot and echo the effective slot back, which the state sync needs to pull the right file afterwards. """ @@ -75,7 +84,7 @@ def save_and_exit( if report is not None and isinstance(report.get("state_slot"), int): effective_slot = report["state_slot"] log.info("broker exit, saved=%s slot=%d", saved, effective_slot) - return saved, effective_slot + return SaveAndExitOutcome(saved, effective_slot, settled=report is not None) body = broker.request_safe( container, @@ -91,7 +100,8 @@ def save_and_exit( log.info( "broker save-and-exit, saved=%s slot=%d wait=%s", saved, effective_slot, wait ) - return saved, effective_slot + # Only a confirmed save that blocked on the kill leaves nothing still writing. + return SaveAndExitOutcome(saved, effective_slot, settled=saved and wait) def set_volume(container: ResolvedContainer, level: int) -> bool: @@ -169,10 +179,18 @@ def swap_disc(container: ResolvedContainer, disc_path: str) -> bool: return bool(body and body.get("status") == "ok") -def stop(container: ResolvedContainer, save: bool = True) -> int | None: +class StopOutcome(NamedTuple): + """What a stop leaves for the teardown to collect.""" + + state_slot: int | None = None + # The broker answered once the emulator was done writing its saves. + settled: bool = False + + +def stop(container: ResolvedContainer, save: bool = True) -> StopOutcome: """Tell the broker to stop emulator. Best-effort, don't raise on failure. - Returns the slot a state was captured in, or None when none was. With + The outcome's slot is where a state was captured, if one was. With `save` off no state is written at all, which is what a player leaving without saving asked for; the game's own save data still travels either way, so progress made at an in-game save point survives the stop. @@ -183,11 +201,14 @@ def stop(container: ResolvedContainer, save: bool = True) -> int | None: """ if container.is_webstation: report = webstation.exit_session(container, slot=0, save=save) - if save and report and report.get("state_saved"): - slot = report.get("state_slot") - return slot if isinstance(slot, int) else None - return None + if report is None: + return StopOutcome() + slot = report.get("state_slot") + if save and report.get("state_saved") and isinstance(slot, int): + return StopOutcome(slot, settled=True) + return StopOutcome(settled=True) + # These brokers ack before the emulator has flushed its saves. broker.request_safe( container, "/launch", "stop", method="DELETE", timeout=ACK_TIMEOUT ) - return None + return StopOutcome() diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index c636cfabb..586d78a49 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -9,6 +9,7 @@ only walks the first. from __future__ import annotations +import hashlib import json import secrets from collections.abc import Iterable, Sequence @@ -16,12 +17,16 @@ from dataclasses import dataclass from typing import Any from urllib.parse import urlparse, urlunparse +from redis.exceptions import RedisError + from config import LIBRARY_BASE_PATH, STREAMING_BROKER_SECRET from config.config_manager import config_manager as cm +from handler.redis_handler import sync_cache from handler.streaming.capabilities import ( PlatformCapabilities, StateTransferLimits, emulator_clears_saves, + emulator_resumes_from_archive, known_to_lack_memory_card, slot_capabilities, state_transfer_limits, @@ -52,7 +57,10 @@ _EMULATOR_DISPLAY_NAMES: dict[str, str] = { "eden": "Eden", "flycast": "Flycast", "pcsx2": "PCSX2", + "play": "Play!", "ppsspp": "PPSSPP", + # Platform-less name; emulator_display_label names the core instead. + "retroarch": "RetroArch", "rpcs3": "RPCS3", "shadps4": "shadPS4", "xemu": "xemu", @@ -121,6 +129,12 @@ _RETROARCH_CORE_NAMES: dict[str, str] = { } +def emulator_labels() -> dict[str, str]: + """Display name per emulator id, for surfaces that label an id they were + handed rather than one they resolved (a save's `emulator`, say).""" + return dict(_EMULATOR_DISPLAY_NAMES) + + def emulator_display_label(emulator: str, platform: str) -> str: """Play-button text for an emulator serving a platform, e.g. "PCSX2" or "RA PPSSPP". Unknown emulators fall back to their configured name.""" @@ -173,6 +187,17 @@ class ResolvedContainer: """Whether the launch screen may offer a save other than the newest.""" return self.is_webstation and self.clears_stale_saves + @property + def resumes_from_archive(self) -> bool: + """Whether a resume rides the save archive, with no state file to push.""" + return self.is_webstation and emulator_resumes_from_archive(self.emulator) + + @property + def supports_live_states(self) -> bool: + """Whether the player may save or load a state while the game runs. An + exit-state broker refuses both, though its slot still backs the library.""" + return self.capabilities["has_autosave"] and not self.resumes_from_archive + def interchangeable_with(self, other: ResolvedContainer) -> bool: """Whether two containers serving a platform are one pool: a player landing on either finds the same saves and the same controls.""" @@ -520,7 +545,7 @@ def resolve_containers() -> tuple[ResolvedContainer, ...]: for row, platform in _platform_entries(dict(entry)): resolved.append(_resolve_one(row, platform, entry.get("label"))) - _warn_about_later_pools(resolved) + _warn_about_later_pools(resolved, fingerprint) _cache_fingerprint = fingerprint _cached = tuple(resolved) return _cached @@ -552,9 +577,36 @@ def _pools_by_platform( return {platform: _pools(members) for platform, members in by_platform.items()} -def _warn_about_later_pools(resolved: Sequence[ResolvedContainer]) -> None: - """Name every container a game claim can never reach, once per config.""" - for pools in _pools_by_platform(resolved).values(): +# Each RQ job runs in a fresh process, so "once" has to outlive the process. +_POOL_WARNING_KEY_PREFIX = "romm:streaming:pool-warning:" +_POOL_WARNING_TTL_SECONDS = 24 * 60 * 60 + + +def _first_to_warn(fingerprint: str) -> bool: + digest = hashlib.sha256(fingerprint.encode()).hexdigest() + try: + return bool( + sync_cache.set( + f"{_POOL_WARNING_KEY_PREFIX}{digest}", + "1", + nx=True, + ex=_POOL_WARNING_TTL_SECONDS, + ) + ) + except RedisError: + return True + + +def _warn_about_later_pools( + resolved: Sequence[ResolvedContainer], fingerprint: str +) -> None: + """Name every container a game claim can never reach, once a day per config.""" + pools_by_platform = _pools_by_platform(resolved) + if not any(len(pools) > 1 for pools in pools_by_platform.values()): + return + if not _first_to_warn(fingerprint): + return + for pools in pools_by_platform.values(): later = [c.key for pool in pools[1:] for c in pool] if later: log.warning( @@ -579,6 +631,12 @@ def containers_for_platform(platform: str) -> list[ResolvedContainer]: return pools[0] if pools else [] +def first_claim_targets() -> list[ResolvedContainer]: + """The first container a game claim tries, one per platform, in config + order.""" + return [pools[0][0] for pools in _pools_by_platform(resolve_containers()).values()] + + def containers_by_key() -> dict[str, list[ResolvedContainer]]: """Configured containers grouped by key. A container serving several platforms has one record per platform, all sharing one key.""" @@ -610,9 +668,10 @@ def container_for_session( def configured_emulator(platform: str) -> str: - """The emulator a configured container serves this platform with, if any.""" - entry = entry_for_platform(resolve_containers(), platform) - return entry.emulator if entry else "" + """The emulator a claim's container serves this platform with, empty when none + can be claimed, taken from the pool a claim walks since slot ceilings read it.""" + pool = containers_for_platform(platform) + return pool[0].emulator if pool else "" def streaming_enabled() -> bool: diff --git a/backend/handler/streaming/imports.py b/backend/handler/streaming/imports.py new file mode 100644 index 000000000..f7d91f82d --- /dev/null +++ b/backend/handler/streaming/imports.py @@ -0,0 +1,285 @@ +"""Folding a foreign-emulator save or state pick into the one archive a +launch's `activate` call sends, under `.import//` for the broker to place. +""" + +import asyncio +import io +import json +import time +import zipfile +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Literal, NamedTuple + +from handler.filesystem import fs_asset_handler +from handler.streaming import broker, saves, states, webstation +from handler.streaming.config import ResolvedContainer, emulator_labels +from logger.logger import log +from models.assets import Save, State +from models.rom import Rom +from utils.zip_cache import ensure_zipfile_writable + +_MANIFEST_NAME = ".broker-manifest.json" + +# Charged on each entry's expanded size, so a small, highly compressible +# upload cannot inflate past the ceiling any stored save archive has. +_MAX_EXPANDED_BYTES = broker.SAVE_FILE_MAX_BYTES +_MAX_MEMBERS = 2000 + + +@dataclass(frozen=True) +class ForeignMember: + """One foreign pick's bytes, waiting to be folded into the import archive.""" + + kind: Literal["save", "state"] + name: str + content: bytes + origin: str + + +def origin_of(emulator: str | None, origin_device_id: str | None) -> str: + """The advisory manifest origin of a pick; EmulatorJS records its core's name as `emulator`.""" + if origin_device_id is not None: + return "hardware" + if not emulator: + return "unknown" + return "standalone" if emulator.lower() in emulator_labels() else "emulatorjs" + + +def _safe_name(name: str) -> str | None: + """None when this zip member is junk that must never ride in an import + archive (a dotfile, or macOS's resource-fork sidecar folder).""" + normalized = name.replace("\\", "/") + parts = [p for p in normalized.split("/") if p] + if not parts or parts[0] == "__MACOSX" or any(p.startswith(".") for p in parts): + return None + return "/".join(parts) + + +def _utf8_zipinfo(name: str, source: zipfile.ZipInfo | None) -> zipfile.ZipInfo: + """A member header named `name`, keeping a copied entry's timestamp and mode.""" + if source is None: + info = zipfile.ZipInfo(name, date_time=time.localtime()[:6]) + else: + info = zipfile.ZipInfo(name, date_time=source.date_time) + info.external_attr = source.external_attr + info.flag_bits |= 0x800 # UTF-8 filename flag + info.compress_type = zipfile.ZIP_DEFLATED + return info + + +def _manifest_files(zf: zipfile.ZipFile) -> dict[str, dict[str, Any]]: + """A broker archive's manifest entries by path, empty when it has none.""" + if _MANIFEST_NAME not in zf.namelist(): + return {} + try: + manifest = json.loads(zf.read(_MANIFEST_NAME)) + except (json.JSONDecodeError, KeyError, UnicodeDecodeError): + return {} + files = manifest.get("files") if isinstance(manifest, dict) else None + return { + f["path"]: f + for f in (files if isinstance(files, list) else []) + if isinstance(f, dict) and isinstance(f.get("path"), str) + } + + +_Staged = dict[str, tuple[bytes, dict[str, Any], zipfile.ZipInfo | None]] + + +@dataclass +class _ArchiveBudget: + """Expanded-size and member-count budget for one archive build.""" + + bytes_left: int = _MAX_EXPANDED_BYTES + members_left: int = _MAX_MEMBERS + + def charge(self, size: int) -> None: + self.bytes_left -= size + self.members_left -= 1 + if self.bytes_left < 0 or self.members_left < 0: + raise ValueError( + "import archive exceeds the expanded-size or member-count limit" + ) + + +def _stage_zip( + zf: zipfile.ZipFile, + staged: _Staged, + budget: _ArchiveBudget, + *, + skip_state: bool, + place: Callable[[str, dict[str, Any] | None], tuple[str, dict[str, Any]]], +) -> None: + """Stage each non-junk entry of `zf` at the path and manifest entry `place` picks. + + A later write at the same path replaces an earlier one, as a zip reader + resolves duplicate entries. + """ + files = _manifest_files(zf) + for info in zf.infolist(): + name = _safe_name(info.filename) + if info.is_dir() or name is None: + continue + entry = files.get(info.filename) or files.get(name) + if skip_state and entry is not None and entry.get("kind") == "state": + continue + budget.charge(info.file_size) + path, manifest_entry = place(name, entry) + staged[path] = (zf.read(info), manifest_entry, info) + + +def _write_member( + member: ForeignMember, staged: _Staged, budget: _ArchiveBudget +) -> None: + """Stage one foreign member's inner entries, or itself when it is not a zip.""" + + def place(name: str, _entry: dict[str, Any] | None) -> tuple[str, dict[str, Any]]: + path = f".import/{member.kind}/{name}" + return path, {"path": path, "kind": member.kind, "origin": member.origin} + + try: + inner = zipfile.ZipFile(io.BytesIO(member.content)) + except zipfile.BadZipFile: + budget.charge(len(member.content)) + path, entry = place(_safe_name(member.name) or "data", None) + staged[path] = (member.content, entry, None) + return + with inner: + # Another emulator's save archive also carries its exit state, which + # a save pick must not bring along. + _stage_zip(inner, staged, budget, skip_state=member.kind == "save", place=place) + + +def build_import_archive( + rom_id: int, + base: tuple[str, bytes] | None, + members: list[ForeignMember], +) -> tuple[bytes, list[dict[str, Any]]]: + """Build the single zip `activate`'s `save.archive` wants. + + The base archive's members are carried over (minus its state when a + foreign state replaces it), then each foreign member lands under + `.import//`, and the manifest is rewritten as v2. + + Returns: + The archive bytes, and the manifest's `files` list actually written. + """ + ensure_zipfile_writable() + staged: _Staged = {} + budget = _ArchiveBudget() + if base is not None: + base_name, base_content = base + try: + base_zf = zipfile.ZipFile(io.BytesIO(base_content)) + except zipfile.BadZipFile: + log.warning("base save archive is not a valid zip, %s", base_name) + else: + with base_zf: + _stage_zip( + base_zf, + staged, + budget, + skip_state=any(m.kind == "state" for m in members), + place=lambda name, entry: ( + name, + entry if entry is not None else {"path": name, "kind": "save"}, + ), + ) + for member in members: + _write_member(member, staged, budget) + + carried = [entry for _content, entry, _source in staged.values()] + out = io.BytesIO() + with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf: + for path, (content, _entry, source) in staged.items(): + zf.writestr(_utf8_zipinfo(path, source), content) + zf.writestr( + _MANIFEST_NAME, + json.dumps( + { + "version": 2, + "created_at": time.time(), + "import": {"source": "romm", "rom_id": rom_id}, + "files": carried, + } + ), + ) + return out.getvalue(), carried + + +async def _read_asset(file_path: str, file_name: str) -> bytes | None: + try: + return await fs_asset_handler.read_file(f"{file_path}/{file_name}") + except FileNotFoundError: + log.warning("import member missing on disk, %s", file_name) + return None + + +class ImportHydration(NamedTuple): + """What `hydrate_import_archive` actually got onto the container.""" + + path: str | None = None + state_imported: bool = False + + +async def hydrate_import_archive( + user_id: int, + rom: Rom, + container: ResolvedContainer, + *, + save: Save | None, + save_is_foreign: bool, + state: State | None, +) -> ImportHydration: + """Build this launch's one archive (native base plus `.import/` members) and upload it. + + Returns: + The container path `activate`'s `save.archive` wants (None when + there is nothing to send through the import path), and whether + `state` specifically made it into the uploaded archive. + """ + members: list[ForeignMember] = [] + if save is not None and save_is_foreign: + archive = await saves.read_restorable_archive(save) + if archive is not None: + members.append( + ForeignMember( + kind="save", + name=save.file_name, + content=archive[1], + origin=origin_of(save.emulator, save.origin_device_id), + ) + ) + + if state is not None: + content = await _read_asset(state.file_path, state.file_name) + if content is not None: + members.append( + ForeignMember( + kind="state", + name=states.container_state_filename(state.file_name), + content=content, + origin=origin_of(state.emulator, None), + ) + ) + + # Nothing foreign made it in, so the caller falls back to ordinary hydration. + if not members: + return ImportHydration() + + base: tuple[str, bytes] | None = None + if not save_is_foreign: + native = save or saves.newest_restorable(user_id, rom.id, container.emulator) + if native is not None: + base = await saves.read_restorable_archive(native) + + archive_bytes, carried = await asyncio.to_thread( + build_import_archive, rom.id, base, members + ) + path = await asyncio.to_thread( + webstation.upload_archive, container, f"rom-{rom.id}.zip", archive_bytes + ) + # A member whose inner zip held only junk never lands in `carried`. + state_included = path is not None and any(f.get("kind") == "state" for f in carried) + return ImportHydration(path, state_included) diff --git a/backend/handler/streaming/launch.py b/backend/handler/streaming/launch.py index 07ff95a21..29b8abe93 100644 --- a/backend/handler/streaming/launch.py +++ b/backend/handler/streaming/launch.py @@ -6,7 +6,7 @@ progress behind it reach the player over the socket instead. """ import asyncio -from typing import Any +from typing import Any, Literal from fastapi import HTTPException @@ -15,7 +15,14 @@ from endpoints.responses.streaming import ( LaunchPhasePayload, LaunchReadyPayload, ) -from handler.streaming import background, commands, lifecycle, states, webstation +from handler.streaming import ( + background, + broker, + commands, + lifecycle, + states, + webstation, +) from handler.streaming.config import ResolvedContainer from handler.streaming.session_store import ( hold_session_claim, @@ -27,6 +34,9 @@ from models.assets import State from models.rom import Rom from models.user import User +# Whether a resume state had to ride the import archive, and if it made it in. +ResumeImport = Literal["none", "imported", "lost"] + async def run_launch( *, @@ -45,6 +55,7 @@ async def run_launch( resume_slot: int | None, resume_pushed: bool, resume_after_launch: bool, + resume_import: ResumeImport, memory_card_synced: bool, multiplayer: bool, blank_card_id: int | None, @@ -61,6 +72,13 @@ async def run_launch( phase_watch = asyncio.create_task( _watch_launch_phase(container, session_key, session, platform) ) + # Nothing of this player's to resume from: a pick that failed to ride its + # import archive, or an exit-state broker with no archive uploaded. + resume_on_activate = ( + (resume_pushed or resume_after_launch) + and resume_import != "lost" + and not (container.resumes_from_archive and archive_path is None) + ) try: # Wrapped in asyncio.to_thread because urllib is synchronous. if container.is_webstation: @@ -76,12 +94,13 @@ async def run_launch( "platform": platform, "language": rom_language, "path": rom_path, + "title_id": rom.title_id, + "save_target": rom.save_target, + "save_target_layout": rom.save_target_layout, }, gui_language=gui_language, archive_path=archive_path, - resume_slot=( - resume_slot if resume_pushed or resume_after_launch else None - ), + resume_slot=resume_slot if resume_on_activate else None, memory_card_synced=memory_card_synced, multiplayer=multiplayer, ) @@ -96,13 +115,21 @@ async def run_launch( except Exception as exc: log.exception("launch failed, platform=%s", platform) await lifecycle.abort_claim(session_key, session, blank_card_id) + refusals = None + refusals_truncated = 0 + if isinstance(exc, broker.ImportRefusedError): + refusals_truncated = exc.truncated + refusals = exc.refusals await push_to_user( session.get("user_id"), "streaming:launch-failed", LaunchFailedPayload( platform=platform, container=session_key, + claimed_at=session["claimed_at"], detail=_failure_detail(exc), + refusals=refusals, + refusals_truncated=refusals_truncated, ).model_dump(), ) return @@ -111,14 +138,23 @@ async def run_launch( claim_hold.cancel() log.info("session claimed, platform=%s rom=%s", platform, rom_name) - await stamp_launched(session_key, session) + host = container.protocol.stream_url(container.host, launch_result) + await stamp_launched(session_key, session, host=host) await lifecycle.publish_session_activity(session_key, session) # The webstation broker's deferred load waits for its emulator to report # the game running, and holds off further until the state file is there, so # this push lands ahead of it even though it runs after activate. if resume_after_launch and resume_state is not None: - resume_pushed = await states.push_resume_state(container, resume_state) + if resume_import != "none": + # The activate's archive carried the state, or there is no other + # delivery for one that never made it in. + resume_pushed = resume_import == "imported" + elif container.resumes_from_archive: + # The pick is the newest capture, which the save archive carries. + resume_pushed = resume_on_activate + else: + resume_pushed = await states.push_resume_state(container, resume_state) await push_to_user( session.get("user_id"), @@ -126,7 +162,8 @@ async def run_launch( LaunchReadyPayload( platform=platform, container=session_key, - host=container.protocol.stream_url(container.host, launch_result), + claimed_at=session["claimed_at"], + host=host, resume=resume_pushed if resume_state is not None else None, ).model_dump(), ) @@ -158,6 +195,9 @@ async def run_launch( def _failure_detail(exc: BaseException) -> str: """What to tell the player about a launch that never came up.""" + if isinstance(exc, broker.ImportRefusedError): + reasons = "; ".join(r.reason for r in exc.refusals) + return reasons or "The broker refused the picked save or state" if isinstance(exc, HTTPException): return str(exc.detail) return "The container could not start the game" @@ -191,6 +231,9 @@ async def _watch_launch_phase( session.get("user_id"), "streaming:launch-phase", LaunchPhasePayload( - platform=platform, container=session_key, phase=phase + platform=platform, + container=session_key, + claimed_at=session["claimed_at"], + phase=phase, ).model_dump(), ) diff --git a/backend/handler/streaming/lifecycle.py b/backend/handler/streaming/lifecycle.py index a9742b2c3..10ed4b627 100644 --- a/backend/handler/streaming/lifecycle.py +++ b/backend/handler/streaming/lifecycle.py @@ -15,8 +15,13 @@ from typing import Any from handler.activity_handler import activity_handler from handler.database import db_user_handler from handler.play_session_handler import ingest_play_sessions +from handler.redis_handler import streaming_queue from handler.streaming import background, commands, memory_cards, saves, states -from handler.streaming.config import ResolvedContainer +from handler.streaming.config import ( + ResolvedContainer, + container_for_session, + containers_by_key, +) from handler.streaming.session_store import ( DRAIN_MARKER_TTL, StreamingSessionContended, @@ -29,6 +34,7 @@ from handler.streaming.session_store import ( record_termination, release_own_session, replace_session_if, + restore_drained_session, same_claim, session_disc_id, session_is_stale, @@ -107,30 +113,52 @@ async def release_after_state_pull( async def quiesce_container( container: ResolvedContainer, session: dict[str, Any], *, save: bool = True -) -> int | None: +) -> commands.StopOutcome: """Stop the emulator, then evacuate and wipe its memory card. Every teardown path opens this way, and the order is load-bearing: stopping first is what makes the card quiescent, and the wipe runs only where the - evacuation captured the card. Returns the slot the stop wrote an exit state - to, if any. + evacuation captured the card. Returns what the stop left to collect. """ - state_slot = await asyncio.to_thread(commands.stop, container, save) + stopped = await asyncio.to_thread(commands.stop, container, save) if await memory_cards.evacuate_session_card(session, container): await memory_cards.wipe_session_card(container) - return state_slot + return stopped -def collect_exit_saves(container: ResolvedContainer, session: dict[str, Any]) -> None: - """Start pulling the in-game save archive a stopped session left behind. +async def pull_exit_saves( + *, + user_id: int, + rom_id: int, + token: str, + container_key: str, + platform: str, + broker_session: str | None, + settled: bool, +) -> None: + """The RQ job behind `collect_exit_saves`, which lets the next claim through + however the pull ended.""" + try: + container = container_for_session(containers_by_key(), container_key, platform) + if container is None: + log.warning("skipping the exit save pull, %s is gone", container_key) + return + await saves.pull_saves_to_library( + user_id, rom_id, container, broker_session, settled=settled + ) + finally: + await saves.clear_save_pull_pending(saves.SavePullMark(user_id, rom_id, token)) - Fire and forget: the broker keeps the archive after the emulator dies, so - no teardown has to wait on it. Whole-card sync containers evacuate the card - instead and have no archive, and a session that ran no ROM (the admin - desktop) has nowhere to file one, so neither schedules anything. - One home for the rule: every teardown path files a session's saves the same - way, and under the session's owner rather than whoever ended it. +async def mark_exit_saves_pending( + container: ResolvedContainer, session: dict[str, Any] +) -> saves.SavePullMark | None: + """Hold the owner's next claim on this ROM until the exit pull has filed. + + Returns: + The mark for `collect_exit_saves`, or None when no pull will run: a + whole-card sync container evacuates the card instead, and a desktop ran + no ROM to file one under. """ rom_id = session.get("rom_id") user_id = session.get("user_id") @@ -139,12 +167,55 @@ def collect_exit_saves(container: ResolvedContainer, session: dict[str, Any]) -> or not isinstance(rom_id, int) or not isinstance(user_id, int) ): + return None + return await saves.mark_save_pull_pending(user_id, rom_id) + + +async def collect_exit_saves( + container: ResolvedContainer, + session: dict[str, Any], + mark: saves.SavePullMark | None, + *, + settled: bool, +) -> None: + """Queue the pull of a stopped session's save archive, since the broker keeps + it after the emulator dies, filing it under the owner whoever ended it. + + Args: + mark: cleared by the pull however it ends. + settled: the broker confirmed the emulator is done writing, so the first + answer is final. + """ + if mark is None: return - background.spawn_sync_task( - saves.pull_saves_to_library( - user_id, rom_id, container, broker_session_id(session) + try: + # On the streaming worker, so a web restart cannot cut a pull short. + streaming_queue.enqueue( + pull_exit_saves, + kwargs={ + "user_id": mark.user_id, + "rom_id": mark.rom_id, + "token": mark.token, + "container_key": container.key, + "platform": container.platform, + "broker_session": broker_session_id(session), + "settled": settled, + }, + job_timeout=saves.SAVE_PULL_TTL_SECONDS, + result_ttl=0, + meta={"task_name": "Streaming exit save pull"}, ) - ) + except Exception: + log.exception("could not queue the exit save pull for %s", container.key) + await saves.clear_save_pull_pending(mark) + + +async def start_exit_save_pull( + container: ResolvedContainer, session: dict[str, Any], *, settled: bool +) -> None: + """Mark the exit pull pending, then start it, for a stop that is already done.""" + mark = await mark_exit_saves_pending(container, session) + await collect_exit_saves(container, session, mark, settled=settled) async def collect_exit_state( @@ -332,15 +403,14 @@ async def teardown_released_session( return keepalive = _hold_reservation(session_key, token, session) + pull_mark: saves.SavePullMark | None = None try: - # The marker, or the claim it could not replace, holds the container - # throughout, so no concurrent claim can interleave. - state_slot = await quiesce_container(container, session, save=save) + # Before anything slow: on a pool the player's next claim can land on a + # free sibling while this container drains. + pull_mark = await mark_exit_saves_pending(container, session) - # Leave a note when this is a force-release rather than a player closing - # their own game. A different user is the obvious case; a reason covers - # the rest, since only the admin panel sends one and an admin can be - # logged in as the same account that is playing in another tab. + # A force-release rather than the player quitting: another user, or a reason, + # which only the admin panel sends. Before the quiesce, so a poll finds it. if session.get("user_id") != acting_user_id or reason is not None: await record_termination( session, @@ -357,12 +427,18 @@ async def teardown_released_session( reason or "-", ) + # The marker, or the claim it could not replace, holds the container + # throughout, so no concurrent claim can interleave. + stopped = await quiesce_container(container, session, save=save) + await record_play_session(session) await clear_session_activity(session_key, session) # Awaited, not spawned: the claim is released below. - await collect_exit_state(container, session, state_slot) - collect_exit_saves(container, session) + await collect_exit_state(container, session, stopped.state_slot) + await collect_exit_saves(container, session, pull_mark, settled=stopped.settled) + # The pull clears it from here. + pull_mark = None log.info("session released, platform=%s", platform) except Exception: @@ -375,18 +451,29 @@ async def teardown_released_session( # whatever is still on the container; a phantom claim is not. keepalive.cancel() await _drop_reservation(session_key, token, session) + if pull_mark is not None: + # No pull is coming, so a claim has nothing to wait for. + await saves.clear_save_pull_pending(pull_mark) -async def _teardown_abandoned_session( - container: ResolvedContainer, session_key: str, session: dict[str, Any] +async def teardown_abandoned_session( + container: ResolvedContainer, + session_key: str, + session: dict[str, Any], + *, + claimed_by: int | None, ) -> bool: """Free a container whose owner vanished without releasing (heartbeat went stale). Same order as an owner release: stop the emulator so the card is quiescent, evacuate and wipe it, credit the owner's playtime, then drop the claim. - Returns False when the session stopped looking abandoned before any of that - started, meaning the owner came back or another request got here first. + Args: + claimed_by: the user whose claim found the session, None for the reaper. + + Returns: + Whether the emulator was stopped: False when the session stopped looking + abandoned first, or a step before the stop failed and it was put back. """ # Claim the teardown before touching the broker. The work below runs for # seconds, and the staleness check that led here is older still, so without @@ -411,27 +498,37 @@ async def _teardown_abandoned_session( return False keepalive = asyncio.ensure_future(hold_drain_marker(session_key, token)) + pull_mark: saves.SavePullMark | None = None + stopping = False try: - state_slot = await quiesce_container(container, session) + # Before anything slow, as a release does. + pull_mark = await mark_exit_saves_pending(container, session) + # That tab may still be showing the stream, so leave a force-release's note, + # but not for the owner coming back, whose new tab it would end. + if session.get("user_id") != claimed_by: + await record_termination( + session, session_key, ended_by=None, reason="abandoned" + ) + stopping = True + stopped = await quiesce_container(container, session) await record_play_session(session) await clear_session_activity(session_key, session) - # That tab may still be showing the stream, so leave the same note an - # admin force-release does rather than letting the picture simply stop. - await record_termination( - session, session_key, ended_by=None, reason="abandoned" - ) - await collect_exit_state(container, session, state_slot) - collect_exit_saves(container, session) + await collect_exit_state(container, session, stopped.state_slot) + await collect_exit_saves(container, session, pull_mark, settled=stopped.settled) + pull_mark = None except Exception: log.exception("abandoned session teardown failed, key=%s", session_key) finally: - # A step raising above would otherwise leave the container unclaimable - # until the marker expires: draining blocks the claim, the takeover - # skips it, and no release path owns it. Only this teardown's own marker - # goes, never a claim that replaced it in the meantime. keepalive.cancel() - await drop_drain_marker(session_key, token) - return True + # Past the stop, free the container rather than park it until the marker + # lapses. Before it, a claim would launch over the running emulator. + if stopping: + await drop_drain_marker(session_key, token) + else: + await restore_drained_session(session_key, token, session) + if pull_mark is not None: + await saves.clear_save_pull_pending(pull_mark) + return stopping # How long a claim waits for stale sessions to be torn down before it gives up. @@ -447,6 +544,8 @@ async def await_teardown_within_budget( session_key: str, session: dict[str, Any], budget: float, + *, + claimed_by: int, ) -> bool: """Tear down an abandoned session, but only wait `budget` seconds for it. @@ -456,7 +555,9 @@ async def await_teardown_within_budget( this leaves behind blocks a claim until the teardown drops it. """ task = background.spawn_sync_task( - _teardown_abandoned_session(container, session_key, session) + teardown_abandoned_session( + container, session_key, session, claimed_by=claimed_by + ) ) try: return await asyncio.wait_for(asyncio.shield(task), timeout=budget) diff --git a/backend/handler/streaming/saves.py b/backend/handler/streaming/saves.py index a3b00cebb..9eeaf62ec 100644 --- a/backend/handler/streaming/saves.py +++ b/backend/handler/streaming/saves.py @@ -7,12 +7,17 @@ a .zip extension so the whole card set travels as a unit. """ import asyncio +import secrets +import time from datetime import datetime, timezone +from typing import NamedTuple from fastapi import HTTPException +from redis.exceptions import WatchError from handler.database import db_rom_handler, db_save_handler, db_user_handler from handler.filesystem import fs_asset_handler +from handler.redis_handler import async_cache from handler.scan_handler import scan_save from handler.streaming import broker, webstation from handler.streaming.config import ResolvedContainer @@ -22,6 +27,78 @@ from models.rom import Rom from models.user import User from utils.filesystem import sanitize_filename +# An exit files its archive in the background, so a claim landing behind it would +# hydrate from the archive before last. The exit leaves a marker a claim waits out. +SAVE_PULL_WAIT_SECONDS = 20.0 +_SAVE_PULL_KEY_PREFIX = "romm:streaming:save-pull:" +# Backstop for a backend that dies mid-pull: a marker nobody clears would cost +# every later claim on that ROM the full wait. +SAVE_PULL_TTL_SECONDS = 10 * 60 +_SAVE_PULL_POLL_SECONDS = 0.25 + + +def _save_pull_redis_key(user_id: int, rom_id: int) -> str: + return f"{_SAVE_PULL_KEY_PREFIX}{user_id}:{rom_id}" + + +class SavePullMark(NamedTuple): + """One exit's pending pull, whose token lets only that pull clear it.""" + + user_id: int + rom_id: int + token: str + + +async def mark_save_pull_pending(user_id: int, rom_id: int) -> SavePullMark: + """Hold this user's claims on this ROM until the returned mark is cleared, a + later mark taking over so an earlier pull finishing cannot let a claim past it.""" + token = secrets.token_hex(8) + await async_cache.set( + _save_pull_redis_key(user_id, rom_id), token, ex=SAVE_PULL_TTL_SECONDS + ) + return SavePullMark(user_id, rom_id, token) + + +async def clear_save_pull_pending(mark: SavePullMark) -> None: + """Drop the marker, while it is still the one `mark` set.""" + key = _save_pull_redis_key(mark.user_id, mark.rom_id) + async with async_cache.pipeline() as pipe: + await pipe.watch(key) + current = await pipe.get(key) + if isinstance(current, bytes): + current = current.decode() + if current != mark.token: + await pipe.unwatch() + return + pipe.multi() + await pipe.delete(key) + try: + await pipe.execute() + except WatchError: + # Only a later mark or the TTL moves the key, and neither is ours. + pass + + +async def wait_for_save_pull( + user_id: int, rom_id: int, budget: float = SAVE_PULL_WAIT_SECONDS +) -> bool: + """Wait for a pull of this user's saves for this ROM to finish filing. + + Returns: + Whether nothing is pending any more, False once `budget` runs out, since a + claim is interactive and must not hang on a wedged pull. + """ + key = _save_pull_redis_key(user_id, rom_id) + deadline = time.monotonic() + budget + while await async_cache.exists(key): + if time.monotonic() >= deadline: + log.warning( + "gave up waiting for the previous session's saves, rom_id=%d", rom_id + ) + return False + await asyncio.sleep(_SAVE_PULL_POLL_SECONDS) + return True + def fetch_save_archive( container: ResolvedContainer, broker_session_id: str | None = None @@ -117,11 +194,17 @@ async def pull_saves_to_library( rom_id: int, container: ResolvedContainer, broker_session_id: str | None = None, + *, + settled: bool = False, ) -> bool: """Background task: pull in-game saves from the broker and store them. Best-effort by design, a sync failure must never surface to the player, the save still exists inside the container. + + Args: + settled: the emulator is done writing, so one attempt is final where the + retries would wait out one still writing. """ user = db_user_handler.get_user(user_id) rom = db_rom_handler.get_rom(rom_id) @@ -129,7 +212,7 @@ async def pull_saves_to_library( return False emulator = container.emulator - for attempt in range(broker.PULL_ATTEMPTS): + for attempt in range(1 if settled else broker.PULL_ATTEMPTS): if attempt > 0: await asyncio.sleep(broker.PULL_RETRY_DELAY) content = await asyncio.to_thread( @@ -168,7 +251,7 @@ def _is_restorable(save: Save, emulator: str) -> bool: return _written_by(save, emulator) and _is_archive(save) -def _newest_restorable(user_id: int, rom_id: int, emulator: str) -> Save | None: +def newest_restorable(user_id: int, rom_id: int, emulator: str) -> Save | None: """The user's most recent restorable archive for this emulator.""" archives = [ save @@ -182,11 +265,11 @@ def _newest_restorable(user_id: int, rom_id: int, emulator: str) -> Save | None: def resolve_save_archive( user_id: int, rom: Rom, container: ResolvedContainer, save_id: int -) -> Save: - """Validate a pick from the launch screen's save list and return the save. +) -> tuple[Save, bool]: + """Validate a launch-screen save pick and return (save, is_foreign). Raises 404 for a save that is not the claiming user's own on this ROM, and - 400 when it cannot be restored on this container. + 400 for one neither restorable here nor accepted as an import. """ save = db_save_handler.get_save(user_id=user_id, id=save_id) # Same 404 for another user's save and another ROM's, so neither leaks. @@ -198,20 +281,25 @@ def resolve_save_archive( status_code=400, detail="This emulator always restores the newest save", ) - if not _written_by(save, container.emulator): - raise HTTPException( - status_code=400, - detail="Save was made by a different emulator", - ) + if _is_restorable(save, container.emulator): + return save, False + + spec = webstation.import_spec(container, container.emulator, container.platform) + if spec is not None and spec.accepts("save"): + return save, True + if not _is_archive(save): raise HTTPException( status_code=400, detail="Save is not a restorable archive", ) - return save + raise HTTPException( + status_code=400, + detail="Save was made by a different emulator", + ) -async def _read_archive(save: Save) -> tuple[str, bytes] | None: +async def read_restorable_archive(save: Save) -> tuple[str, bytes] | None: """The archive's (file name, content), or None when it is gone off disk.""" try: content = await fs_asset_handler.read_file(f"{save.file_path}/{save.file_name}") @@ -232,10 +320,10 @@ async def hydrate_saves_to_broker( if db_user_handler.get_user(user_id) is None or rom is None: return False - newest = _newest_restorable(user_id, rom_id, container.emulator) + newest = newest_restorable(user_id, rom_id, container.emulator) if newest is None: return False - archive = await _read_archive(newest) + archive = await read_restorable_archive(newest) if archive is None: return False file_name, content = archive @@ -254,10 +342,10 @@ async def hydrate_saves_to_webstation( The webstation broker restores as part of activate, so hydration only gets the bytes into place. `save` is the player's pick, newest when absent. """ - picked = save or _newest_restorable(user_id, rom_id, container.emulator) + picked = save or newest_restorable(user_id, rom_id, container.emulator) if picked is None: return None - archive = await _read_archive(picked) + archive = await read_restorable_archive(picked) if archive is None: return None file_name, content = archive diff --git a/backend/handler/streaming/session_store.py b/backend/handler/streaming/session_store.py index 34a3a3bc0..530df66ac 100644 --- a/backend/handler/streaming/session_store.py +++ b/backend/handler/streaming/session_store.py @@ -75,7 +75,7 @@ _CLAIM_REFRESH_SECONDS = _STREAMING_SESSION_STALE_SECONDS // 3 # this the refresh stops and the container ages back out on its own: every step # under a keepalive carries its own timeout, so overrunning this means something # is wedged, and a wedged step must not reserve a container indefinitely. -_HOLD_CEILING_SECONDS = 15 * 60 +HOLD_CEILING_SECONDS = 15 * 60 def session_redis_key(session_key: str) -> str: @@ -278,6 +278,20 @@ async def mutate_session( return session if outcome is _CasOutcome.WROTE else None +def session_platform_matches(session: dict[str, Any], platform: str) -> bool: + """Whether a session was claimed for this platform, a record from before the + field existed matching anything so an upgrade cannot strand one.""" + stored = session.get("platform") + if not isinstance(stored, str) or not stored: + return True + return stored.lower() == platform.lower() + + +def session_is_desktop(session: dict[str, Any]) -> bool: + """Whether a session is an admin desktop rather than a game.""" + return bool(session.get("desktop")) + + def same_claim(session: dict[str, Any], claim: dict[str, Any]) -> bool: """Whether a session read back is still the one a route resolved. Identity is the holder plus the moment they took it, so a re-claim by the same user does @@ -319,6 +333,11 @@ def drain_marker(token: str) -> str: return json.dumps({"draining": True, "drain_token": token}) +def _holds_marker(token: str) -> Callable[[dict[str, Any]], bool]: + """Whether a session key still holds the drain marker `token` wrote.""" + return lambda current: current.get("drain_token") == token + + async def claim_drain_marker( session_key: str, claim: dict[str, Any], ttl: int = DRAIN_MARKER_TTL ) -> str | None: @@ -353,13 +372,13 @@ async def hold_drain_marker(session_key: str, token: str) -> None: minute instead of parking it for the length of a transfer nobody is doing. """ marker = drain_marker(token) - deadline = time.monotonic() + _HOLD_CEILING_SECONDS + deadline = time.monotonic() + HOLD_CEILING_SECONDS while True: await asyncio.sleep(_DRAIN_MARKER_REFRESH) try: held = await replace_session_if( session_key, - lambda current: current.get("drain_token") == token, + _holds_marker(token), marker, DRAIN_MARKER_TTL, ) @@ -376,7 +395,7 @@ async def hold_drain_marker(session_key: str, token: str) -> None: "stopped refreshing the drain marker on %s, the work behind it " "has run for over %ss", session_key, - _HOLD_CEILING_SECONDS, + HOLD_CEILING_SECONDS, ) return @@ -389,7 +408,7 @@ async def hold_session_claim(session_key: str, claim: dict[str, Any]) -> None: gone, so without this the record ages past `_STREAMING_SESSION_STALE_SECONDS` and the next claimant tears the container down mid-work. """ - deadline = time.monotonic() + _HOLD_CEILING_SECONDS + deadline = time.monotonic() + HOLD_CEILING_SECONDS while True: await asyncio.sleep(_CLAIM_REFRESH_SECONDS) try: @@ -408,12 +427,14 @@ async def hold_session_claim(session_key: str, claim: dict[str, Any]) -> None: "stopped refreshing the claim on %s, the work behind it has run " "for over %ss", session_key, - _HOLD_CEILING_SECONDS, + HOLD_CEILING_SECONDS, ) return -async def stamp_launched(session_key: str, claim: dict[str, Any]) -> None: +async def stamp_launched( + session_key: str, claim: dict[str, Any], host: str | None +) -> None: """Record that the activate returned, so the status poll stops asking the broker for an extraction phase. @@ -424,11 +445,18 @@ async def stamp_launched(session_key: str, claim: dict[str, Any]) -> None: Best-effort: a stamp that never lands only costs a few redundant broker round trips, and failing a session that is already up would be worse. + + Args: + host: a game's room URL, for the status poll to hand a tab that missed + the push; None for a desktop, whose POST is the only reader. """ try: await mutate_session( session_key, - {"launched_at": datetime.now(timezone.utc).isoformat()}, + { + "launched_at": datetime.now(timezone.utc).isoformat(), + **({"host": host} if host else {}), + }, require=lambda current: same_claim(current, claim), ) except StreamingSessionContended: @@ -444,13 +472,28 @@ async def drop_drain_marker(session_key: str, token: str) -> None: try: await replace_session_if( session_key, - lambda current: current.get("drain_token") == token, + _holds_marker(token), None, ) except StreamingSessionContended: log.warning("could not drop the drain marker on %s", session_key) +async def restore_drained_session( + session_key: str, token: str, session: dict[str, Any] +) -> None: + """Put `session` back in place of the drain marker `token` wrote, while it is still there.""" + try: + await replace_session_if( + session_key, + _holds_marker(token), + json.dumps(session), + STREAMING_SESSION_TTL_SECONDS, + ) + except StreamingSessionContended: + log.warning("could not restore the session on %s", session_key) + + async def release_own_session(session_key: str, claim: dict[str, Any]) -> bool: """Free a container, while the key still holds the claim being released. @@ -534,6 +577,27 @@ def session_is_stale(session: dict[str, Any]) -> bool: return age > _STREAMING_SESSION_STALE_SECONDS +# Heartbeats fail while the backend is down, but the stream runs straight from +# the container, so a restart gives every tab one stale window to beat again. +_RESTART_GRACE_KEY = "romm:streaming:restart-grace" + + +async def start_restart_grace() -> None: + await async_cache.set(_RESTART_GRACE_KEY, "1", ex=_STREAMING_SESSION_STALE_SECONDS) + + +async def in_restart_grace() -> bool: + return bool(await async_cache.exists(_RESTART_GRACE_KEY)) + + +async def get_abandoned_session(session_key: str) -> dict[str, Any] | None: + """The claim on `session_key` when its heartbeat went stale, never a drain marker.""" + session = await get_live_session(session_key) + if session is None or not session_is_stale(session): + return None + return session + + # ── Termination notices ─────────────────────────────────────────────────────── # An admin force-release deletes the session key, but the displaced player's @@ -570,6 +634,12 @@ async def record_termination( "platform": session.get("platform"), "rom_id": session.get("rom_id"), "rom_name": session.get("rom_name"), + # Which claim ended: a user can hold one per container, plus a desktop, + # and only the tab that holds this one should act on the notice. + "container": session_key, + # A re-claim of the container keeps its key, so the stamp names the claim. + "claimed_at": session.get("claimed_at"), + "desktop": session_is_desktop(session), } await async_cache.set( _termination_redis_key(session_key, user_id), diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index b78eea2f8..4c4cf6676 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -36,7 +36,7 @@ from handler.database import ( db_user_handler, ) from handler.filesystem import fs_asset_handler -from handler.streaming import broker, commands +from handler.streaming import broker, commands, webstation from handler.streaming.config import ResolvedContainer from handler.streaming.session_store import set_session_disc from logger.logger import log @@ -57,13 +57,16 @@ _SLOT_PATTERNS = { # RetroArch leaves the number off its default slot: "GAME.state" is slot 0 # and "GAME.state3" is slot 3. "retroarch": re.compile(r"\.state(\d{0,2})$"), + # DuckStation and RPCS3 write one exit state per game with no slot in the + # name, so the empty group reads as the working slot 0. + "duckstation": re.compile(r"()\.sav$"), + "rpcs3": re.compile(r"()\.SAVESTAT(?:\.zst|\.gz)?$"), } -# Lowest slot each emulator's broker will actually address. Everything but -# RetroArch counts from 1, so a "0" in one of their names is a filename that -# happens to look like a state, not a slot they could load. -_MIN_SLOT = {"retroarch": 0} +# Lowest slot each emulator's broker addresses. The rest count from 1, so a "0" +# in one of their names is a filename that looks like a state, not a slot. +_MIN_SLOT = {"duckstation": 0, "retroarch": 0, "rpcs3": 0} def slot_from_state_filename(emulator: str, filename: str) -> int | None: @@ -110,13 +113,13 @@ def container_state_filename(filename: str) -> str: def resolve_resume_state( user_id: int, rom: Rom, container: ResolvedContainer, state_id: int -) -> tuple[State, int]: - """Validate a resume-from-state pick and return (state, slot). +) -> tuple[State, int, bool]: + """Validate a resume-from-state pick and return (state, slot, is_foreign). Visibility follows the same rule as the state list the picker was built from: the claiming user's own states plus other users' public ones. - Raises 404 for anything invisible, 400 when the state cannot drive a - resume on this container. + Raises 404 for anything invisible, 400 for a foreign state the broker + will not import. """ state = next( ( @@ -132,19 +135,26 @@ def resolve_resume_state( raise HTTPException(status_code=404, detail="State not found") emulator = container.emulator - if (state.emulator or "").lower() != emulator: + native = (state.emulator or "").lower() == emulator + if native: + slot = slot_from_state_filename(emulator, state.file_name) + if slot is not None: + return state, slot, False + + spec = webstation.import_spec(container, emulator, container.platform) + import_slot = spec.resume_slot() if spec is not None else None + if import_slot is not None: + return state, import_slot, True + + if not native: raise HTTPException( status_code=400, detail="State was made by a different emulator", ) - - slot = slot_from_state_filename(emulator, state.file_name) - if slot is None: - raise HTTPException( - status_code=400, - detail="State filename carries no recognizable slot number", - ) - return state, slot + raise HTTPException( + status_code=400, + detail="State filename carries no recognizable slot number", + ) def fetch_state_file( @@ -482,9 +492,10 @@ async def hydrate_states_to_broker( For the same reason, a resume pick already sent at claim time means there is nothing to add here: any push would overwrite it before the broker's - deferred load fires. + deferred load fires. A container that resumes from its save archive takes no + state file at all, and the archive already carries the newest exit state. """ - if resume_pushed: + if resume_pushed or container.resumes_from_archive: return 0 user = db_user_handler.get_user(user_id) diff --git a/backend/handler/streaming/webstation.py b/backend/handler/streaming/webstation.py index f5d5e180b..adb97674e 100644 --- a/backend/handler/streaming/webstation.py +++ b/backend/handler/streaming/webstation.py @@ -21,8 +21,12 @@ RomM can only come back for it once the teardown has answered. What is still missing here is volume, mute and whole-card sync. """ +import http.client +import math +import time import urllib.error -from typing import Any +from dataclasses import dataclass +from typing import Any, Literal from urllib.parse import quote from config import STREAMING_LAUNCH_TIMEOUT, STREAMING_SAVE_TIMEOUT @@ -33,6 +37,103 @@ from logger.logger import log from models.user import User +@dataclass(frozen=True) +class ImportSpec: + """What one (emulator, platform) pair accepts through a declared import.""" + + kinds: frozenset[str] + state_channel: str + state_slot: int | None + + def accepts(self, kind: str) -> bool: + return kind in self.kinds + + def resume_slot(self) -> int | None: + """The slot an imported state resumes through, or None when it cannot.""" + if self.accepts("state") and self.state_channel != "none": + return self.state_slot + return None + + def pickable_kinds(self) -> list[Literal["save", "state"]]: + """The launch picks a foreign save or state can resume through here.""" + kinds: list[Literal["save", "state"]] = [] + if self.accepts("save"): + kinds.append("save") + if self.resume_slot() is not None: + kinds.append("state") + return kinds + + +# Per container, so one broker's answer never speaks for another. A 404 or 422 +# holds for the worker's life, an answer for one claim's checks, a failure not at all. +_IMPORT_SPEC_TTL = 30.0 +_import_spec_cache: dict[tuple[str, str, str], tuple[float, "ImportSpec | None"]] = {} + + +def _parse_import_spec(body: dict[str, Any]) -> ImportSpec | None: + raw_kinds = body.get("kinds") + if not isinstance(raw_kinds, list): + log.warning("import-spec response has no kinds list, treating as unknown") + return None + if not all( + isinstance(entry, dict) and isinstance(entry.get("kind"), str) + for entry in raw_kinds + ): + log.warning("import-spec response has a malformed kind entry, %r", raw_kinds) + return None + state_channel = body.get("state_channel") + if state_channel not in ("archive", "push", "none"): + log.warning( + "import-spec response has an unrecognized state_channel, %r", + state_channel, + ) + return None + state_slot = body.get("state_slot") + return ImportSpec( + kinds=frozenset(entry["kind"] for entry in raw_kinds), + state_channel=state_channel, + state_slot=state_slot if isinstance(state_slot, int) else None, + ) + + +def import_spec( + container: ResolvedContainer, emulator: str, platform: str +) -> ImportSpec | None: + """What this broker accepts as a declared import, or None when nothing or unknown.""" + if not container.is_webstation: + return None + cache_key = (container.key, emulator, platform) + cached = _import_spec_cache.get(cache_key) + if cached is not None and cached[0] > time.monotonic(): + return cached[1] + path = container.protocol.session_route( + f"/import-spec?emulator={quote(emulator, safe='')}&platform={quote(platform, safe='')}" + ) + try: + resp = broker.request(container, path, method="GET", timeout=ACK_TIMEOUT) + except urllib.error.HTTPError as exc: + code = exc.code + exc.close() + if code in (404, 422): + _import_spec_cache[cache_key] = (math.inf, None) + return None + log.warning("import-spec check failed with HTTP %d, treating as unknown", code) + return None + except (urllib.error.URLError, OSError, http.client.HTTPException): + log.warning("import-spec check unreachable, treating as unknown") + return None + except ValueError as exc: + log.warning("import-spec response was not valid JSON, %s", exc) + return None + if not isinstance(resp, dict): + log.warning("import-spec response was not a JSON object, treating as unknown") + return None + spec = _parse_import_spec(resp) + if spec is not None: + _import_spec_cache[cache_key] = (time.monotonic() + _IMPORT_SPEC_TTL, spec) + return spec + + def activate( container: ResolvedContainer, *, diff --git a/backend/handler/sync/comparison.py b/backend/handler/sync/comparison.py index 980eb872a..b71065047 100644 --- a/backend/handler/sync/comparison.py +++ b/backend/handler/sync/comparison.py @@ -1,11 +1,12 @@ from __future__ import annotations +from collections.abc import Collection from datetime import datetime from typing import Literal, NamedTuple from utils.datetime import to_utc -SyncAction = Literal["upload", "download", "conflict", "no_op"] +SyncAction = Literal["upload", "download", "conflict", "no_op", "delete"] class SyncComparisonResult(NamedTuple): @@ -71,3 +72,20 @@ def compare_save_state( return SyncComparisonResult("conflict", "Same timestamp but different content") return SyncComparisonResult("no_op", "Saves appear identical") + + +def compare_missing_server_save( + client_hash: str | None, deleted_hashes: Collection[str] +) -> SyncComparisonResult: + """Decide a client save whose slot has no server save, matched by identity. + + Args: + client_hash: The digest the client reported, when it reported one. + deleted_hashes: What the slot is known to have lost. + + Returns: + `delete` when the client holds a version the slot lost, else `upload`. + """ + if client_hash in deleted_hashes: + return SyncComparisonResult("delete", "Save was deleted on the server") + return SyncComparisonResult("upload", "Save exists on client but not on server") diff --git a/backend/handler/sync/retroarch/sync_handler.py b/backend/handler/sync/retroarch/sync_handler.py index 9a65da75f..cb20c63cb 100644 --- a/backend/handler/sync/retroarch/sync_handler.py +++ b/backend/handler/sync/retroarch/sync_handler.py @@ -11,7 +11,7 @@ from collections.abc import Awaitable, Callable, Collection, Iterable, Sequence from dataclasses import dataclass from datetime import datetime from functools import partial -from typing import Literal, NamedTuple, cast +from typing import Literal, NamedTuple from handler.database import ( db_rom_handler, @@ -88,7 +88,7 @@ def parse_retroarch_sync_path(path: str) -> RetroArchSyncPath | None: if segments[0] not in ASSET_ROOTS: return None - kind = cast(AssetKind, segments[0]) + kind = segments[0] emulator = None if len(segments) == 3: @@ -407,7 +407,7 @@ class ManifestAsset(NamedTuple): def _manifest_assets( user: User, can_see: Callable[[Rom], bool], tree: AssetKind | None = None -) -> tuple[list[ManifestAsset], list[Save]]: +) -> tuple[list[ManifestAsset], Sequence[Save]]: """The manifest's saves and states (only `tree`'s when given), plus the unslotted saves its PSP bundles come from.""" # Slotted saves are RomM's timestamped history, which no core would load. saves = ( diff --git a/backend/main.py b/backend/main.py index fa3b3c354..2444bf849 100644 --- a/backend/main.py +++ b/backend/main.py @@ -9,7 +9,6 @@ import sentry_sdk import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware -from fastapi_pagination import add_pagination from starlette.middleware.authentication import AuthenticationMiddleware from startup import main @@ -29,6 +28,7 @@ from config import ( ROMM_CORS_ALLOWED_ORIGINS, ROMM_SESSION_SECURE_COOKIE, SENTRY_DSN, + cors_allow_credentials, ) from endpoints.activity import router as activity_router from endpoints.audit_events import router as audit_events_router @@ -53,6 +53,7 @@ from endpoints.permissions import router as permissions_router from endpoints.platform import router as platform_router from endpoints.play_sessions import router as play_sessions_router from endpoints.recommendations import router as recommendations_router +from endpoints.responses.streaming import SOCKET_PAYLOADS as STREAMING_SOCKET_PAYLOADS from endpoints.roms import router as rom_router from endpoints.saves import router as saves_router from endpoints.screenshots import router as screenshots_router @@ -69,6 +70,7 @@ from handler.auth.middleware.csrf_middleware import CSRFMiddleware from handler.auth.middleware.redis_session_middleware import RedisSessionMiddleware from handler.middleware.upload_size_middleware import UploadSizeLimitMiddleware from handler.socket_handler import netplay_socket_handler, socket_handler +from handler.streaming.session_store import start_restart_grace from logger.formatter import LOGGING_CONFIG from utils import get_version from utils.context import ( @@ -78,6 +80,7 @@ from utils.context import ( set_context_middleware, ) from utils.memory_cards import MEMORY_CARD_MAX_BYTES +from utils.openapi import publish_socket_payloads logging.config.dictConfig(LOGGING_CONFIG) @@ -87,6 +90,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None]: async with initialize_context(): app.state.aiohttp_session = ctx_aiohttp_session.get() app.state.httpx_client = ctx_httpx_client.get() + await start_restart_grace() # Relay backend log lines to admin Socket.IO clients in real time. log_forwarder_task: asyncio.Task[None] | None = None @@ -122,7 +126,7 @@ app = FastAPI( app.add_middleware( CORSMiddleware, allow_origins=ROMM_CORS_ALLOWED_ORIGINS, - allow_credentials=True, + allow_credentials=cors_allow_credentials(ROMM_CORS_ALLOWED_ORIGINS), allow_methods=["*"], allow_headers=["*"], ) @@ -220,7 +224,7 @@ app.include_router(streaming_router, prefix="/api") app.mount("/ws", socket_handler.socket_app) app.mount("/netplay", netplay_socket_handler.socket_app) -add_pagination(app) +publish_socket_payloads(app, STREAMING_SOCKET_PAYLOADS) # NOTE: This code is only executed when running the application directly, diff --git a/backend/models/deleted_asset.py b/backend/models/deleted_asset.py new file mode 100644 index 000000000..f40478d39 --- /dev/null +++ b/backend/models/deleted_asset.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from sqlalchemy import ForeignKey, Index, String +from sqlalchemy.orm import Mapped, mapped_column + +from models.assets import SAVE_SLOT_MAX_LENGTH +from models.base import BaseModel +from utils.database import CustomJSON + +# Trimming drops the oldest, which a long-offline device is likeliest to hold; +# past the bound that device is answered `upload` rather than `delete`. +MAX_REMEMBERED_HASHES = 100 + + +class DeletedAsset(BaseModel): + """A slot emptied by its owner, so a device still holding it can be told.""" + + __tablename__ = "deleted_assets" + __table_args__ = ( + # One row per slot, however often it is emptied and refilled. + Index( + "ix_deleted_assets_user_rom_slot", "user_id", "rom_id", "slot", unique=True + ), + {"extend_existing": True}, + ) + + 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"), index=True + ) + slot: Mapped[str] = mapped_column(String(length=SAVE_SLOT_MAX_LENGTH)) + # Every version the slot lost, matched by identity rather than by time: + # a device's clock is not the server's. + content_hashes: Mapped[list[str]] = mapped_column(CustomJSON(), default=list) diff --git a/backend/models/notification_channel.py b/backend/models/notification_channel.py index f113a44b6..3d6ebe3bb 100644 --- a/backend/models/notification_channel.py +++ b/backend/models/notification_channel.py @@ -12,16 +12,13 @@ from utils.database import CustomJSON class NotificationChannelType(enum.StrEnum): + # Any service Apprise reaches, set up through that service's own fields. + APPRISE = "apprise" + # RomM's own JSON payload, signed when the channel has a secret. WEBHOOK = "webhook" EMAIL = "email" -class WebhookFormat(enum.StrEnum): - JSON = "json" - DISCORD = "discord" - NTFY = "ntfy" - - class NotificationChannelMinLevel(enum.StrEnum): """The least severe notification a channel forwards; success ranks as info.""" @@ -36,6 +33,10 @@ NOTIFICATION_CHANNEL_SECRET_MAX_LENGTH: Final = 255 NOTIFICATION_CHANNEL_ERROR_MAX_LENGTH: Final = 1000 NOTIFICATION_CHANNEL_ADDRESS_MAX_LENGTH: Final = 320 NOTIFICATION_CHANNEL_CODE_MAX_LENGTH: Final = 16 +NOTIFICATION_CHANNEL_SERVICE_MAX_LENGTH: Final = 32 +NOTIFICATION_CHANNEL_MAX_FIELDS: Final = 64 +# Each target of a list is its own request to the service. +NOTIFICATION_CHANNEL_MAX_LIST_ITEMS: Final = 20 MAX_NOTIFICATION_CHANNELS_PER_USER: Final = 20 # A channel that fails this many deliveries in a row turns itself off. MAX_CONSECUTIVE_DELIVERY_FAILURES: Final = 10 @@ -51,7 +52,7 @@ class NotificationChannel(BaseModel): ) type: Mapped[str] = mapped_column(String(16)) name: Mapped[str] = mapped_column(String(NOTIFICATION_CHANNEL_NAME_MAX_LENGTH)) - # Sealed with `utils.secret_box`: a webhook URL can carry its own token. + # Sealed with `utils.secret_box`: a URL can carry its own token. config: Mapped[str] = mapped_column(Text) min_level: Mapped[str] = mapped_column(String(16), default="info") # None forwards every topic. diff --git a/backend/models/play_session.py b/backend/models/play_session.py index c4c22ddff..6369060a9 100644 --- a/backend/models/play_session.py +++ b/backend/models/play_session.py @@ -8,7 +8,6 @@ from sqlalchemy import ( BigInteger, ForeignKey, Index, - Integer, String, ) from sqlalchemy.orm import Mapped, mapped_column, relationship @@ -18,7 +17,6 @@ from models.base import BaseModel if TYPE_CHECKING: from models.device import Device from models.rom import Rom - from models.sync_session import SyncSession from models.user import User @@ -46,9 +44,6 @@ class PlaySession(BaseModel): rom_id: Mapped[int | None] = mapped_column( ForeignKey("roms.id", ondelete="SET NULL") ) - sync_session_id: Mapped[int | None] = mapped_column( - Integer, ForeignKey("sync_sessions.id", ondelete="SET NULL"), default=None - ) save_slot: Mapped[str | None] = mapped_column(String(255), default=None) start_time: Mapped[datetime] = mapped_column(TIMESTAMP(timezone=True)) end_time: Mapped[datetime] = mapped_column(TIMESTAMP(timezone=True)) @@ -57,4 +52,3 @@ class PlaySession(BaseModel): user: Mapped[User] = relationship(lazy="raise", back_populates="play_sessions") device: Mapped[Device | None] = relationship(lazy="raise") rom: Mapped[Rom | None] = relationship(lazy="raise") - sync_session: Mapped[SyncSession | None] = relationship(lazy="raise") diff --git a/backend/models/rom.py b/backend/models/rom.py index 3dfae3a83..386fbafcc 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -367,16 +367,10 @@ class RomFile(BaseModel): return LookupHashes(crc=self.crc_hash, md5=self.md5_hash, sha1=self.sha1_hash) - @cached_property - def is_nested(self) -> bool: - return self.file_path.count("/") > 1 - @cached_property def is_top_level(self) -> bool: - # File is the same as the rom's full path, or nested file in the rom's directory - return self.rom.full_path == ( - self.file_path if self.is_nested else self.full_path - ) + # The rom's own file, or a file directly inside the rom's folder + return self.rom.full_path in (self.full_path, self.file_path) def file_name_for_download(self, hidden_folder: bool = False) -> str: # This needs a trailing slash in the path to work! @@ -1249,11 +1243,7 @@ Rom.top_level_file_count = column_property( def apply_file_stats(rom: Rom, files: Sequence[RomFile]) -> None: - """Fill the deferred file-stat columns from an already-loaded file list. - - Mirrors the subqueries above, not `RomFile.is_top_level`, which disagrees - on nested files. - """ + """Fill the deferred file-stat columns from an already-loaded file list.""" set_committed_value( rom, "multi_file", any(f.file_path != rom.fs_path for f in files) ) @@ -1273,9 +1263,17 @@ def apply_file_stats(rom: Rom, files: Sequence[RomFile]) -> None: ) +class HasFileOnDiskFilters(TypedDict): + physical: bool + missing: bool + + # Query-side twin of `Rom.has_file_on_disk`, for callers that enumerate roms and # want the file-less ones dropped by the database rather than after loading. -HAS_FILE_ON_DISK_FILTERS = {"physical": False, "missing": False} +HAS_FILE_ON_DISK_FILTERS: Final[HasFileOnDiskFilters] = { + "physical": False, + "missing": False, +} # Maps a metadata-source slug (matching the MetadataSource enum) to the Rom diff --git a/backend/tasks/cron_config.py b/backend/tasks/cron_config.py index f0a56ed1f..9348aebc8 100644 --- a/backend/tasks/cron_config.py +++ b/backend/tasks/cron_config.py @@ -6,8 +6,7 @@ one off is a restart rather than an unschedule. from rq import cron -from config import TASK_RESULT_TTL, TASK_TIMEOUT -from handler.redis_handler import QueuePrio +from config import TASK_TIMEOUT from logger.logger import log from tasks.registry import SCHEDULED_TASKS, enqueue_scheduled_scan from tasks.tasks import TaskType, run_task_by_name @@ -24,14 +23,14 @@ for name, task in SCHEDULED_TASKS.items(): # share one cron identity and one job history. cron.register( enqueue_scheduled_scan if is_scan else run_task_by_name, - QueuePrio.LOW.value, + task.queue_name, name=name, kwargs={"name": name}, cron=task.cron_string, job_timeout=TASK_TIMEOUT if is_scan else task.timeout, # A spent dispatch carries the scan's own name, and RQ drops a job whose # result_ttl is 0, so one rescan is not listed as two runs. - result_ttl=0 if is_scan else TASK_RESULT_TTL, + result_ttl=0 if is_scan else task.result_ttl, meta=task.job_meta(name), ) log.info(f"Scheduled '{name}' at '{task.cron_string}'") diff --git a/backend/tasks/registry.py b/backend/tasks/registry.py index 6b3a36757..6f9818db8 100644 --- a/backend/tasks/registry.py +++ b/backend/tasks/registry.py @@ -5,7 +5,6 @@ from typing import Any, Final from rq.job import Job from rq.queue import Queue -from config import TASK_RESULT_TTL from exceptions.task_exceptions import TaskNotFoundException from handler.redis_handler import low_prio_queue, scan_queue from tasks.manual.cleanup_missing_firmware import cleanup_missing_firmware_task @@ -18,9 +17,11 @@ from tasks.scheduled.build_recommendations import build_recommendations_task from tasks.scheduled.cleanup_audit_log import cleanup_audit_log_task from tasks.scheduled.cleanup_netplay import cleanup_netplay_task from tasks.scheduled.cleanup_orphaned_resources import cleanup_orphaned_resources_task +from tasks.scheduled.cleanup_sync_sessions import cleanup_sync_sessions_task from tasks.scheduled.cleanup_upload_tmp import cleanup_upload_tmp_task from tasks.scheduled.cleanup_zip_cache import cleanup_zip_cache_task from tasks.scheduled.convert_images_to_webp import convert_images_to_webp_task +from tasks.scheduled.reap_streaming_sessions import reap_streaming_sessions_task from tasks.scheduled.scan_library import scan_library_task from tasks.scheduled.sync_retroachievements_progress import ( sync_retroachievements_progress_task, @@ -44,6 +45,8 @@ SCHEDULED_TASKS: Final[dict[str, PeriodicTask]] = { "cleanup_orphaned_resources": cleanup_orphaned_resources_task, "cleanup_netplay": cleanup_netplay_task, "cleanup_upload_tmp": cleanup_upload_tmp_task, + "reap_streaming_sessions": reap_streaming_sessions_task, + "cleanup_sync_sessions": cleanup_sync_sessions_task, "cleanup_audit_log": cleanup_audit_log_task, "sync_retroachievements_progress": sync_retroachievements_progress_task, "sync_push_pull": sync_push_pull_task, @@ -95,7 +98,7 @@ def enqueue_task( "run_by_user_id": run_by_user_id, }, job_timeout=task.timeout, - result_ttl=TASK_RESULT_TTL, + result_ttl=task.result_ttl, meta=task.job_meta(name), **job_options, ) diff --git a/backend/tasks/scheduled/cleanup_sync_sessions.py b/backend/tasks/scheduled/cleanup_sync_sessions.py new file mode 100644 index 000000000..7b3a5741a --- /dev/null +++ b/backend/tasks/scheduled/cleanup_sync_sessions.py @@ -0,0 +1,33 @@ +from datetime import datetime, timedelta, timezone + +from handler.database import db_sync_session_handler +from logger.logger import log +from tasks.tasks import PeriodicTask, TaskType + +# Longer than any launch, since nothing else closes a session: one killed, put +# to sleep or taken off the network would otherwise stay open for good. +STALE_AFTER_HOURS = 24 + + +class CleanupSyncSessionsTask(PeriodicTask): + def __init__(self): + super().__init__( + title="Scheduled sync session cleanup", + description="Fails sync sessions no client ever completed", + task_type=TaskType.CLEANUP, + enabled=True, + manual_run=False, + cron_string="23 * * * *", # Hourly, off the hour + ) + + async def run(self) -> None: + if not self.enabled: + return + + cutoff = datetime.now(timezone.utc) - timedelta(hours=STALE_AFTER_HOURS) + failed = db_sync_session_handler.fail_stale_sessions(older_than=cutoff) + if failed: + log.info(f"Failed {failed} sync session(s) left open since {cutoff}") + + +cleanup_sync_sessions_task = CleanupSyncSessionsTask() diff --git a/backend/tasks/scheduled/reap_streaming_sessions.py b/backend/tasks/scheduled/reap_streaming_sessions.py new file mode 100644 index 000000000..4a2ed211d --- /dev/null +++ b/backend/tasks/scheduled/reap_streaming_sessions.py @@ -0,0 +1,69 @@ +import asyncio + +from handler.redis_handler import STREAMING_QUEUE_NAME +from handler.streaming.config import ( + ResolvedContainer, + container_for_session, + containers_by_key, + streaming_enabled, +) +from handler.streaming.lifecycle import teardown_abandoned_session +from handler.streaming.session_store import ( + HOLD_CEILING_SECONDS, + get_abandoned_session, + in_restart_grace, +) +from logger.logger import log +from tasks.tasks import PeriodicTask, TaskType + + +async def _reap( + grouped: dict[str, list[ResolvedContainer]], container_key: str +) -> None: + try: + session = await get_abandoned_session(container_key) + if session is None: + return + record = container_for_session(grouped, container_key, session.get("platform")) + if record is None: + return + if await teardown_abandoned_session( + record, container_key, session, claimed_by=None + ): + log.info( + "reaped abandoned streaming session, platform=%s user_id=%s", + record.platform, + session.get("user_id"), + ) + except Exception: + log.exception("streaming session reap failed, key=%s", container_key) + + +class ReapStreamingSessionsTask(PeriodicTask): + def __init__(self): + super().__init__( + title="Scheduled streaming session reaper", + description="Stops streaming sessions whose player stopped sending heartbeats", + task_type=TaskType.CLEANUP, + # Read once, as cron registers only enabled tasks when it starts. + enabled=streaming_enabled(), + manual_run=False, + cron_string="* * * * *", # Every minute + # RQ kills a job at its timeout, so it has to cover a teardown holding + # its marker to the ceiling. + timeout=HOLD_CEILING_SECONDS, + result_ttl=0, + queue_name=STREAMING_QUEUE_NAME, + ) + + async def run(self) -> None: + if not self.enabled or await in_restart_grace(): + return + + # Empty once streaming is disabled, so a disabled install reaps nothing. + grouped = containers_by_key() + # Concurrent, so one sick broker cannot hold up every other container. + await asyncio.gather(*(_reap(grouped, key) for key in grouped)) + + +reap_streaming_sessions_task = ReapStreamingSessionsTask() diff --git a/backend/tasks/scheduled/sync_retroachievements_progress.py b/backend/tasks/scheduled/sync_retroachievements_progress.py index eef49cd79..cc073799b 100644 --- a/backend/tasks/scheduled/sync_retroachievements_progress.py +++ b/backend/tasks/scheduled/sync_retroachievements_progress.py @@ -116,7 +116,8 @@ class SyncRetroAchievementsProgressTask(PeriodicTask): for user in users: try: user_progression = await meta_ra_handler.get_user_progression( - user.ra_username, + # `has_ra_username` above filters out users without one + cast(str, user.ra_username), current_progression=cast( RAUserProgression | None, user.ra_progression ), diff --git a/backend/tasks/tasks.py b/backend/tasks/tasks.py index 5c49822fa..6c61b5ba6 100644 --- a/backend/tasks/tasks.py +++ b/backend/tasks/tasks.py @@ -9,9 +9,11 @@ from rq.exceptions import AbandonedJobError from rq.job import Job from rq.timeouts import JobTimeoutException -from config import TASK_TIMEOUT +from config import TASK_RESULT_TTL, TASK_TIMEOUT from exceptions.task_exceptions import TaskNotFoundException +from handler.redis_handler import QueuePrio from logger.logger import log +from utils.background_tasks import wait_for_background_tasks from utils.context import ctx_httpx_client @@ -44,7 +46,11 @@ async def run_task_by_name( if task is None: raise TaskNotFoundException(name) - result = await task.run(**(task_kwargs or {})) + try: + result = await task.run(**(task_kwargs or {})) + finally: + # RQ runs the job on a loop that never runs again once it returns. + await wait_for_background_tasks() await _notify_task_end(name, task, run_by_user_id) return result @@ -149,6 +155,8 @@ class Task(ABC): cron_string: str | None = None task_type: TaskType timeout: int + result_ttl: int + queue_name: str def __init__( self, @@ -159,6 +167,8 @@ class Task(ABC): manual_run: bool = False, cron_string: str | None = None, timeout: int = TASK_TIMEOUT, + result_ttl: int = TASK_RESULT_TTL, + queue_name: str = QueuePrio.LOW.value, ): self.title = title self.description = description or title @@ -167,6 +177,8 @@ class Task(ABC): self.manual_run = manual_run self.cron_string = cron_string self.timeout = timeout + self.result_ttl = result_ttl + self.queue_name = queue_name @property def can_run_manually(self) -> bool: diff --git a/backend/tests/adapters/services/test_steam.py b/backend/tests/adapters/services/test_steam.py index 567eae10e..6894194d7 100644 --- a/backend/tests/adapters/services/test_steam.py +++ b/backend/tests/adapters/services/test_steam.py @@ -66,6 +66,36 @@ async def test_get_app_details_unwraps_envelope(session): assert details == {"type": "game", "name": "Portal"} +async def test_get_app_details_unwraps_envelope_keyed_by_another_id(session): + """Steam keys some apps' details by a DLC ID instead of the requested one.""" + session.get.return_value = _response( + { + "662290": { + "success": True, + "data": {"type": "game", "name": "140", "steam_appid": 242820}, + } + } + ) + + details = await SteamService().get_app_details(242820) + + assert details == {"type": "game", "name": "140", "steam_appid": 242820} + + +async def test_get_app_details_rejects_envelope_for_another_app(session): + session.get.return_value = _response( + {"662290": {"success": True, "data": {"type": "dlc", "steam_appid": 662290}}} + ) + + assert await SteamService().get_app_details(242820) is None + + +async def test_get_app_details_rejects_a_sole_value_that_is_not_an_envelope(session): + session.get.return_value = _response({"error": "unavailable"}) + + assert await SteamService().get_app_details(242820) is None + + async def test_get_app_details_returns_none_on_unsuccessful_envelope(session): """Steam reports an unknown or region-locked app as success: false.""" session.get.return_value = _response({"400": {"success": False}}) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 1a8f24176..827efa5ce 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -34,6 +34,7 @@ from models.assets import MemoryCard, MemoryCardVersion, Save, Screenshot, State from models.audit_event import AuditEvent from models.client_token import ClientToken from models.container_adoption import StreamingContainerAdoption +from models.deleted_asset import DeletedAsset from models.device import Device from models.device_save_sync import DeviceSaveSync from models.firmware import Firmware @@ -145,6 +146,7 @@ def clear_database(): s.query(MemoryCardVersion).delete(synchronize_session="evaluate") s.query(MemoryCard).delete(synchronize_session="evaluate") s.query(StreamingContainerAdoption).delete(synchronize_session="evaluate") + s.query(DeletedAsset).delete(synchronize_session="evaluate") s.query(Save).delete(synchronize_session="evaluate") s.query(State).delete(synchronize_session="evaluate") s.query(Screenshot).delete(synchronize_session="evaluate") diff --git a/backend/tests/endpoints/roms/conftest.py b/backend/tests/endpoints/roms/conftest.py index b7d2c67fb..a7ab450d4 100644 --- a/backend/tests/endpoints/roms/conftest.py +++ b/backend/tests/endpoints/roms/conftest.py @@ -64,4 +64,6 @@ def game_folder_rom(admin_user: User, platform: Platform) -> Rom: category=RomFileCategory.GAME, ) ) - return db_rom_handler.get_rom(rom.id) + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + return refreshed diff --git a/backend/tests/endpoints/roms/test_convert_to_folder.py b/backend/tests/endpoints/roms/test_convert_to_folder.py index a605c85cf..a2e506579 100644 --- a/backend/tests/endpoints/roms/test_convert_to_folder.py +++ b/backend/tests/endpoints/roms/test_convert_to_folder.py @@ -57,7 +57,9 @@ def _single_file_rom( disk = lib / rom.fs_path / fs_name disk.parent.mkdir(parents=True, exist_ok=True) disk.write_bytes(b"romdata") - return db_rom_handler.get_rom(rom.id) + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + return refreshed # ---------- POST /api/roms/{id}/convert-to-folder ---------- @@ -87,6 +89,7 @@ def test_convert_single_file_promotes_in_place( assert response.status_code == status.HTTP_200_OK after = db_rom_handler.get_rom(rom_id) + assert after is not None assert after.id == rom_id # same id, no dead reference assert after.fs_name == "test_rom" game_file = after.files[0] @@ -125,6 +128,7 @@ def test_convert_already_folder_is_clean_noop( ) assert second.status_code == status.HTTP_200_OK after = db_rom_handler.get_rom(rom.id) + assert after is not None assert after.fs_name == "test_rom" # unchanged by the second call @@ -152,6 +156,7 @@ def test_convert_folder_collision_returns_409( assert response.status_code == status.HTTP_409_CONFLICT after = db_rom_handler.get_rom(rom.id) + assert after is not None assert after.fs_name == "test_rom.zip" # untouched @@ -179,6 +184,7 @@ def test_convert_extensionless_uses_staging( moved = real_library / f"{platform.slug}/roms/test_rom/test_rom" assert moved.is_file() and moved.read_bytes() == b"romdata" after = db_rom_handler.get_rom(rom.id) + assert after is not None assert after.files[0].file_path == f"{platform.slug}/roms/test_rom" @@ -209,6 +215,7 @@ def test_convert_extensionless_dir_collision_returns_409( assert response.status_code == status.HTTP_409_CONFLICT after = db_rom_handler.get_rom(rom.id) + assert after is not None assert after.fs_name == "test_rom" # untouched assert (lone / "already_here.txt").read_text() == "keep me" # user's dir intact @@ -245,6 +252,7 @@ def test_convert_rolls_back_fs_on_db_failure( assert (base / "test_rom").read_bytes() == b"romdata" assert not (base / ".romm_tmp_test_rom").exists() after = db_rom_handler.get_rom(rom.id) + assert after is not None assert after.fs_name == "test_rom" assert after.has_simple_single_file @@ -275,6 +283,7 @@ def test_soundtrack_upload_auto_converts_single_file_rom( assert response.status_code == status.HTTP_201_CREATED after = db_rom_handler.get_rom(rom.id) + assert after is not None assert after.fs_name == "test_rom" # converted soundtracks = [f for f in after.files if f.category == RomFileCategory.SOUNDTRACK] assert len(soundtracks) == 1 @@ -306,6 +315,7 @@ def test_manual_upload_auto_converts_single_file_rom( assert response.status_code == status.HTTP_201_CREATED after = db_rom_handler.get_rom(rom.id) + assert after is not None assert after.fs_name == "test_rom" assert any(f.category == RomFileCategory.MANUAL for f in after.files) @@ -333,6 +343,7 @@ def test_screenshot_upload_auto_converts_single_file_rom( assert response.status_code == status.HTTP_201_CREATED after = db_rom_handler.get_rom(rom.id) + assert after is not None assert after.fs_name == "test_rom" assert any(f.category == RomFileCategory.SCREENSHOT for f in after.files) @@ -352,6 +363,7 @@ async def test_second_upload_racing_a_promotion_keeps_the_rom_in_its_folder( fs_extension="zip", ) second = db_rom_handler.get_rom(rom.id) + assert second is not None # Holding both at the mkdir puts them past the collision check together. make_directory = fs_rom_handler.make_directory @@ -394,6 +406,7 @@ async def test_promotion_racing_across_workers_does_not_destroy_the_folder( fs_extension="zip", ) second = db_rom_handler.get_rom(rom.id) + assert second is not None class _NoLock: async def __aenter__(self) -> None: diff --git a/backend/tests/endpoints/roms/test_manual.py b/backend/tests/endpoints/roms/test_manual.py index bf7de1b99..5932f2bc0 100644 --- a/backend/tests/endpoints/roms/test_manual.py +++ b/backend/tests/endpoints/roms/test_manual.py @@ -67,6 +67,7 @@ def test_upload_manual_to_resources_success( assert written.exists() assert written.read_bytes() == PDF_BYTES refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None assert refreshed.path_manual == f"{rom.fs_resources_path}/manual/{rom.id}.pdf" assert refreshed.locked_fields == ["url_manual"] @@ -88,6 +89,7 @@ def test_upload_markdown_manual_to_resources_preserves_extension( assert written.exists() assert written.read_bytes() == MD_BYTES refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None assert refreshed.path_manual == f"{rom.fs_resources_path}/manual/{rom.id}.md" @@ -165,6 +167,7 @@ def test_upload_manual_to_folder_success( assert written.read_bytes() == PDF_BYTES rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert rom_after is not None manual_files = [f for f in rom_after.files if f.category == RomFileCategory.MANUAL] assert len(manual_files) == 1 assert manual_files[0].file_name == "english.pdf" @@ -187,6 +190,7 @@ def test_upload_manual_to_folder_upserts_on_reupload( assert response.status_code == status.HTTP_201_CREATED rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert rom_after is not None manual_files = [f for f in rom_after.files if f.category == RomFileCategory.MANUAL] assert len(manual_files) == 1 @@ -254,6 +258,7 @@ def test_redownload_manual_success( assert response.status_code == status.HTTP_200_OK refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None assert refreshed.path_manual == fake_path assert refreshed.locked_fields == [] @@ -311,6 +316,7 @@ def test_delete_manual_success( assert response.status_code == status.HTTP_200_OK remove_mock.assert_awaited_once() refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None assert refreshed.path_manual == "" assert refreshed.url_manual == "" assert refreshed.locked_fields == [] diff --git a/backend/tests/endpoints/roms/test_rom.py b/backend/tests/endpoints/roms/test_rom.py index 21c1a0778..535d78c3a 100644 --- a/backend/tests/endpoints/roms/test_rom.py +++ b/backend/tests/endpoints/roms/test_rom.py @@ -1095,7 +1095,9 @@ def test_update_rom_artwork_locks_the_cover( ) assert response.status_code == status.HTTP_200_OK - assert db_rom_handler.get_rom(rom.id).locked_fields == ["url_cover"] + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + assert refreshed.locked_fields == ["url_cover"] @patch.object( @@ -1119,7 +1121,9 @@ def test_remove_cover_releases_the_lock( ) assert response.status_code == status.HTTP_200_OK - assert db_rom_handler.get_rom(rom.id).locked_fields == [] + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + assert refreshed.locked_fields == [] @patch.object( @@ -1162,7 +1166,9 @@ def test_saving_without_changing_urls_keeps_locks( ) assert response.status_code == status.HTTP_200_OK - assert db_rom_handler.get_rom(rom.id).locked_fields == [ + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + assert refreshed.locked_fields == [ "url_cover", "url_manual", ] @@ -1208,7 +1214,9 @@ def test_naming_new_source_urls_releases_both_locks( ) assert response.status_code == status.HTTP_200_OK - assert db_rom_handler.get_rom(rom.id).locked_fields == [] + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + assert refreshed.locked_fields == [] def test_delete_roms(client: TestClient, access_token: str, rom: Rom): @@ -2022,7 +2030,9 @@ class TestUpdateMetadataIDs: assert response.status_code == status.HTTP_200_OK assert response.json()["url_cover"] == "" - assert db_rom_handler.get_rom(rom.id).locked_fields == ["url_cover"] + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + assert refreshed.locked_fields == ["url_cover"] @patch.object( SteamHandler, diff --git a/backend/tests/endpoints/roms/test_screenshot.py b/backend/tests/endpoints/roms/test_screenshot.py index 38954203f..712c99e7d 100644 --- a/backend/tests/endpoints/roms/test_screenshot.py +++ b/backend/tests/endpoints/roms/test_screenshot.py @@ -43,6 +43,7 @@ def test_upload_screenshot_success( assert written.read_bytes() == PNG_BYTES rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert rom_after is not None screenshots = [ f for f in rom_after.files if f.category == RomFileCategory.SCREENSHOT ] @@ -67,6 +68,7 @@ def test_upload_screenshot_upserts_on_reupload( assert response.status_code == status.HTTP_201_CREATED rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert rom_after is not None screenshots = [ f for f in rom_after.files if f.category == RomFileCategory.SCREENSHOT ] diff --git a/backend/tests/endpoints/roms/test_soundtrack.py b/backend/tests/endpoints/roms/test_soundtrack.py index 92fb36cc1..cb8da3cbe 100644 --- a/backend/tests/endpoints/roms/test_soundtrack.py +++ b/backend/tests/endpoints/roms/test_soundtrack.py @@ -47,6 +47,7 @@ def test_upload_soundtrack_success( assert written.read_bytes() == MP3_BYTES rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert rom_after is not None soundtracks = [ f for f in rom_after.files if f.category == RomFileCategory.SOUNDTRACK ] @@ -71,6 +72,7 @@ def test_upload_soundtrack_upserts_on_reupload( assert response.status_code == status.HTTP_201_CREATED rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert rom_after is not None soundtracks = [ f for f in rom_after.files if f.category == RomFileCategory.SOUNDTRACK ] @@ -114,6 +116,7 @@ def test_upload_soundtrack_keeps_the_other_files( assert response.status_code == status.HTTP_201_CREATED rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert rom_after is not None assert {f.file_name for f in rom_after.files} == before | {"track1.mp3"} assert not list(soundtrack_fs.glob(".*")) @@ -274,6 +277,7 @@ def test_upload_soundtrack_extracts_audio_meta( assert response.status_code == status.HTTP_201_CREATED rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert rom_after is not None soundtracks = [ f for f in rom_after.files if f.category == RomFileCategory.SOUNDTRACK ] @@ -320,6 +324,7 @@ def test_upload_soundtrack_no_cover_leaves_cover_path_unset( assert cover_calls == [] # never called when has_embedded_cover is False rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert rom_after is not None track = next(f for f in rom_after.files if f.category == RomFileCategory.SOUNDTRACK) assert track.track_meta is not None assert track.track_meta.cover_path is None @@ -533,6 +538,7 @@ def test_upload_soundtrack_with_malformed_audio_still_succeeds( assert response.status_code == status.HTTP_201_CREATED rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert rom_after is not None soundtracks = [ f for f in rom_after.files if f.category == RomFileCategory.SOUNDTRACK ] diff --git a/backend/tests/endpoints/roms/test_upload.py b/backend/tests/endpoints/roms/test_upload.py index ae2cdb54b..41d758f23 100644 --- a/backend/tests/endpoints/roms/test_upload.py +++ b/backend/tests/endpoints/roms/test_upload.py @@ -385,7 +385,9 @@ def _folder_rom( db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id) for rel, data in files.items(): _add_row(rom, lib, f"{ROM_FOLDER}/{rel}", data) - return db_rom_handler.get_rom(rom.id) + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + return refreshed def _single_file_rom(platform: Platform, admin_user: User, lib: Path) -> Rom: @@ -402,7 +404,9 @@ def _single_file_rom(platform: Platform, admin_user: User, lib: Path) -> Rom: rom = db_rom_handler.add_rom(rom) db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id) _add_row(rom, lib, "solo.zip", b"romdata") - return db_rom_handler.get_rom(rom.id) + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + return refreshed def _start_into_rom( @@ -612,7 +616,9 @@ def test_overwrite_replaces_an_existing_file( assert response.status_code == status.HTTP_201_CREATED, response.json() on_disk = rom_upload_fs / rom.fs_path / ROM_FOLDER / "hack" / "x.ips" assert on_disk.read_bytes() == b"new" - rows = [f for f in db_rom_handler.get_rom(rom.id).files if f.file_name == "x.ips"] + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + rows = [f for f in refreshed.files if f.file_name == "x.ips"] assert len(rows) == 1 assert rows[0].file_size_bytes == 3 @@ -644,6 +650,7 @@ def test_complete_registers_nested_file( on_disk = rom_upload_fs / rom.fs_path / ROM_FOLDER / "patches/v2/fix.ips" assert on_disk.read_bytes() == b"patch bytes" after = db_rom_handler.get_rom(rom.id) + assert after is not None new = next(f for f in after.files if f.file_name == "fix.ips") assert new.file_path == f"{rom.fs_path}/{ROM_FOLDER}/patches/v2" assert new.category == RomFileCategory.PATCH @@ -669,6 +676,7 @@ def test_complete_top_level_file_updates_rom_hashes( assert response.status_code == status.HTTP_201_CREATED after = db_rom_handler.get_rom(rom.id) + assert after is not None assert {f.file_name for f in after.files} == {"game.bin", "extra.bin"} assert after.md5_hash != "stored-md5" expected = hashlib.md5(usedforsecurity=False) @@ -698,6 +706,7 @@ def test_complete_into_single_file_rom_promotes_it_to_a_folder( assert response.status_code == status.HTTP_201_CREATED after = db_rom_handler.get_rom(rom.id) + assert after is not None assert after.fs_name == "solo" folder = f"{rom.fs_path}/solo" assert {(f.file_path, f.file_name) for f in after.files} == { @@ -752,7 +761,9 @@ def test_start_into_single_file_rom_rejects_its_own_name( ) assert response.status_code == status.HTTP_409_CONFLICT - assert db_rom_handler.get_rom(rom.id).fs_name == "solo.zip" + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + assert refreshed.fs_name == "solo.zip" def test_complete_collision_does_not_promote_a_single_file_rom( @@ -780,6 +791,7 @@ def test_complete_collision_does_not_promote_a_single_file_rom( assert response.status_code == status.HTTP_409_CONFLICT after = db_rom_handler.get_rom(rom.id) + assert after is not None assert after.fs_name == "solo.zip" assert (rom_upload_fs / rom.fs_path / "solo.zip").read_bytes() == b"romdata" diff --git a/backend/tests/endpoints/roms/test_walkthrough.py b/backend/tests/endpoints/roms/test_walkthrough.py index 5de5d5c78..9eed23f2b 100644 --- a/backend/tests/endpoints/roms/test_walkthrough.py +++ b/backend/tests/endpoints/roms/test_walkthrough.py @@ -169,6 +169,7 @@ def test_add_gamefaqs_walkthrough_success( assert len(files) == 1 created = files[0] assert created.file_name == "chrono-trigger-faq.txt" + assert created.doc_meta is not None assert created.doc_meta.source == DocSource.GAMEFAQS assert created.doc_meta.source_url == GAMEFAQS_URL assert created.doc_meta.author == "Jane Roe" diff --git a/backend/tests/endpoints/sockets/test_netplay.py b/backend/tests/endpoints/sockets/test_netplay.py new file mode 100644 index 000000000..216efa2d2 --- /dev/null +++ b/backend/tests/endpoints/sockets/test_netplay.py @@ -0,0 +1,551 @@ +"""Authorization for the netplay socket namespace.""" + +from typing import Any +from unittest.mock import AsyncMock, Mock + +import pytest + +from endpoints.netplay import DEFAULT_MAX_PLAYERS +from endpoints.sockets import netplay as netplay_module +from endpoints.sockets.netplay import ( + AUTH_USER_SESSION_KEY, + RoomData, + RoomDataExtra, + connect, + data_message, + disconnect, + join_room, + leave_room, + open_room, + webrtc_signal, +) +from handler.auth.constants import Scope +from handler.netplay_handler import NetplayPlayerInfo, NetplayRoom + +ROM_ID = 42 +PLATFORM_ID = 7 +VISIBLE_ROM = Mock(id=ROM_ID, platform_id=PLATFORM_ID) +ROOM_1 = netplay_module._socket_room("room-1") + + +def _user(*scopes: Scope) -> Mock: + user = Mock() + user.id = 1 + user.enabled = True + user.oauth_scopes = list(scopes) + return user + + +def _player(socket_id: str, name: str, player_id: str) -> NetplayPlayerInfo: + return NetplayPlayerInfo( + socketId=socket_id, + player_name=name, + userid=player_id, + playerId=player_id, + ) + + +def _room( + *, + password: str | None = None, + players: dict[str, NetplayPlayerInfo] | None = None, +) -> NetplayRoom: + return NetplayRoom( + owner="sid-owner", + players=players + or { + "owner": _player("sid-owner", "Owner", "owner"), + "me": _player("sid", "Me", "me"), + }, + peers=[], + room_name="Room", + game_id=str(ROM_ID), + domain=None, + password=password, + max_players=4, + ) + + +@pytest.fixture +def server(mocker) -> Mock: + """The netplay socket server, with the session store stubbed per socket.""" + sessions: dict[str, dict[str, Any]] = {} + + async def get_session(sid: str) -> dict[str, Any]: + if sid not in sessions: + raise KeyError(sid) + return sessions[sid] + + async def save_session(sid: str, session: dict[str, Any]) -> None: + sessions[sid] = session + + socket_server = netplay_module.netplay_socket_handler.socket_server + mocker.patch.object( + socket_server, "get_session", AsyncMock(side_effect=get_session) + ) + mocker.patch.object( + socket_server, "save_session", AsyncMock(side_effect=save_session) + ) + enter_room = mocker.patch.object(socket_server, "enter_room", AsyncMock()) + leave_room_event = mocker.patch.object(socket_server, "leave_room", AsyncMock()) + emit = mocker.patch.object(socket_server, "emit", AsyncMock()) + return Mock( + sessions=sessions, + enter_room=enter_room, + leave_room=leave_room_event, + emit=emit, + ) + + +@pytest.fixture +def rooms(mocker) -> Mock: + """The room store, plus the ROM and permission lookups the gate uses.""" + store: dict[str, NetplayRoom] = {} + handler = mocker.patch.object(netplay_module, "netplay_handler") + + async def get(session_id: str) -> NetplayRoom | None: + return store.get(session_id) + + async def set_(session_id: str, room: NetplayRoom) -> None: + store[session_id] = room + + handler.get = AsyncMock(side_effect=get) + handler.set = AsyncMock(side_effect=set_) + handler.delete = AsyncMock() + + mocker.patch.object( + netplay_module.db_rom_handler, "get_rom_visibility", return_value=VISIBLE_ROM + ) + permissions = mocker.patch.object(netplay_module, "resolve_permissions") + permissions.return_value.can_see_rom = Mock(return_value=True) + return Mock(store=store, handler=handler, permissions=permissions) + + +def _open( + *, + game_id: str | None = str(ROM_ID), + session_id: str = "room-1", + password: str | None = None, +) -> RoomData: + extra = RoomDataExtra(sessionid=session_id, userid="me", playerId=None) + if game_id is not None: + extra["game_id"] = game_id + data = RoomData(extra=extra) + if password is not None: + data["password"] = password + return data + + +def _join(*, password: str | None = None, player_id: str = "guest") -> RoomData: + extra = RoomDataExtra(sessionid="room-1", userid=player_id, playerId=None) + data = RoomData(extra=extra) + if password is not None: + data["password"] = password + return data + + +@pytest.fixture +def authorized(mocker) -> None: + mocker.patch.object( + netplay_module, + "_authenticated_user", + AsyncMock(return_value=_user(Scope.ROMS_READ)), + ) + + +class TestOpenRoomAuthorization: + async def test_rejects_unauthenticated(self, mocker, server, rooms): + mocker.patch.object( + netplay_module, "_authenticated_user", AsyncMock(return_value=None) + ) + + result = await open_room("sid", _open()) + + assert "Not authorized" in result + rooms.handler.set.assert_not_awaited() + server.enter_room.assert_not_awaited() + + async def test_rejects_missing_roms_read(self, mocker, server, rooms): + mocker.patch.object( + netplay_module, + "_authenticated_user", + AsyncMock(return_value=_user(Scope.ASSETS_READ)), + ) + + result = await open_room("sid", _open()) + + assert "Not authorized" in result + rooms.handler.set.assert_not_awaited() + + async def test_rejects_a_user_disabled_after_connecting( + self, mocker, server, rooms + ): + """The identity is reloaded per call, so a disable lands without a reconnect.""" + disabled = _user(Scope.ROMS_READ) + disabled.enabled = False + mocker.patch.object( + netplay_module.db_user_handler, "get_user", return_value=disabled + ) + server.sessions["sid"] = {AUTH_USER_SESSION_KEY: 1} + + result = await open_room("sid", _open()) + + assert "Not authorized" in result + rooms.handler.set.assert_not_awaited() + + async def test_rejects_hidden_rom(self, mocker, server, rooms): + mocker.patch.object( + netplay_module, + "_authenticated_user", + AsyncMock(return_value=_user(Scope.ROMS_READ)), + ) + rooms.permissions.return_value.can_see_rom = Mock(return_value=False) + + result = await open_room("sid", _open()) + + assert "Not authorized" in result + rooms.handler.set.assert_not_awaited() + + async def test_rejects_unknown_rom(self, mocker, server, rooms): + mocker.patch.object( + netplay_module, + "_authenticated_user", + AsyncMock(return_value=_user(Scope.ROMS_READ)), + ) + mocker.patch.object( + netplay_module.db_rom_handler, "get_rom_visibility", return_value=None + ) + + result = await open_room("sid", _open()) + + assert "Not authorized" in result + rooms.handler.set.assert_not_awaited() + + async def test_rejects_missing_game_id(self, mocker, server, rooms): + mocker.patch.object( + netplay_module, + "_authenticated_user", + AsyncMock(return_value=_user(Scope.ROMS_READ)), + ) + + result = await open_room("sid", _open(game_id=None)) + + assert "Not authorized" in result + rooms.handler.set.assert_not_awaited() + + async def test_allows_visible_rom(self, mocker, server, rooms): + mocker.patch.object( + netplay_module, + "_authenticated_user", + AsyncMock(return_value=_user(Scope.ROMS_READ)), + ) + + assert await open_room("sid", _open()) is None + + assert "room-1" in rooms.store + server.enter_room.assert_awaited_once_with("sid", ROOM_1) + server.emit.assert_awaited_once() + + async def test_keeps_the_connect_identity_in_the_room_session( + self, mocker, server, rooms + ): + """The room keys and the connect-time identity share one session dict.""" + mocker.patch.object( + netplay_module, + "_authenticated_user", + AsyncMock(return_value=_user(Scope.ROMS_READ)), + ) + server.sessions["sid"] = {AUTH_USER_SESSION_KEY: 1} + + await open_room("sid", _open()) + + assert server.sessions["sid"][AUTH_USER_SESSION_KEY] == 1 + assert server.sessions["sid"]["session_id"] == "room-1" + + +class TestJoinRoomAuthorization: + async def test_rejects_guest_without_a_password(self, mocker, server, rooms): + rooms.store["room-1"] = _room() + mocker.patch.object( + netplay_module, "_authenticated_user", AsyncMock(return_value=None) + ) + + result = await join_room("sid", _join()) + + assert "Not authorized" in result + server.enter_room.assert_not_awaited() + + async def test_rejects_guest_with_the_wrong_password(self, mocker, server, rooms): + rooms.store["room-1"] = _room(password="s3cret") + mocker.patch.object( + netplay_module, "_authenticated_user", AsyncMock(return_value=None) + ) + + result = await join_room("sid", _join(password="guess")) + + assert result == "Incorrect password" + server.enter_room.assert_not_awaited() + + async def test_allows_guest_with_the_correct_password(self, mocker, server, rooms): + rooms.store["room-1"] = _room(password="s3cret") + mocker.patch.object( + netplay_module, "_authenticated_user", AsyncMock(return_value=None) + ) + + assert await join_room("sid", _join(password="s3cret")) is not None + + server.enter_room.assert_awaited_once_with("sid", ROOM_1) + + async def test_rejects_user_who_cannot_see_the_rom(self, mocker, server, rooms): + rooms.store["room-1"] = _room() + rooms.permissions.return_value.can_see_rom = Mock(return_value=False) + mocker.patch.object( + netplay_module, + "_authenticated_user", + AsyncMock(return_value=_user(Scope.ROMS_READ)), + ) + + result = await join_room("sid", _join()) + + assert "Not authorized" in result + server.enter_room.assert_not_awaited() + + async def test_allows_a_password_invite_for_a_hidden_rom( + self, mocker, server, rooms + ): + """The room password is the owner's invite and stands in for the ROM gate.""" + rooms.store["room-1"] = _room(password="s3cret") + rooms.permissions.return_value.can_see_rom = Mock(return_value=False) + mocker.patch.object( + netplay_module, + "_authenticated_user", + AsyncMock(return_value=_user()), + ) + + assert await join_room("sid", _join(password="s3cret")) is not None + + server.enter_room.assert_awaited_once_with("sid", ROOM_1) + + async def test_allows_user_who_can_see_the_rom(self, mocker, server, rooms): + rooms.store["room-1"] = _room() + mocker.patch.object( + netplay_module, + "_authenticated_user", + AsyncMock(return_value=_user(Scope.ROMS_READ)), + ) + + joined = await join_room("sid", _join()) + + assert joined is not None + server.enter_room.assert_awaited_once_with("sid", ROOM_1) + + +class TestWebRtcSignalRelay: + async def test_drops_a_signal_to_a_non_peer(self, mocker, server, rooms): + rooms.store["room-1"] = _room() + server.sessions["sid"] = {"session_id": "room-1"} + + await webrtc_signal("sid", {"target": "sid-stranger", "offer": {"sdp": "x"}}) + + server.emit.assert_not_awaited() + + async def test_relays_a_signal_to_a_peer(self, mocker, server, rooms): + rooms.store["room-1"] = _room() + rooms.store["room-1"]["players"]["guest"] = NetplayPlayerInfo( + socketId="sid-peer", + player_name="Guest", + userid=None, + playerId="guest", + ) + server.sessions["sid"] = {"session_id": "room-1"} + + await webrtc_signal("sid", {"target": "sid-peer", "offer": {"sdp": "x"}}) + + server.emit.assert_awaited_once() + await_args = server.emit.await_args + assert await_args is not None + assert await_args.kwargs["to"] == "sid-peer" + + async def test_drops_a_signal_from_a_socket_with_no_room( + self, mocker, server, rooms + ): + rooms.store["room-1"] = _room() + + await webrtc_signal("sid", {"target": "sid-owner", "offer": {"sdp": "x"}}) + + server.emit.assert_not_awaited() + + async def test_drops_a_signal_from_a_socket_that_is_not_a_player( + self, mocker, server, rooms + ): + """A room id in the session is not enough; the sender must still be a player.""" + rooms.store["room-1"] = _room( + players={"owner": _player("sid-owner", "Owner", "owner")} + ) + server.sessions["sid"] = {"session_id": "room-1"} + + await webrtc_signal("sid", {"target": "sid-owner", "offer": {"sdp": "x"}}) + + server.emit.assert_not_awaited() + + +class TestLeaveRoom: + async def test_clears_the_room_session_keys(self, server, rooms): + rooms.store["room-1"] = _room() + server.sessions["sid"] = {"session_id": "room-1", "player_id": "me"} + + await leave_room("sid") + + assert "session_id" not in server.sessions["sid"] + assert "player_id" not in server.sessions["sid"] + + async def test_stops_broadcasting_after_leaving(self, server, rooms): + rooms.store["room-1"] = _room() + server.sessions["sid"] = {"session_id": "room-1", "player_id": "me"} + + await leave_room("sid") + server.emit.reset_mock() + + await data_message("sid", {"frame": 1}) + + server.emit.assert_not_awaited() + + +class TestRoomPassword: + """EmulatorJS sends the password beside ``extra``, not inside it.""" + + async def test_open_room_stores_the_password(self, server, rooms, authorized): + await open_room("sid", _open(password="s3cret")) + + assert rooms.store["room-1"]["password"] == "s3cret" + + async def test_join_accepts_the_password(self, mocker, server, rooms): + rooms.store["room-1"] = _room(password="s3cret") + mocker.patch.object( + netplay_module, "_authenticated_user", AsyncMock(return_value=None) + ) + + assert await join_room("sid", _join(password="s3cret")) is not None + + server.enter_room.assert_awaited_once_with("sid", ROOM_1) + + async def test_join_without_the_password_is_refused_even_with_rom_access( + self, server, rooms, authorized + ): + rooms.store["room-1"] = _room(password="s3cret") + + assert await join_room("sid", _join()) == "Incorrect password" + + server.enter_room.assert_not_awaited() + + +class TestRoomIsolation: + async def test_a_room_id_cannot_name_another_sockets_own_room( + self, server, rooms, authorized + ): + await open_room("sid", _open(session_id="sid-victim")) + + server.enter_room.assert_awaited_once_with( + "sid", netplay_module._socket_room("sid-victim") + ) + + async def test_join_refuses_a_player_id_already_seated( + self, server, rooms, authorized + ): + rooms.store["room-1"] = _room() + + assert await join_room("sid-2", _join(player_id="owner")) == ( + "Player already in room" + ) + + assert rooms.store["room-1"]["players"]["owner"]["socketId"] == "sid-owner" + server.enter_room.assert_not_awaited() + + async def test_joining_another_room_leaves_the_current_one( + self, server, rooms, authorized + ): + rooms.store["room-0"] = _room() + rooms.store["room-1"] = _room( + players={"owner": _player("sid-owner", "Owner", "owner")} + ) + server.sessions["sid"] = {"session_id": "room-0", "player_id": "me"} + + assert await join_room("sid", _join()) is not None + + assert "me" not in rooms.store["room-0"]["players"] + server.leave_room.assert_awaited_once_with( + "sid", netplay_module._socket_room("room-0") + ) + + async def test_a_malformed_max_players_falls_back_to_the_default( + self, server, rooms, authorized + ): + data: Any = _open() + data["maxPlayers"] = "lots" + + await open_room("sid", data) + + assert rooms.store["room-1"]["max_players"] == DEFAULT_MAX_PLAYERS + + async def test_stores_the_rom_id_the_gate_resolved(self, server, rooms, authorized): + await open_room("sid", _open(game_id=f" {ROM_ID}")) + + assert rooms.store["room-1"]["game_id"] == str(ROM_ID) + + +class TestLoginSessionBinding: + """Revoking a login session must close the netplay sockets it opened.""" + + async def test_disconnect_forgets_the_binding(self, mocker, server, rooms): + unbind = mocker.patch.object( + netplay_module.netplay_socket_handler, + "unbind_from_login_session", + AsyncMock(), + ) + + await disconnect("sid") + + unbind.assert_awaited_once_with("sid") + + +class TestEventWiring: + """The gates only hold if they are attached to the netplay server, not `/ws`.""" + + def test_handlers_are_registered_on_the_netplay_server(self): + handlers = netplay_module.netplay_socket_handler.socket_server.handlers["/"] + + assert handlers["connect"] is connect + assert handlers["disconnect"] is disconnect + for event in ("open-room", "join-room", "webrtc-signal"): + assert event in handlers + + +class TestConnectIdentity: + @pytest.fixture + def authenticate(self, mocker) -> AsyncMock: + return mocker.patch.object( + netplay_module.netplay_socket_handler, "authenticate", AsyncMock() + ) + + async def test_stores_identity_for_an_authenticated_session( + self, server, authenticate + ): + user = _user(Scope.ROMS_READ) + authenticate.return_value = user + + await connect("sid", {"HTTP_COOKIE": "c"}) + + authenticate.assert_awaited_once_with("sid", {"HTTP_COOKIE": "c"}) + assert server.sessions["sid"][AUTH_USER_SESSION_KEY] == user.id + + async def test_leaves_an_anonymous_socket_unidentified(self, server, authenticate): + authenticate.return_value = None + + await connect("sid", {}) + + assert AUTH_USER_SESSION_KEY not in server.sessions.get("sid", {}) + + async def test_never_refuses_the_connection(self, server, authenticate): + authenticate.side_effect = RuntimeError("redis down") + + assert await connect("sid", {}) is None diff --git a/backend/tests/endpoints/sockets/test_socket_connect.py b/backend/tests/endpoints/sockets/test_socket_connect.py index 8397ad432..67ca05f78 100644 --- a/backend/tests/endpoints/sockets/test_socket_connect.py +++ b/backend/tests/endpoints/sockets/test_socket_connect.py @@ -3,14 +3,16 @@ from unittest.mock import AsyncMock, MagicMock import pytest from endpoints.sockets import logs +from handler.database import db_user_handler from handler.socket_handler import socket_handler from models.user import Role +from utils import auth as auth_utils @pytest.fixture def user(mocker): user = MagicMock(id=3, enabled=True, role=Role.USER) - mocker.patch.object(logs.db_user_handler, "get_user_by_username", return_value=user) + mocker.patch.object(db_user_handler, "get_user_by_username", return_value=user) return user @@ -27,7 +29,7 @@ def bind(mocker): def _session(mocker, **session): mocker.patch.object( - logs, "get_session_from_environ", AsyncMock(return_value=session) + auth_utils, "get_session_from_environ", AsyncMock(return_value=session) ) diff --git a/backend/tests/endpoints/test_assets.py b/backend/tests/endpoints/test_assets.py index 311ea3dc5..cabf257ff 100644 --- a/backend/tests/endpoints/test_assets.py +++ b/backend/tests/endpoints/test_assets.py @@ -1,7 +1,14 @@ +from unittest import mock + from fastapi import status from fastapi.testclient import TestClient -from handler.database import db_save_handler, db_screenshot_handler, db_state_handler +from handler.database import ( + db_deleted_asset_handler, + db_save_handler, + db_screenshot_handler, + db_state_handler, +) from models.assets import Save, Screenshot, State from models.platform import Platform from models.rom import Rom @@ -19,6 +26,37 @@ def test_delete_saves(client, access_token, save): body = response.json() assert len(body) == 1 + # No hash and no file to take one from, so nothing a device could match. + assert ( + db_deleted_asset_handler.get_deletions( + user_id=save.user_id, rom_ids=[save.rom_id] + ) + == [] + ) + + +def test_delete_saves_hashes_a_save_that_never_recorded_one( + client, access_token, save: Save +): + assert save.content_hash is None + + with mock.patch( + "endpoints.saves.fs_asset_handler.compute_content_hash", + new=mock.AsyncMock(return_value="deadbeef"), + ) as compute_content_hash: + response = client.post( + "/api/saves/delete", + headers={"Authorization": f"Bearer {access_token}"}, + json={"saves": [save.id]}, + ) + + assert response.status_code == status.HTTP_200_OK + compute_content_hash.assert_awaited_once_with(save.full_path) + [record] = db_deleted_asset_handler.get_deletions( + user_id=save.user_id, rom_ids=[save.rom_id] + ) + assert record.content_hashes == ["deadbeef"] + def test_delete_states(client, access_token, state): response = client.post( diff --git a/backend/tests/endpoints/test_cors.py b/backend/tests/endpoints/test_cors.py new file mode 100644 index 000000000..f3ade9847 --- /dev/null +++ b/backend/tests/endpoints/test_cors.py @@ -0,0 +1,88 @@ +"""Guards the cross-origin defaults the API is served with.""" + +from collections.abc import Sequence +from typing import Any + +import pytest +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from fastapi.testclient import TestClient +from main import app +from starlette.middleware import Middleware + +from config import cors_allow_credentials + +FOREIGN_ORIGIN = "https://evil.example" +LISTED_ORIGIN = "https://romm.example" + + +def _cors_middleware() -> Middleware: + return next(m for m in app.user_middleware if m.cls is CORSMiddleware) + + +def _scratch_app(**kwargs: Any) -> TestClient: + scratch = FastAPI() + scratch.add_middleware(CORSMiddleware, **kwargs) + + @scratch.get("/ping") + async def ping() -> dict[str, bool]: + return {"ok": True} + + return TestClient(scratch) + + +def test_a_wildcard_origin_is_never_paired_with_credentials() -> None: + cors = _cors_middleware() + origins = cors.kwargs["allow_origins"] + assert isinstance(origins, Sequence) + assert not (cors.kwargs["allow_credentials"] and "*" in origins), ( + "Starlette answers a wildcard with the caller's own Origin and " + "Access-Control-Allow-Credentials, granting every site credentialed access" + ) + + +def test_a_foreign_origin_gets_no_cors_grant(client: TestClient) -> None: + response = client.get("/api/heartbeat", headers={"Origin": FOREIGN_ORIGIN}) + + assert response.status_code == 200 + # Starlette ships the credentials header either way; with no Allow-Origin to + # pair it with, the browser drops the response. + assert "access-control-allow-origin" not in response.headers + + +def test_a_listed_origin_is_granted_with_credentials() -> None: + """Listing an origin is what turns cross-origin access on, credentials included.""" + client = _scratch_app( + **{**_cors_middleware().kwargs, "allow_origins": [LISTED_ORIGIN]} + ) + + response = client.get("/ping", headers={"Origin": LISTED_ORIGIN}) + + assert response.headers["access-control-allow-origin"] == LISTED_ORIGIN + assert response.headers["access-control-allow-credentials"] == "true" + + +def test_an_explicit_wildcard_is_served_without_credentials() -> None: + """An operator-set `*` stays open, but is not paired with the session cookie.""" + client = _scratch_app( + allow_origins=["*"], + allow_credentials=cors_allow_credentials(["*"]), + ) + + response = client.get("/ping", headers={"Origin": FOREIGN_ORIGIN}) + + assert response.headers["access-control-allow-origin"] == "*" + assert "access-control-allow-credentials" not in response.headers + + +@pytest.mark.parametrize( + ("origins", "expected"), + [ + (["*"], False), + ([], True), + ([LISTED_ORIGIN], True), + (["*", LISTED_ORIGIN], False), + ], +) +def test_credentials_follow_the_wildcard(origins: list[str], expected: bool) -> None: + assert cors_allow_credentials(origins) is expected diff --git a/backend/tests/endpoints/test_memory_cards.py b/backend/tests/endpoints/test_memory_cards.py index efc7b1ca2..8db82bb7d 100644 --- a/backend/tests/endpoints/test_memory_cards.py +++ b/backend/tests/endpoints/test_memory_cards.py @@ -216,9 +216,9 @@ def test_version_listing_flags_an_archive_that_is_gone( ) assert response.status_code == status.HTTP_200_OK assert response.json()[0]["missing_from_fs"] is True - assert db_memory_card_handler.get_version_by_id( - memory_card_version.id - ).missing_from_fs + version = db_memory_card_handler.get_version_by_id(memory_card_version.id) + assert version is not None + assert version.missing_from_fs @mock.patch("endpoints.memory_cards.fs_asset_handler.validate_path") @@ -240,9 +240,9 @@ def test_version_listing_clears_the_flag_when_the_archive_is_back( ) assert response.status_code == status.HTTP_200_OK assert response.json()[0]["missing_from_fs"] is False - assert not db_memory_card_handler.get_version_by_id( - memory_card_version.id - ).missing_from_fs + version = db_memory_card_handler.get_version_by_id(memory_card_version.id) + assert version is not None + assert not version.missing_from_fs @mock.patch("endpoints.memory_cards.fs_asset_handler.validate_path") @@ -450,9 +450,9 @@ def test_upload_memory_card_version(client, access_token: str, memory_card: Memo assert response.status_code == status.HTTP_200_OK assert response.json()["content_hash"] == "uploaded" write_file.assert_awaited_once() - assert db_memory_card_handler.get_latest_version(memory_card.id).id == ( - response.json()["id"] - ) + latest = db_memory_card_handler.get_latest_version(memory_card.id) + assert latest is not None + assert latest.id == response.json()["id"] def test_upload_of_already_stored_content_still_becomes_newest( @@ -840,9 +840,9 @@ async def test_version_filename_steps_around_an_occupied_name( written = write_file.await_args.kwargs["filename"] if write_file.await_args else "" assert "(2)" in written - assert ( - db_memory_card_handler.get_latest_version(memory_card.id).file_name == written - ) + latest = db_memory_card_handler.get_latest_version(memory_card.id) + assert latest is not None + assert latest.file_name == written async def test_a_failed_scan_leaves_no_archive_behind( diff --git a/backend/tests/endpoints/test_music.py b/backend/tests/endpoints/test_music.py index 23ec18f60..89ecf9026 100644 --- a/backend/tests/endpoints/test_music.py +++ b/backend/tests/endpoints/test_music.py @@ -327,6 +327,29 @@ def test_facet_years_typeahead(client: TestClient, access_token: str, music_libr assert {i["value"] for i in body["items"]} == {1991, 1992} +@pytest.mark.parametrize( + "path", ["/api/roms", "/api/music/tracks", "/api/music/artists"] +) +@pytest.mark.parametrize("query", ["limit=0", "limit=10001", "offset=-1"]) +def test_page_params_out_of_bounds_422( + client: TestClient, access_token: str, path: str, query: str +): + response = client.get(f"{path}?{query}", headers=_auth(access_token)) + assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT + + +def test_facet_page_applies_limit_and_offset( + client: TestClient, access_token: str, music_library +): + url = "/api/music/artists?order_by=value&order_dir=asc" + everything = client.get(url, headers=_auth(access_token)).json() + page = client.get(f"{url}&limit=1&offset=1", headers=_auth(access_token)).json() + + assert (page["limit"], page["offset"]) == (1, 1) + assert page["total"] == everything["total"] + assert page["items"] == everything["items"][1:2] + + # ---------- visibility (handler level) ---------- diff --git a/backend/tests/endpoints/test_music_playlists.py b/backend/tests/endpoints/test_music_playlists.py index b6e0c9fac..e5700e159 100644 --- a/backend/tests/endpoints/test_music_playlists.py +++ b/backend/tests/endpoints/test_music_playlists.py @@ -196,6 +196,22 @@ def test_playlist_tracks_ordered_and_deduped( assert body[0]["track_count"] == 3 +def test_playlist_tracks_apply_limit_and_offset( + client: TestClient, access_token: str, playlist_id: int +): + _add_tracks( + client, access_token, playlist_id, ["Jingle", "Green Hill", "Overworld"] + ) + + body = client.get( + f"/api/music/playlists/{playlist_id}/tracks?limit=1&offset=1", + headers=_auth(access_token), + ).json() + + assert (body["limit"], body["offset"], body["total"]) == (1, 1, 3) + assert [i["title"] for i in body["items"]] == ["Green Hill"] + + def test_playlist_reorder(client: TestClient, access_token: str, playlist_id: int): ids = _add_tracks( client, access_token, playlist_id, ["Jingle", "Green Hill", "Overworld"] diff --git a/backend/tests/endpoints/test_netplay.py b/backend/tests/endpoints/test_netplay.py new file mode 100644 index 000000000..4bb9971bb --- /dev/null +++ b/backend/tests/endpoints/test_netplay.py @@ -0,0 +1,96 @@ +"""The netplay room listing must not reveal rooms for a hidden rom.""" + +from datetime import timedelta +from unittest.mock import AsyncMock, Mock + +import pytest + +from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS +from endpoints import netplay as netplay_endpoints +from handler.auth import oauth_handler +from handler.auth.constants import Scope +from handler.database.base_handler import sync_session +from handler.netplay_handler import NetplayPlayerInfo, NetplayRoom +from models.permission import HiddenEntity, PermEntity +from models.user import User + + +def _auth(user: User, scopes: list[Scope] | None = None) -> dict[str, str]: + # Re-reads the user's current (projected) scopes each call. + token = oauth_handler.create_access_token( + data={ + "sub": user.username, + "iss": "romm:oauth", + "scopes": " ".join(scopes if scopes is not None else user.oauth_scopes), + }, + expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS), + ) + return {"Authorization": f"Bearer {token}"} + + +def _hide(entity: PermEntity, entity_id: int, user_id: int) -> None: + with sync_session.begin() as s: + s.add(HiddenEntity(entity=entity, entity_id=entity_id, user_id=user_id)) + + +def _room(rom_id: int) -> NetplayRoom: + return NetplayRoom( + owner="sid", + players={ + "p": NetplayPlayerInfo( + socketId="sid", + player_name="Player p", + userid=None, + playerId="p", + ) + }, + peers=[], + room_name="Room", + game_id=str(rom_id), + domain=None, + password=None, + max_players=4, + ) + + +@pytest.fixture +def rooms(mocker) -> Mock: + return mocker.patch.object( + netplay_endpoints.netplay_handler, "get_all", AsyncMock(return_value={}) + ) + + +def test_listing_shows_rooms_for_a_visible_rom(client, viewer_user, rom, rooms): + rooms.return_value = {"room-1": _room(rom.id)} + + resp = client.get(f"/api/netplay/list?game_id={rom.id}", headers=_auth(viewer_user)) + + assert resp.status_code == 200 + assert "room-1" in resp.json() + + +def test_listing_hides_rooms_for_a_hidden_rom(client, viewer_user, rom, rooms): + _hide(PermEntity.ROMS, rom.id, viewer_user.id) + rooms.return_value = {"room-1": _room(rom.id)} + + resp = client.get(f"/api/netplay/list?game_id={rom.id}", headers=_auth(viewer_user)) + + assert resp.status_code == 404 + rooms.assert_not_awaited() + + +def test_listing_of_a_missing_rom_is_not_found(client, viewer_user, rooms): + resp = client.get("/api/netplay/list?game_id=999999", headers=_auth(viewer_user)) + + assert resp.status_code == 404 + rooms.assert_not_awaited() + + +def test_listing_needs_the_rom_read_scope(client, viewer_user, rooms): + """The listing answers about a rom, so asset access alone is not enough.""" + headers = _auth(viewer_user, scopes=[Scope.ASSETS_READ]) + + resp = client.get("/api/netplay/list?game_id=1", headers=headers) + + assert resp.status_code == 403 + rooms.assert_not_awaited() diff --git a/backend/tests/endpoints/test_notification_channels.py b/backend/tests/endpoints/test_notification_channels.py index 1927c7735..5562521db 100644 --- a/backend/tests/endpoints/test_notification_channels.py +++ b/backend/tests/endpoints/test_notification_channels.py @@ -23,6 +23,18 @@ def _webhook(url: str = "https://hooks.example.com/romm/token", **fields) -> dic return {"type": "webhook", "name": "Hook", "url": url, **fields} +_DISCORD = {"webhook_id": "1234567890", "webhook_token": "abcdefghijklmnop"} + + +def _apprise(service: str = "discord", **fields) -> dict: + return { + "type": "apprise", + "name": "Discord", + "service": service, + "fields": fields or _DISCORD, + } + + @pytest.fixture def emailed(mocker): mocker.patch.object(channels, "EMAIL_ENABLED", True) @@ -37,7 +49,7 @@ def sent(mocker): class TestCreate: def test_a_webhook_hides_its_token(self, client, access_token): response = client.post( - API, json=_webhook(secret="k", format="json"), headers=_auth(access_token) + API, json=_webhook(secret="k"), headers=_auth(access_token) ) assert response.status_code == status.HTTP_201_CREATED @@ -64,6 +76,38 @@ class TestCreate: assert response.status_code == status.HTTP_400_BAD_REQUEST + def test_an_admin_forwards_through_apprise(self, client, access_token): + response = client.post( + API, json=_apprise(**_DISCORD, botname="RomM"), headers=_auth(access_token) + ) + + assert response.status_code == status.HTTP_201_CREATED + body = response.json() + assert (body["type"], body["service"], body["service_name"]) == ( + "apprise", + "discord", + "Discord", + ) + assert body["target"] == "discord://RomM@1...0/a...p/" + assert body["fields"] == {"botname": "RomM"} + assert body["stored_secrets"] == ["webhook_id", "webhook_token"] + assert "abcdefghijklmnop" not in response.text + + def test_a_user_may_not_use_apprise(self, client, viewer_access_token): + response = client.post(API, json=_apprise(), headers=_auth(viewer_access_token)) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert response.json()["detail"] == "Only admins can use Apprise channels" + + @pytest.mark.parametrize( + "payload", + [_apprise("syslog", host="localhost"), _apprise(webhook_id="1234567890")], + ) + def test_fields_apprise_cannot_use_are_refused(self, client, access_token, payload): + response = client.post(API, json=payload, headers=_auth(access_token)) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + def test_a_user_has_at_most_so_many(self, client, access_token): for n in range(MAX_NOTIFICATION_CHANNELS_PER_USER): created = client.post( @@ -83,6 +127,7 @@ class TestCreate: [ {"type": "sms", "name": "x", "url": "https://example.com"}, {"type": "email", "name": "x", "address": "not-an-address"}, + {"type": "apprise", "name": "x", "service": "discord"}, _webhook(topics=["everything"]), _webhook(name=""), ], @@ -118,6 +163,55 @@ class TestCreate: assert db_notification_channel_handler.get_channels(admin_user.id) == [] +class TestAppriseServices: + def test_an_admin_gets_each_service_with_its_fields(self, client, access_token): + response = client.get(f"{API}/apprise-services", headers=_auth(access_token)) + + assert response.status_code == status.HTTP_200_OK + discord = next(s for s in response.json() if s["id"] == "discord") + token = next(f for f in discord["fields"] if f["key"] == "webhook_token") + assert discord["name"] == "Discord" + assert (token["required"], token["private"], token["advanced"]) == ( + True, + True, + False, + ) + + def test_an_admin_pastes_a_discord_webhook(self, client, access_token): + response = client.post( + f"{API}/apprise-services/parse", + json={ + "url": "https://discord.com/api/webhooks/1234567890/abcdefghijklmnop" + }, + headers=_auth(access_token), + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json() == {"service": "discord", "fields": _DISCORD} + + def test_a_url_it_cant_read_is_refused(self, client, access_token): + response = client.post( + f"{API}/apprise-services/parse", + json={"url": "nowhere://romm"}, + headers=_auth(access_token), + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + + def test_a_user_gets_none(self, client, viewer_access_token): + listed = client.get( + f"{API}/apprise-services", headers=_auth(viewer_access_token) + ) + parsed = client.post( + f"{API}/apprise-services/parse", + json={"url": "ntfys://ntfy.sh/romm"}, + headers=_auth(viewer_access_token), + ) + + assert listed.status_code == status.HTTP_403_FORBIDDEN + assert parsed.status_code == status.HTTP_403_FORBIDDEN + + class TestEmailConfirmation: def test_the_emailed_code_confirms_the_address(self, client, access_token, emailed): created = client.post( @@ -215,6 +309,22 @@ class TestUpdate: assert body["has_secret"] is False assert body["enabled"] is False + def test_apprise_secrets_stay_until_given_again(self, client, access_token): + created = client.post(API, json=_apprise(), headers=_auth(access_token)).json() + path = f"{API}/{created['id']}" + + renamed = client.patch( + path, json={"name": "Phone"}, headers=_auth(access_token) + ) + retitled = client.patch( + path, + json={"fields": {"webhook_id": "1234567890", "botname": "Bot"}}, + headers=_auth(access_token), + ) + + assert renamed.json()["target"] == created["target"] + assert retitled.json()["target"] == "discord://Bot@1...0/a...p/" + def test_null_topics_forwards_everything_again(self, client, access_token): created = client.post( API, json=_webhook(topics=["scans"]), headers=_auth(access_token) diff --git a/backend/tests/endpoints/test_permissions_admin.py b/backend/tests/endpoints/test_permissions_admin.py index 53b318b97..bad031c6d 100644 --- a/backend/tests/endpoints/test_permissions_admin.py +++ b/backend/tests/endpoints/test_permissions_admin.py @@ -7,6 +7,7 @@ from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS from handler.auth import oauth_handler from handler.database import db_user_handler from handler.database.base_handler import sync_session +from handler.database.permissions_handler import DBPermissionsHandler from models.permission import PermissionGroup @@ -17,6 +18,7 @@ def _bearer(token): def _fresh_user_auth(user_id): # Mint a token from the user's CURRENT (post-change) projected scopes. user = db_user_handler.get_user(user_id) + assert user is not None return _bearer( oauth_handler.create_access_token( data={ @@ -170,6 +172,25 @@ def test_cannot_delete_default_group(client, access_token): assert resp.status_code == 400 +def test_update_group_deleted_mid_update_returns_404(client, access_token, mocker): + try: + gid = client.post( + "/api/permissions/groups", + headers=_bearer(access_token), + json={"name": "Vanishing"}, + ).json()["id"] + mocker.patch.object(DBPermissionsHandler, "update_group", return_value=None) + + resp = client.put( + f"/api/permissions/groups/{gid}", + headers=_bearer(access_token), + json={"description": "renamed"}, + ) + assert resp.status_code == 404 + finally: + _cleanup() + + def test_delete_group_falls_members_back(client, access_token, viewer_user): gid = client.post( "/api/permissions/groups", @@ -189,6 +210,7 @@ def test_delete_group_falls_members_back(client, access_token, viewer_user): # FK SET NULL -> user falls back to the default (viewer) matrix. user = db_user_handler.get_user(viewer_user.id) + assert user is not None assert user.permission_group_id is None actions, _ = _me_actions(client, viewer_user.id) assert "collection.create" in actions # default viewer behaviour restored diff --git a/backend/tests/endpoints/test_permissions_visibility.py b/backend/tests/endpoints/test_permissions_visibility.py index 06d94103b..d8105c9f5 100644 --- a/backend/tests/endpoints/test_permissions_visibility.py +++ b/backend/tests/endpoints/test_permissions_visibility.py @@ -393,6 +393,7 @@ def test_delete_requires_delete_grant_even_with_write_scope( ) db_user_handler.update_user(viewer_user.id, {"permission_group_id": gid}) user = db_user_handler.get_user(viewer_user.id) + assert user is not None # Coarse PLATFORMS_WRITE is present (projected from the write grant), so the # request passes the scope gate and is rejected by the fine delete check. diff --git a/backend/tests/endpoints/test_play_sessions.py b/backend/tests/endpoints/test_play_sessions.py index 664e89cf1..e40db45f3 100644 --- a/backend/tests/endpoints/test_play_sessions.py +++ b/backend/tests/endpoints/test_play_sessions.py @@ -538,6 +538,8 @@ class TestPlaySessionRomUserUpdates: ) rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user is not None + assert rom_user.last_played is not None expected_latest = later + timedelta(minutes=30) last_played_utc = to_utc(rom_user.last_played) assert abs((last_played_utc - expected_latest).total_seconds()) < 2 @@ -566,6 +568,7 @@ class TestPlaySessionRomUserUpdates: ) rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user is not None assert rom_user.status == RomUserStatus.INCOMPLETE def test_finished_status_rewound_to_incomplete( @@ -580,6 +583,7 @@ class TestPlaySessionRomUserUpdates: ) rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user is not None assert rom_user.status == RomUserStatus.INCOMPLETE @pytest.mark.parametrize( @@ -602,6 +606,7 @@ class TestPlaySessionRomUserUpdates: ) rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user is not None # now_playing is orthogonal, so it still flips on... assert rom_user.now_playing is True # ...but the deliberate enum status is left untouched. @@ -617,6 +622,7 @@ class TestPlaySessionRomUserUpdates: headers={"Authorization": f"Bearer {access_token}"}, ) rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user is not None db_rom_handler.update_rom_user( rom_user.id, {"now_playing": False, "status": RomUserStatus.FINISHED} ) @@ -629,6 +635,7 @@ class TestPlaySessionRomUserUpdates: ) rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user is not None assert rom_user.now_playing is False assert rom_user.status == RomUserStatus.FINISHED diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 43b2cc849..650176208 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -16,9 +16,11 @@ import pytest from fastapi import HTTPException from fastapi.testclient import TestClient from main import app +from tests.streaming_stubs import exit_pulls_spawned_inline from config import LIBRARY_BASE_PATH, OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS from endpoints import streaming +from endpoints.responses.streaming import ImportRefusalSchema from endpoints.streaming import platform_capabilities from handler.activity_handler import activity_handler from handler.auth import oauth_handler @@ -40,6 +42,8 @@ from handler.streaming import ( access, broker, commands, + imports, + launch, lifecycle, memory_cards, saves, @@ -55,9 +59,11 @@ from handler.streaming.capabilities import ( from handler.streaming.config import ( ResolvedContainer, _derive_broker_host, + configured_emulator, emulator_display_label, pools_for_platform, reset_cache, + resolve_containers, resolve_entry, ) from handler.streaming.protocol import protocol_for @@ -65,7 +71,7 @@ from models.assets import MemoryCard, MemoryCardVersion, Save, Screenshot, State from models.notification import NotificationKind from models.permission import HiddenEntity, PermEntity from models.platform import Platform -from models.rom import Rom, RomFile +from models.rom import Rom, RomFile, SaveTargetLayout from models.user import User from utils.memory_cards import content_hash_of_bytes @@ -104,6 +110,19 @@ def clear_streaming_sessions(): yield +@pytest.fixture(autouse=True) +def clear_import_spec_cache(): + """The import-spec cache is process-wide, so one case's answer must not leak.""" + with patch.dict(webstation._import_spec_cache, clear=True): + yield + + +@pytest.fixture(autouse=True) +def exit_pull_queue(): + with exit_pulls_spawned_inline() as queue: + yield queue + + @pytest.fixture(autouse=True) def no_pull_backoff(monkeypatch): """The pull tests assert on how many attempts happen, not on the wait.""" @@ -329,6 +348,18 @@ def test_get_config_ships_platform_capabilities(client, access_token): } +def test_get_config_ships_the_emulator_labels(client, access_token): + """Saves and states are tagged with the emulator that wrote them, so the + display names ride along rather than being copied into the frontend.""" + with _streaming({"platform": "ps2", "host": "http://192.168.1.10:3000"}): + r = client.get("/api/streaming/config", headers=_auth(access_token)) + labels = r.json()["emulator_labels"] + assert labels["pcsx2"] == "PCSX2" + assert labels["play"] == "Play!" + # The id a save carries, with no platform to pick a core from. + assert labels["retroarch"] == "RetroArch" + + def test_get_config_ships_capabilities_for_a_retroarch_platform(client, access_token): """RetroArch serves dozens of platforms, none of them listed by name. Without a fallback they all reported no states and the player offered no save @@ -478,6 +509,47 @@ def test_get_config_reports_save_picker_support(client, access_token, rom: Rom): assert supported["gba"] is False +def test_get_config_reports_the_foreign_picks_each_broker_imports( + client, access_token, rom: Rom +): + """The picker only offers a foreign pick the claim would take, so a broker + that declares no imports, or cannot be asked, reports none.""" + importing = {**_webstation_for(rom), "emulator": "duckstation"} + silent = {**_webstation_for(rom), "platform": "ps2", "emulator": "pcsx2"} + spec = webstation.ImportSpec( + kinds=frozenset({"save", "state"}), state_channel="archive", state_slot=0 + ) + + def answer(container, _emulator, _platform): + return spec if container.platform == rom.platform_slug else None + + with _streaming(importing, silent): + with patch("handler.streaming.webstation.import_spec", side_effect=answer): + response = client.get("/api/streaming/config", headers=_auth(access_token)) + assert response.status_code == 200 + kinds = {c["platform"]: c["import_kinds"] for c in response.json()["containers"]} + assert kinds[rom.platform_slug] == ["save", "state"] + assert kinds["ps2"] == [] + + +@pytest.mark.parametrize( + ("kinds", "channel", "slot", "expected"), + [ + ({"save", "state"}, "archive", 0, ["save", "state"]), + ({"state"}, "none", 0, []), + ({"state"}, "push", None, []), + ({"save", "memcard"}, "none", None, ["save"]), + ], +) +def test_import_spec_pickable_kinds_match_what_the_claim_accepts( + kinds, channel, slot, expected +): + spec = webstation.ImportSpec( + kinds=frozenset(kinds), state_channel=channel, state_slot=slot + ) + assert spec.pickable_kinds() == expected + + def test_clears_stale_saves_overrides_the_emulator_default(client, access_token, rom): """The default mirrors a flag that lives in the broker's repo, so an operator on a fork or a newer broker can say what theirs actually does.""" @@ -547,6 +619,59 @@ def test_clears_stale_saves_has_no_picker_to_gate_on_a_legacy_container(caplog): assert "clears_stale_saves" in caplog.text +def test_only_a_webstation_exit_state_emulator_resumes_from_its_archive(): + """Only the webstation broker takes an archive to restore, so on any other + protocol the resume state still has to be pushed as a file.""" + base = { + "platform": "psx", + "host": "http://192.168.1.10:3000", + "broker_host": "http://192.168.1.10:8000", + } + webstation = {**base, "protocol": "webstation"} + assert _resolved({**webstation, "emulator": "duckstation"}).resumes_from_archive + assert _resolved({**webstation, "emulator": "rpcs3"}).resumes_from_archive + assert not _resolved({**webstation, "emulator": "pcsx2"}).resumes_from_archive + assert not _resolved({**base, "emulator": "duckstation"}).resumes_from_archive + + +def test_an_exit_state_emulator_offers_no_live_states(): + """DuckStation and RPCS3 brokers answer a mid-session save or load with a + 400, so the player must not offer one. psx is one platform entry whichever + emulator serves it, so RetroArch on psx keeps its controls.""" + webstation = { + "platform": "psx", + "host": "http://192.168.1.10:3000", + "broker_host": "http://192.168.1.10:8000", + "protocol": "webstation", + } + assert not _resolved({**webstation, "emulator": "duckstation"}).supports_live_states + assert not _resolved( + {**webstation, "platform": "ps3", "emulator": "rpcs3"} + ).supports_live_states + assert _resolved({**webstation, "emulator": "retroarch"}).supports_live_states + # No states at all is no live states either. + assert not _resolved( + {**webstation, "platform": "xbox", "emulator": "xemu"} + ).supports_live_states + + +def test_get_config_ships_whether_a_container_takes_live_states(client, access_token): + """The exit-state library still needs has_autosave, so the Save and Load + buttons read their own flag rather than switching the slot off.""" + container = { + "host": "http://box:3010", + "protocol": "webstation", + "platforms": {"psx": "duckstation", "gba": "retroarch"}, + } + with _streaming(container): + r = client.get("/api/streaming/config", headers=_auth(access_token)) + assert r.status_code == 200 + by_platform = {c["platform"]: c for c in r.json()["containers"]} + assert by_platform["psx"]["supports_live_states"] is False + assert by_platform["psx"]["capabilities"]["has_autosave"] is True + assert by_platform["gba"]["supports_live_states"] is True + + def test_a_container_that_disagrees_on_clearing_saves_is_a_pool_of_its_own(caplog): """The picker is advertised from the head of the pool, so a member that keeps its own newer files would take the pick and silently discard it.""" @@ -692,6 +817,47 @@ def test_get_config_offers_disc_swap_only_on_a_webstation_container( assert ws_caps["supports_disc_swap"] is True +def test_get_config_leaves_out_a_container_no_claim_can_reach(client, access_token): + """A host with no scheme resolves to no key, so every claim on it fails and + listing it would put a Play button on a platform that can never stream.""" + with _streaming({"platform": "ps2", "host": "192.168.1.10:3000"}): + response = client.get("/api/streaming/config", headers=_auth(access_token)) + assert response.status_code == 200 + assert response.json()["containers"] == [] + + +def test_get_config_lists_a_platform_once_whatever_the_case(client, access_token): + """Platforms are matched case-insensitively everywhere else, so two records + naming one platform in different case are one platform to every claim.""" + with _streaming( + {"platform": "PS2", "host": "http://box-a:3000"}, + {"platform": "ps2", "host": "http://box-b:3000"}, + ): + response = client.get("/api/streaming/config", headers=_auth(access_token)) + assert response.status_code == 200 + assert len(response.json()["containers"]) == 1 + + +def test_configured_emulator_names_the_container_a_claim_wins(client): + """Slot ceilings are read off this emulator, so it has to be the one on the + container a claim lands on, not the first record in the file.""" + with _streaming( + {"platform": "ps2", "host": "192.168.1.10:3000", "emulator": "retroarch"}, + { + "platform": "ps2", + "host": "http://box:3000", + "broker_host": "http://box:8000", + "emulator": "pcsx2", + }, + ): + assert configured_emulator("ps2") == "pcsx2" + + +def test_configured_emulator_is_empty_without_a_claimable_container(client): + with _streaming({"platform": "ps2", "host": "192.168.1.10:3000"}): + assert configured_emulator("ps2") == "" + + # ── Nested platform config ──────────────────────────────────────────────────── @@ -856,6 +1022,27 @@ def test_claim_derives_rom_path_server_side(client, access_token, rom: Rom): assert rom_path == f"{LIBRARY_BASE_PATH}/{rom.full_path}" +def test_a_slow_claim_setup_keeps_its_claim_fresh(client, access_token, rom: Rom): + """Nothing beats for the player until the stream is up, so a setup step + outlasting the stale window would hand the container to the reaper.""" + + async def slow_save_pull(*args: Any, **kwargs: Any) -> bool: + await asyncio.sleep(0.05) + return True + + with ( + _streaming(_container_for(rom)), + patch.object(session_store, "_CLAIM_REFRESH_SECONDS", 0), + patch("handler.streaming.saves.wait_for_save_pull", new=slow_save_pull), + patch("handler.streaming.launch.run_launch", new=AsyncMock()), + ): + r = _claim(client, access_token, rom.id) + + assert r.status_code == 202 + stored = _load_session(session_store.session_redis_key(r.json()["container"])) + assert stored["last_seen"] != r.json()["claimed_at"] + + def test_claim_honors_container_library_path(client, access_token, rom: Rom): """`library_path` on the container entry replaces LIBRARY_BASE_PATH so the broker gets a path valid inside a container with a different mount.""" @@ -945,6 +1132,8 @@ def test_claim_answers_before_the_launch_and_pushes_the_room_url( assert "host" not in body assert [event for event, _ in sent] == ["streaming:launch-ready"] assert _launch_ready(sent)["host"] == "http://192.168.1.10:3000" + # A re-claim of the same container is only told apart by its stamp. + assert _launch_ready(sent)["claimed_at"] == body["claimed_at"] def test_a_failed_launch_pushes_the_reason_and_frees_the_container( @@ -963,6 +1152,7 @@ def test_a_failed_launch_pushes_the_reason_and_frees_the_container( assert event == "streaming:launch-failed" assert payload["detail"] == "broker said no" assert payload["container"] == _key_of(_container_for(rom)) + assert payload["claimed_at"] == r.json()["claimed_at"] assert _session_raw(_container_for(rom)) is None @@ -995,9 +1185,10 @@ def test_launch_phase_is_pushed_while_a_webstation_unpacks( r = _claim(client, access_token, rom.id) assert r.status_code == 202 - pushed = [p["phase"] for event, p in sent if event == "streaming:launch-phase"] + phases_sent = [p for event, p in sent if event == "streaming:launch-phase"] # Only changes are pushed, so a repeated phase is not re-sent. - assert pushed == ["unpacking", "installing"] + assert [p["phase"] for p in phases_sent] == ["unpacking", "installing"] + assert {p["claimed_at"] for p in phases_sent} == {r.json()["claimed_at"]} assert sent[-1][0] == "streaming:launch-ready" @@ -1194,10 +1385,11 @@ def _pool_member(rom: Rom, index: int) -> dict: } -def _volume(client, token, platform: str, level: int = 42): +def _volume(client, token, platform: str, level: int = 42, params=None): return client.post( f"/api/streaming/sessions/{platform}/volume", json={"level": level}, + params=params, headers=_auth(token), ) @@ -1207,6 +1399,16 @@ def _session_raw(container: dict): return asyncio.run(async_cache.get(key)) +def _drain(container: dict) -> None: + session = _load_session(session_store.session_redis_key(_key_of(container))) + token = asyncio.run(session_store.claim_drain_marker(_key_of(container), session)) + assert token is not None + + +def _stub_stop(): + return patch("handler.streaming.commands.stop", return_value=commands.StopOutcome()) + + def test_pool_claim_falls_through_to_a_free_container( client, access_token, viewer_access_token, rom: Rom ): @@ -1234,6 +1436,48 @@ def test_pool_409s_only_once_every_container_is_held( assert "2 containers" in r3.json()["detail"]["message"] +def test_a_busy_pool_names_the_holder_while_a_member_drains( + client, access_token, viewer_access_token, editor_access_token, rom: Rom +): + """A drain marker names nobody, so reading only the head of the pool told + the waiting player the platform was saving while another member played on.""" + head, tail = _pool_member(rom, 0), _pool_member(rom, 1) + with _streaming(head, tail): + _claim_ok(client, access_token, rom.id) + _claim_ok(client, viewer_access_token, rom.id) + holder = json.loads(_session_raw(tail)) + _drain(head) + r = _claim_ok(client, editor_access_token, rom.id) + + assert r.status_code == 409 + detail = r.json()["detail"] + # One member is about to come free, which is what "try again shortly" says. + assert detail["draining"] is True + assert detail["rom_name"] == rom.name + assert detail["claimed_at"] == holder["claimed_at"] + + +def test_a_busy_pool_reports_a_drain_on_any_member( + client, access_token, viewer_access_token, editor_access_token, rom: Rom +): + """The container about to come free is the one the waiting player is told to + wait for, wherever in the pool it sits.""" + head, tail = _pool_member(rom, 0), _pool_member(rom, 1) + with _streaming(head, tail): + _claim_ok(client, access_token, rom.id) + _claim_ok(client, viewer_access_token, rom.id) + holder = json.loads(_session_raw(head)) + _drain(tail) + r = _claim_ok(client, editor_access_token, rom.id) + + assert r.status_code == 409 + detail = r.json()["detail"] + assert detail["draining"] is True + assert "shutting down" in detail["message"] + assert detail["rom_name"] == rom.name + assert detail["claimed_at"] == holder["claimed_at"] + + def test_a_claim_never_lands_in_a_later_pool( client, access_token, viewer_access_token, rom: Rom ): @@ -1265,6 +1509,37 @@ def test_a_pool_does_not_roll_its_own_holder_onto_a_second_container( assert free is None +def test_a_session_on_one_platform_does_not_block_a_claim_on_another( + client, access_token +): + """The caller's ps2 session sits on a key the ngc walk visits too, and only + occupies that container rather than counting as the player's ngc session.""" + ps2_rom = _rom_on("ps2") + ngc_rom = _rom_on("ngc") + second = _nested( + host="http://192.168.1.11:3000", broker_host="http://192.168.1.11:8000" + ) + with _streaming(_nested(), second): + r1 = _claim_ok(client, access_token, ps2_rom.id) + r2 = _claim_ok(client, access_token, ngc_rom.id) + assert [r1.status_code, r2.status_code] == [202, 202] + assert r1.json()["container"] == _key_of(_nested()) + assert r2.json()["container"] == _key_of(second) + + +def test_status_does_not_report_a_session_on_another_platform(client, access_token): + """The ps2 claim shares its key with the container's ngc row, and a poll for + ngc must not read that as a session the caller holds there.""" + ps2_rom = _rom_on("ps2") + with _streaming(_nested()): + assert _claim_ok(client, access_token, ps2_rom.id).status_code == 202 + r = client.get( + "/api/streaming/sessions/ngc/status", headers=_auth(access_token) + ) + assert r.status_code == 200 + assert r.json()["status"] == "ended" + + @contextmanager def _claim_in_flight(platform: str, user_id: int) -> Iterator[None]: """Stand in for a claim from the same player that is inside the reserve and @@ -1306,7 +1581,7 @@ def test_a_pool_hands_the_owner_of_a_stale_session_their_own_container_back( _age_session_on( _pool_member(rom, 0), session_store._STREAMING_SESSION_STALE_SECONDS + 60 ) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): r2 = _claim_ok(client, access_token, rom.id) free = asyncio.run(session_store.get_session(_key_of(_pool_member(rom, 1)))) assert r2.status_code == 202 @@ -1324,7 +1599,7 @@ def test_pool_never_evicts_a_stale_session_while_a_container_is_free( _age_session_on( _pool_member(rom, 0), session_store._STREAMING_SESSION_STALE_SECONDS + 60 ) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r2 = _claim_ok(client, viewer_access_token, rom.id) assert r2.status_code == 202 assert r2.json()["container"] == _key_of(_pool_member(rom, 1)) @@ -1341,7 +1616,7 @@ def test_pool_takes_over_a_stale_session_once_every_container_is_held( _age_session_on( _pool_member(rom, 1), session_store._STREAMING_SESSION_STALE_SECONDS + 60 ) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r3 = _claim_ok(client, viewer_access_token, rom.id) assert r3.status_code == 202 assert r3.json()["container"] == _key_of(_pool_member(rom, 1)) @@ -1400,6 +1675,52 @@ def test_an_admin_cannot_guess_which_of_two_sessions_to_control( assert r.status_code == 409 +def test_an_admin_names_which_of_two_sessions_to_control( + client, access_token, viewer_access_token, editor_access_token, rom: Rom +): + with _streaming(_pool_member(rom, 0), _pool_member(rom, 1)): + _claim_ok(client, viewer_access_token, rom.id) + _claim_ok(client, editor_access_token, rom.id) + with patch( + "handler.streaming.commands.set_volume", return_value=True + ) as volume: + r = _volume( + client, + access_token, + rom.platform_slug, + params={"container": _key_of(_pool_member(rom, 1))}, + ) + assert r.status_code == 200 + assert volume.call_args[0][0].host == "http://192.168.1.11:3000" + + +@pytest.mark.parametrize( + "route, body, command", + [ + ("volume", {"level": 42}, "set_volume"), + ("mute", {"mute": True}, "set_mute"), + ("save-state", {"slot": 1}, "save_state"), + ("load-state", {"slot": 1}, "load_state"), + ("swap-disc", {"file_id": 1}, "swap_disc"), + ], +) +def test_a_control_for_a_replaced_claim_never_reaches_the_broker( + client, access_token, rom: Rom, route, body, command +): + """A tab that missed its takeover must not drive the claim that replaced it.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch(f"handler.streaming.commands.{command}") as broker: + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/{route}", + json=body, + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(access_token), + ) + assert r.status_code == 404 + broker.assert_not_called() + + def test_admin_release_names_the_container( client, access_token, viewer_access_token, editor_access_token, rom: Rom ): @@ -1408,7 +1729,7 @@ def test_admin_release_names_the_container( with _streaming(_pool_member(rom, 0), _pool_member(rom, 1)): _claim_ok(client, viewer_access_token, rom.id) _claim_ok(client, editor_access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): r = client.delete( f"/api/streaming/sessions/{rom.platform_slug}", params={"container": _key_of(_pool_member(rom, 1))}, @@ -1452,7 +1773,7 @@ def test_admin_release_ends_a_session_on_a_container_in_a_later_pool( key = _key_of(later) assert key not in [c.key for c in streaming.containers_for_platform("ps2")] assert _desktop(client, access_token, key)[0].status_code == 200 - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): r = client.delete( "/api/streaming/sessions/ps2", params={"container": key}, @@ -1494,7 +1815,7 @@ def test_heartbeat_naming_a_released_container_reports_ended(client, access_toke _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 ) assert _desktop(client, access_token, key)[0].status_code == 200 - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): released = client.delete( "/api/streaming/sessions/ps2", params={"container": key}, @@ -1537,7 +1858,7 @@ def test_status_finds_the_termination_on_whichever_container_held_it( with _streaming(_pool_member(rom, 0), _pool_member(rom, 1)): _claim_ok(client, access_token, rom.id) _claim_ok(client, viewer_access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): client.delete( "/api/streaming/sessions", params={"reason": "maintenance"}, @@ -1552,6 +1873,76 @@ def test_status_finds_the_termination_on_whichever_container_held_it( assert r.json()["termination"]["reason"] == "maintenance" +def test_status_does_not_report_a_desktop_notice_to_a_game_poll(client, access_token): + """One tombstone per container and one room per user, so the poll has to + scope the notice the same way it scopes the session it looked for.""" + ps2_rom = _rom_on("ps2") + with _streaming(_webstation()): + key = _key_of(_webstation()) + assert _desktop(client, access_token, key)[0].status_code == 200 + with _stub_stop(): + ended = client.delete( + "/api/streaming/sessions/ps2", + params={"container": key, "reason": "patching the host"}, + headers=_auth(access_token), + ) + assert ended.status_code == 200 + r = client.get( + f"/api/streaming/sessions/{ps2_rom.platform_slug}/status", + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert r.json()["termination"] is None + + +def test_a_desktop_beat_still_learns_why_its_claim_ended(client, access_token): + """The desktop names its container, which is what puts its own notice in + scope: nothing else would tell that tab it was taken away.""" + with _streaming(_webstation()): + key = _key_of(_webstation()) + assert _desktop(client, access_token, key)[0].status_code == 200 + with _stub_stop(): + client.delete( + "/api/streaming/sessions/ps2", + params={"container": key, "reason": "patching the host"}, + headers=_auth(access_token), + ) + r = client.post( + "/api/streaming/sessions/ps2/heartbeat", + params={"container": key}, + headers=_auth(access_token), + ) + assert r.json()["status"] == "ended" + notice = r.json()["termination"] + assert notice["reason"] == "patching the host" + assert notice["desktop"] is True + assert notice["container"] == key + + +def test_status_does_not_report_a_notice_from_another_platform(client, access_token): + """A container serving two platforms files both notices under one key, so + the ngc session ending is not an answer for the ps2 tab.""" + ngc_rom = _rom_on("ngc") + with _streaming(_nested()): + _claim_ok(client, access_token, ngc_rom.id) + with _stub_stop(): + client.delete( + "/api/streaming/sessions/ngc", + params={"reason": "patching the host"}, + headers=_auth(access_token), + ) + r = client.get( + "/api/streaming/sessions/ps2/status", headers=_auth(access_token) + ) + ngc = client.get( + "/api/streaming/sessions/ngc/status", headers=_auth(access_token) + ) + assert r.json()["status"] == "ended" + assert r.json()["termination"] is None + assert ngc.json()["termination"]["reason"] == "patching the host" + + def test_heartbeat_refreshes_the_session_on_the_container_that_holds_it( client, access_token, viewer_access_token, rom: Rom ): @@ -1605,6 +1996,33 @@ def test_a_container_that_disagrees_on_the_emulator_is_a_later_pool(caplog): assert _key_of(second) in caplog.text +def test_a_fresh_process_does_not_repeat_the_later_pool_warning(caplog): + """Every reaper run is a new RQ job process with nothing memoized.""" + first = { + "platform": "ps2", + "host": "http://192.168.1.10:3000", + "broker_host": "http://192.168.1.10:8000", + "emulator": "pcsx2", + } + second = { + **first, + "host": "http://192.168.1.11:3000", + "broker_host": "http://192.168.1.11:8000", + "emulator": "play", + } + romm_logger = logging.getLogger("romm") + romm_logger.addHandler(caplog.handler) + try: + with caplog.at_level(logging.WARNING, logger="romm"): + with _streaming(first, second): + streaming.containers_for_platform("ps2") + with _streaming(first, second): + streaming.containers_for_platform("ps2") + finally: + romm_logger.removeHandler(caplog.handler) + assert caplog.text.count("never claimed for a game") == 1 + + def test_a_lone_container_is_a_pool_of_one(rom: Rom): member = _pool_member(rom, 0) with _streaming(member): @@ -1661,7 +2079,7 @@ def test_a_proxied_host_disagreeing_with_its_subfolder_cannot_be_claimed(caplog) with _streaming(entry): with caplog.at_level(logging.WARNING, logger="romm"): candidates = streaming.containers_for_platform("ps2") - listed = streaming.resolve_containers() + listed = resolve_containers() finally: romm_logger.removeHandler(caplog.handler) assert candidates == [] @@ -1833,6 +2251,35 @@ def _claim_webstation_ok(client, token, rom_id): return _claim(client, token, rom_id) +def test_containers_reports_a_container_that_is_still_saving( + client, access_token, rom: Rom +): + """A drain marker has no owner, so the row read as idle while the previous + session's state was still coming out of the container.""" + container = _container_for(rom) + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _drain(container) + rows = _containers(client, access_token).json()["containers"] + + assert rows[0]["draining"] is True + assert rows[0]["session"] is None + + +def test_a_desktop_refused_over_a_drain_says_it_is_saving(client, access_token): + """Nobody holds a draining container, so "in use" names no one and the + admin needs to hear that waiting is enough.""" + ps2_rom = _rom_on("ps2") + container = _webstation() + with _streaming(container): + _claim_webstation_ok(client, access_token, ps2_rom.id) + _drain(container) + response, _ = _desktop(client, access_token, _key_of(container)) + + assert response.status_code == 409 + assert response.json()["detail"]["draining"] is True + + def test_containers_lists_one_row_per_container(client, access_token): """A container serves many platforms but hosts one session, so the fleet view counts containers, not the platform rows /config ships.""" @@ -1923,6 +2370,115 @@ def test_desktop_and_a_game_block_each_other(client, access_token): assert _desktop(client, access_token, key)[0].status_code == 409 +def test_an_admins_desktop_does_not_block_their_game_claim(client, access_token): + """A desktop occupies its container, not the platform, so the claim rolls + onto the free pool member.""" + ps2_rom = _rom_on("ps2") + second = _webstation( + host="http://192.168.1.11:3000", broker_host="http://192.168.1.11:8000" + ) + with _streaming(_webstation(), second): + assert ( + _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 + ) + r = _claim_webstation_ok(client, access_token, ps2_rom.id) + assert r.status_code == 202 + assert r.json()["container"] == _key_of(second) + + +def test_an_unnamed_heartbeat_skips_the_callers_desktop( + client, access_token, viewer_access_token +): + """An admin playing on one pool member while holding a desktop on another + beats their game session, not the desktop the walk reaches first.""" + ps2_rom = _rom_on("ps2") + second = _webstation( + host="http://192.168.1.11:3000", broker_host="http://192.168.1.11:8000" + ) + with _streaming(_webstation(), second): + # The viewer takes the head of the pool, so the admin's game lands on + # the second member and the desktop gets the head once it is released. + assert ( + _claim_webstation_ok(client, viewer_access_token, ps2_rom.id).status_code + == 202 + ) + assert _claim_webstation_ok(client, access_token, ps2_rom.id).json()[ + "container" + ] == _key_of(second) + with ( + _stub_stop(), + patch("handler.streaming.background.spawn_sync_task"), + ): + client.delete( + "/api/streaming/sessions/ps2", headers=_auth(viewer_access_token) + ) + assert ( + _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 + ) + _age_session_on(_webstation(), 120) + _age_session_on(second, 120) + desktop_before = json.loads(_session_raw(_webstation()))["last_seen"] + game_before = json.loads(_session_raw(second))["last_seen"] + r = client.post( + "/api/streaming/sessions/ps2/heartbeat", headers=_auth(access_token) + ) + desktop_after = json.loads(_session_raw(_webstation()))["last_seen"] + game_after = json.loads(_session_raw(second))["last_seen"] + assert r.json()["status"] == "active" + assert game_after > game_before + assert desktop_after == desktop_before + + +def test_an_unnamed_release_leaves_the_callers_desktop_alone(client, access_token): + """Desktop.vue names its container and a game tab never does, so an unnamed + release must not end the desktop the admin has open.""" + with _streaming(_webstation()): + key = _key_of(_webstation()) + assert _desktop(client, access_token, key)[0].status_code == 200 + with _stub_stop(): + r = client.delete( + "/api/streaming/sessions/ps2", headers=_auth(access_token) + ) + session = asyncio.run(session_store.get_session(key)) + assert r.json()["status"] == "not_found" + assert session is not None and session["desktop"] is True + + +def test_an_unnamed_release_leaves_another_platforms_session_alone( + client, access_token +): + """The container's ngc row shares a key with the caller's ps2 session, so an + unnamed ngc release must not end the ps2 game.""" + ps2_rom = _rom_on("ps2") + with _streaming(_nested()): + assert _claim_ok(client, access_token, ps2_rom.id).status_code == 202 + with _stub_stop(): + r = client.delete( + "/api/streaming/sessions/ngc", headers=_auth(access_token) + ) + session = asyncio.run(session_store.get_session(_key_of(_nested()))) + assert r.json()["status"] == "not_found" + assert session is not None and session["platform"] == "ps2" + + +def test_an_unnamed_heartbeat_leaves_another_platforms_session_alone( + client, access_token +): + """An ngc tab beating unnamed must not keep the caller's ps2 session on the + same container alive.""" + ps2_rom = _rom_on("ps2") + with _streaming(_nested()): + assert _claim_ok(client, access_token, ps2_rom.id).status_code == 202 + _age_session_on(_nested(), 120) + before = json.loads(_session_raw(_nested()))["last_seen"] + r = client.post( + "/api/streaming/sessions/ngc/heartbeat", headers=_auth(access_token) + ) + after = json.loads(_session_raw(_nested()))["last_seen"] + assert r.json()["status"] == "ended" + assert after == before + + def test_desktop_is_admin_only(client, viewer_access_token): with _streaming(_webstation()): key = _key_of(_first_container("ps2")) @@ -1970,11 +2526,12 @@ def test_releasing_a_desktop_session_syncs_nothing_to_the_library(client, access container = _first_container("ps2") assert _desktop(client, access_token, _key_of(container))[0].status_code == 200 with ( - patch("handler.streaming.commands.stop", return_value=None) as stop, + _stub_stop() as stop, patch("handler.streaming.background.spawn_sync_task") as spawn, ): response = client.delete( f"/api/streaming/sessions/{container.platform}", + params={"container": _key_of(container)}, headers=_auth(access_token), ) assert response.status_code == 200 @@ -2136,13 +2693,37 @@ def test_stale_session_taken_over_on_claim( with _streaming(_container_for(rom)): r1 = _claim_ok(client, access_token, rom.id) _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r2 = _claim_ok(client, viewer_access_token, rom.id) assert r1.status_code == 202 assert r2.status_code == 202 stop_broker.assert_called_once() +def test_a_swept_session_is_torn_down_with_its_own_platforms_record( + client, access_token, viewer_access_token +): + """An ngc claim sweeping a stale ps2 session on a shared container tears it + down as pcsx2, since the state and card coming out are that emulator's.""" + ps2_rom = _rom_on("ps2") + ngc_rom = _rom_on("ngc") + with _streaming(_nested()): + _claim_ok(client, access_token, ps2_rom.id) + _age_session_on(_nested(), session_store._STREAMING_SESSION_STALE_SECONDS + 60) + with ( + patch( + "handler.streaming.commands.stop", return_value=commands.StopOutcome(3) + ) as stop, + patch( + "handler.streaming.states.pull_state_to_library", new=AsyncMock() + ) as pull_state, + ): + r = _claim_ok(client, viewer_access_token, ngc_rom.id) + assert r.status_code == 202 + assert stop.call_args.args[0].emulator == "pcsx2" + assert pull_state.call_args.args[2].emulator == "pcsx2" + + def test_the_owner_of_a_stale_session_can_claim_it_again( client, access_token, rom: Rom ): @@ -2151,7 +2732,7 @@ def test_the_owner_of_a_stale_session_can_claim_it_again( with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r2 = _claim_ok(client, access_token, rom.id) assert r2.status_code == 202 stop_broker.assert_called_once() @@ -2169,7 +2750,7 @@ def test_takeover_leaves_the_displaced_owner_a_notice( "user_id" ] _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): _claim_ok(client, viewer_access_token, rom.id) notice = asyncio.run(session_store.get_termination(_key_of(container), owner)) @@ -2179,6 +2760,29 @@ def test_takeover_leaves_the_displaced_owner_a_notice( assert notice["rom_id"] == rom.id +def test_taking_over_ones_own_stale_session_pushes_no_notice( + client, access_token, rom: Rom +): + """The notice goes to the user, whose only tab is now the one that just + claimed this container, and it would end that fresh claim.""" + container = _container_for(rom) + sent: list[str] = [] + + async def _capture(user_id: Any, event: str, payload: dict[str, Any]) -> None: + sent.append(event) + + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + with ( + _stub_stop(), + patch("handler.streaming.session_store.push_to_user", new=_capture), + ): + _claim_ok(client, access_token, rom.id) + + assert "streaming:session-ended" not in sent + + def test_takeover_aborts_when_the_owner_comes_back_first( client, access_token, viewer_access_token, rom: Rom ): @@ -2201,12 +2805,12 @@ def test_takeover_aborts_when_the_owner_comes_back_first( checked = True return real_stale(session) - # Both callers hold their own reference: the claim route runs the scan, + # Both callers hold their own reference: session_store runs the scan, # lifecycle re-checks under the marker. with ( - patch.object(streaming, "session_is_stale", stale_then_fresh), + patch.object(session_store, "session_is_stale", stale_then_fresh), patch.object(lifecycle, "session_is_stale", stale_then_fresh), - patch("handler.streaming.commands.stop", return_value=None) as stop_broker, + _stub_stop() as stop_broker, ): r = _claim_ok(client, viewer_access_token, rom.id) @@ -2221,7 +2825,7 @@ def test_fresh_session_not_taken_over( and the running emulator is never stopped.""" with _streaming(_container_for(rom)): r1 = _claim_ok(client, access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r2 = _claim_ok(client, viewer_access_token, rom.id) assert r1.status_code == 202 assert r2.status_code == 409 @@ -2245,6 +2849,40 @@ def test_heartbeat_refreshes_last_seen(client, access_token, rom: Rom): assert not session_store.session_is_stale(session) +def test_a_heartbeat_for_a_replaced_claim_reports_ended(client, access_token, rom: Rom): + """A tab that missed its takeover must not keep the claim that replaced it + alive: the stamp it was given is what identifies the claim it holds.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + _age_session(rom, 60) + before = json.loads(_session_raw(_container_for(rom)))["last_seen"] + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(access_token), + ) + after = json.loads(_session_raw(_container_for(rom)))["last_seen"] + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert after == before + + +def test_a_heartbeat_naming_its_own_claim_still_refreshes_it( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + _age_session(rom, 60) + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + params={"claimed_at": claimed_at}, + headers=_auth(access_token), + ) + session = json.loads(_session_raw(_container_for(rom))) + assert r.json()["status"] == "active" + assert not session_store.session_is_stale(session) + + def test_heartbeat_racing_a_teardown_reports_ended(client, access_token, rom: Rom): """The refresh finds nothing when the claim was released between the lookup and the write; answering "active" there would leave the client beating a @@ -2270,6 +2908,75 @@ def test_heartbeat_racing_a_teardown_reports_ended(client, access_token, rom: Ro assert r.json()["status"] == "ended" +def test_heartbeat_for_a_session_reassigned_mid_request_reports_ended( + client, access_token, viewer_access_token, viewer_user: User, rom: Rom +): + """The write re-checks the owner the lookup found: a takeover landing in + between must not have the loser's beat keep it alive.""" + container = _container_for(rom) + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _age_session(rom, 60) + before = json.loads(_session_raw(container))["last_seen"] + key = session_store.session_redis_key(_key_of(container)) + + real_find = access.find_session_for_user + + async def find_then_reassign(*args, **kwargs): + found = await real_find(*args, **kwargs) + raw = await async_cache.get(key) + assert raw is not None + session = json.loads(raw) + session["user_id"] = viewer_user.id + await async_cache.set(key, json.dumps(session)) + return found + + with patch.object(access, "find_session_for_user", find_then_reassign): + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + headers=_auth(access_token), + ) + after = json.loads(_session_raw(container))["last_seen"] + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert after == before + + +def test_heartbeat_for_a_claim_restamped_mid_request_reports_ended( + client, access_token, rom: Rom +): + """The same player pressing Play again between the lookup and the write + replaces the claim, which the old tab's beat must not keep alive.""" + container = _container_for(rom) + with _streaming(container): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + _age_session(rom, 60) + before = json.loads(_session_raw(container))["last_seen"] + key = session_store.session_redis_key(_key_of(container)) + + real_find = access.find_session_for_user + + async def find_then_restamp(*args, **kwargs): + found = await real_find(*args, **kwargs) + raw = await async_cache.get(key) + assert raw is not None + session = json.loads(raw) + session["claimed_at"] = "2099-01-01T00:00:00+00:00" + await async_cache.set(key, json.dumps(session)) + return found + + with patch.object(access, "find_session_for_user", find_then_restamp): + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + params={"claimed_at": claimed_at}, + headers=_auth(access_token), + ) + after = json.loads(_session_raw(container))["last_seen"] + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert after == before + + def test_heartbeat_does_not_revive_a_draining_session(client, access_token, rom: Rom): """A container being torn down must not be made to look live again: the emulator is already stopped and its card evacuated.""" @@ -2359,7 +3066,8 @@ def test_heartbeat_for_unknown_platform_returns_404(client, access_token, rom: R def test_status_reports_active_for_owner(client, access_token, rom: Rom): - with _streaming(_container_for(rom)): + container = _container_for(rom) + with _streaming(container): _claim_ok(client, access_token, rom.id) r = client.get( f"/api/streaming/sessions/{rom.platform_slug}/status", @@ -2371,9 +3079,36 @@ def test_status_reports_active_for_owner(client, access_token, rom: Rom): "platform": rom.platform_slug, "extraction_phase": None, "termination": None, + "host": container["host"], } +def test_status_carries_the_room_the_launch_answered_with(client, access_token): + """launch-ready is pushed once: a tab that was reloading when the game came + up has only the poll to find its way back into the stream.""" + rom = _rom_on("ps2") + container = _webstation() + with _streaming(container): + assert _claim_webstation_ok(client, access_token, rom.id).status_code == 202 + r = client.get( + "/api/streaming/sessions/ps2/status", headers=_auth(access_token) + ) + assert r.status_code == 200 + assert r.json()["host"].endswith("/room/x") + + +def test_a_desktop_launch_is_stamped_without_a_room(client, access_token): + """The desktop POST is the only place its room is read, so the session keeps + just the launch stamp the status fallback gates its broker call on.""" + container = _webstation() + with _streaming(container): + response, _ = _desktop(client, access_token, _key_of(container)) + assert response.status_code == 200 + session = json.loads(_session_raw(container)) + assert session["launched_at"] + assert "host" not in session + + def test_status_does_not_refresh_the_session(client, access_token, rom: Rom): """Status is read-only: polling it must not extend a claim, otherwise a background tab could keep a container hostage without playing.""" @@ -2389,6 +3124,24 @@ def test_status_does_not_refresh_the_session(client, access_token, rom: Rom): assert session_store.session_is_stale(session) +def test_status_for_a_replaced_claim_reports_ended(client, access_token, rom: Rom): + """A loading tab whose claim was re-taken on the same container must not be + handed the new claim's room as its own.""" + with _streaming(_container_for(rom)): + first = _claim_ok(client, access_token, rom.id) + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + with _stub_stop(): + second = _claim_ok(client, access_token, rom.id) + assert second.json()["container"] == first.json()["container"] + r = client.get( + f"/api/streaming/sessions/{rom.platform_slug}/status", + params={"claimed_at": first.json()["claimed_at"]}, + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "ended" + + def test_admin_release_leaves_termination_notice( client, access_token, viewer_access_token, rom: Rom ): @@ -2457,6 +3210,123 @@ def test_heartbeat_carries_termination_notice( assert body["termination"]["reason"] == "patching the host" +def test_a_termination_notice_names_the_container_it_ended( + client, access_token, viewer_access_token, rom: Rom +): + """A player can hold a session on several containers, so the notice has to + say which one ended for the right tab to act on it.""" + with _streaming(_container_for(rom)): + _claim_ok(client, viewer_access_token, rom.id) + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"reason": "maintenance window"}, + headers=_auth(access_token), + ) + r = client.get( + f"/api/streaming/sessions/{rom.platform_slug}/status", + headers=_auth(viewer_access_token), + ) + notice = r.json()["termination"] + assert notice["container"] == _key_of(_container_for(rom)) + assert notice["desktop"] is False + + +def test_a_termination_notice_names_the_claim_it_ended( + client, access_token, viewer_access_token, rom: Rom +): + """A re-claim of the same container keeps its key, so only the stamp tells + the tab that lost its claim from the one holding the next.""" + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, viewer_access_token, rom.id).json()["claimed_at"] + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + r = client.get( + f"/api/streaming/sessions/{rom.platform_slug}/status", + headers=_auth(viewer_access_token), + ) + assert r.json()["termination"]["claimed_at"] == claimed_at + + +def test_status_does_not_report_the_notice_of_another_claim( + client, access_token, viewer_access_token, rom: Rom +): + """A poll names the claim it asks about, so a notice filed for another + claim on the container must not tell it who ended its own.""" + with _streaming(_container_for(rom)): + _claim_ok(client, viewer_access_token, rom.id) + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"reason": "maintenance window"}, + headers=_auth(access_token), + ) + r = client.get( + f"/api/streaming/sessions/{rom.platform_slug}/status", + params={"claimed_at": "2026-09-17T10:05:00+00:00"}, + headers=_auth(viewer_access_token), + ) + assert r.json()["status"] == "ended" + assert r.json()["termination"] is None + + +def test_a_termination_notice_lands_before_the_drain( + client, access_token, viewer_access_token, rom: Rom +): + """The session ends when the drain marker is written, so a poll during the + seconds-long drain is told why the stream stopped, not a bare `ended`.""" + container = _container_for(rom) + seen: list[dict[str, Any] | None] = [] + + with _streaming(container): + _claim_ok(client, viewer_access_token, rom.id) + user_id = json.loads(_session_raw(container))["user_id"] + + async def capture(*args, **kwargs): + seen.append( + await session_store.get_termination(_key_of(container), user_id) + ) + return commands.StopOutcome() + + with patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(side_effect=capture), + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"reason": "maintenance window"}, + headers=_auth(access_token), + ) + assert seen and seen[0] is not None + assert seen[0]["reason"] == "maintenance window" + + +def test_a_takeover_notice_lands_before_the_drain( + client, access_token, viewer_access_token, rom: Rom +): + """The abandoned owner's tab polls through the takeover's drain like any + other, so the notice has to be there before the quiesce starts.""" + container = _container_for(rom) + seen: list[dict[str, Any] | None] = [] + + with _streaming(container): + _claim_ok(client, access_token, rom.id) + owner = json.loads(_session_raw(container))["user_id"] + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + + async def capture(*args, **kwargs): + seen.append(await session_store.get_termination(_key_of(container), owner)) + return commands.StopOutcome() + + with patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(side_effect=capture), + ): + _claim_ok(client, viewer_access_token, rom.id) + assert seen and seen[0] is not None + assert seen[0]["reason"] == "abandoned" + + def test_force_release_all_leaves_termination_notice( client, access_token, viewer_access_token, rom: Rom ): @@ -2616,12 +3486,8 @@ def test_status_stops_asking_the_broker_once_the_launch_returned(client, access_ r = client.get( "/api/streaming/sessions/ps2/status", headers=_auth(access_token) ) - assert r.json() == { - "status": "active", - "platform": "ps2", - "extraction_phase": None, - "termination": None, - } + assert r.json()["status"] == "active" + assert r.json()["extraction_phase"] is None broker.assert_not_called() @@ -2638,12 +3504,8 @@ def test_status_on_a_legacy_container_never_asks_for_a_phase( f"/api/streaming/sessions/{rom.platform_slug}/status", headers=_auth(access_token), ) - assert r.json() == { - "status": "active", - "platform": rom.platform_slug, - "extraction_phase": None, - "termination": None, - } + assert r.json()["status"] == "active" + assert r.json()["extraction_phase"] is None broker.assert_not_called() @@ -2654,7 +3516,7 @@ def test_release_uses_container_key_not_platform(client, access_token, rom: Rom) """release_session must find the session by broker_host, not platform string.""" with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): r = client.delete( f"/api/streaming/sessions/{rom.platform_slug}", headers=_auth(access_token), @@ -2663,6 +3525,80 @@ def test_release_uses_container_key_not_platform(client, access_token, rom: Rom) assert r.json()["status"] == "released" +def test_a_release_for_a_replaced_claim_leaves_the_session( + client, access_token, rom: Rom +): + """A tab whose claim was taken over still releases on unload, and it must + not end the session that replaced it.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with _stub_stop() as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(access_token), + ) + session = asyncio.run(session_store.get_session(_key_of(_container_for(rom)))) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + stop.assert_not_called() + assert session is not None + + +def test_a_release_naming_its_own_claim_still_ends_the_session( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + with _stub_stop() as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"claimed_at": claimed_at}, + headers=_auth(access_token), + ) + assert r.json()["status"] == "released" + stop.assert_called_once() + + +def test_a_release_for_a_claim_another_player_took_over_is_a_no_op( + client, viewer_access_token, editor_access_token, rom: Rom +): + """The tab lost its claim, so the player now holding the container is none + of its business, not a forbidden target.""" + with _streaming(_container_for(rom)): + _claim_ok(client, editor_access_token, rom.id) + with _stub_stop() as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={ + "container": _key_of(_container_for(rom)), + "claimed_at": "2020-01-01T00:00:00+00:00", + }, + headers=_auth(viewer_access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + stop.assert_not_called() + + +def test_an_unnamed_release_for_a_claim_another_player_took_over_is_a_no_op( + client, viewer_access_token, editor_access_token, rom: Rom +): + """A stamped release that names no container reads a takeover the same way + as a named one.""" + with _streaming(_container_for(rom)): + _claim_ok(client, editor_access_token, rom.id) + with _stub_stop() as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(viewer_access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + stop.assert_not_called() + + def test_release_by_other_user_is_forbidden( client, access_token, viewer_access_token, rom: Rom ): @@ -2715,11 +3651,12 @@ def test_save_and_exit_releases_session_once_the_state_is_pulled( with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(True, 10)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ), patch("handler.streaming.states.pull_state_to_library", new=AsyncMock()), - # Plain MagicMock: the async original would auto-mock to AsyncMock, - # whose call handed to the mocked spawn is a never-awaited coroutine. - patch("handler.streaming.saves.pull_saves_to_library", new=MagicMock()), + patch("handler.streaming.saves.pull_saves_to_library", new=AsyncMock()), patch( "handler.streaming.background.spawn_sync_task", side_effect=spawned.append, @@ -2740,13 +3677,128 @@ def test_save_and_exit_releases_session_once_the_state_is_pulled( assert r2.status_code == 202 +def test_a_save_and_exit_for_a_replaced_claim_leaves_the_session( + client, access_token, rom: Rom +): + """A playing tab that missed its takeover saves and exits on unload, and + must not end the session that replaced it.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), + ) as save_and_exit: + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + params={ + "container": _key_of(_container_for(rom)), + "claimed_at": "2020-01-01T00:00:00+00:00", + }, + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + session = asyncio.run(session_store.get_session(_key_of(_container_for(rom)))) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + save_and_exit.assert_not_called() + assert session is not None + + +def test_a_save_and_exit_naming_its_own_claim_still_ends_the_session( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + with patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), + ) as save_and_exit: + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + params={ + "container": _key_of(_container_for(rom)), + "claimed_at": claimed_at, + }, + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + assert r.json()["status"] == "ok" + save_and_exit.assert_called_once() + + +def test_a_named_save_and_exit_leaves_another_platforms_session_alone( + client, access_token +): + """The container's ngc row shares a key with the caller's ps2 session, so a + named ngc save-and-exit must not save and kill the ps2 game.""" + ps2_rom = _rom_on("ps2") + with _streaming(_nested()): + assert _claim_ok(client, access_token, ps2_rom.id).status_code == 202 + with patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ) as save_and_exit: + r = client.post( + "/api/streaming/sessions/ngc/save-and-exit", + params={"container": _key_of(_nested())}, + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + session = asyncio.run(session_store.get_session(_key_of(_nested()))) + assert r.json()["status"] == "not_found" + save_and_exit.assert_not_called() + assert session is not None and session["platform"] == "ps2" + + +def test_a_named_save_and_exit_leaves_a_desktop_alone(client, access_token): + """Save-and-exit acts on a game, so naming a desktop's container reaches + nothing to save.""" + container = _webstation() + key = _key_of(container) + with _streaming(container): + assert _desktop(client, access_token, key)[0].status_code == 200 + with patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ) as save_and_exit: + r = client.post( + "/api/streaming/sessions/ps2/save-and-exit", + params={"container": key}, + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + session = asyncio.run(session_store.get_session(key)) + assert r.json()["status"] == "not_found" + save_and_exit.assert_not_called() + assert session is not None and session["desktop"] is True + + +def test_a_save_and_exit_with_nothing_active_is_a_no_op(client, access_token, rom: Rom): + """A retried unload finds its claim already gone, which ends nothing.""" + with _streaming(_container_for(rom)): + with patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), + ) as save_and_exit: + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + assert r.json()["released"] is True + save_and_exit.assert_not_called() + + def test_save_and_exit_failure_still_releases_session(client, access_token, rom: Rom): """A failed save is reported as saved=False, but the session is still released - the container must not stay claimed by a dead session.""" with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with patch( - "handler.streaming.commands.save_and_exit", return_value=(False, 10) + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), ): r = client.post( f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", @@ -2766,7 +3818,8 @@ def test_save_and_exit_rejects_a_slot_the_platform_lacks(client, access_token): with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with patch( - "handler.streaming.commands.save_and_exit", return_value=(True, 9) + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 9, True), ) as broker: r = client.post( "/api/streaming/sessions/ngc/save-and-exit", @@ -2781,7 +3834,7 @@ def test_force_release_all_stops_brokers(client, access_token, rom: Rom): """Force-release must tell each broker to stop, not just clear Redis.""" with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r = client.delete("/api/streaming/sessions", headers=_auth(access_token)) assert r.status_code == 200 assert stop_broker.call_count == 1 @@ -2931,12 +3984,15 @@ def test_save_and_exit_pulls_broker_effective_slot(client, access_token, rom: Ro with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(True, 10)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ), _spawns_nothing() as spawn, patch( "handler.streaming.states.pull_state_to_library", new=MagicMock() ) as pull, - patch("handler.streaming.saves.pull_saves_to_library", new=MagicMock()), + patch("handler.streaming.saves.pull_saves_to_library", new=AsyncMock()), ): r = client.post( f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", @@ -2957,13 +4013,17 @@ def test_save_and_exit_failed_blocking_save_skips_state_pull( with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(False, 10)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), + ), patch("handler.streaming.background.spawn_sync_task") as spawn, patch( "handler.streaming.states.pull_state_to_library", new=MagicMock() ) as state_pull, patch( - "handler.streaming.saves.pull_saves_to_library", new=MagicMock() + "handler.streaming.saves.pull_saves_to_library", + new_callable=AsyncMock, ) as save_pull, ): r = client.post( @@ -2971,10 +4031,11 @@ def test_save_and_exit_failed_blocking_save_skips_state_pull( json={"slot": 0, "wait": True}, headers=_auth(access_token), ) + spawn.assert_called_once() + asyncio.run(spawn.call_args[0][0]) assert r.status_code == 200 state_pull.assert_not_called() - save_pull.assert_called_once() - spawn.assert_called_once() + save_pull.assert_awaited_once() def test_save_and_exit_holds_the_container_until_the_state_is_pulled( @@ -2988,9 +4049,12 @@ def test_save_and_exit_holds_the_container_until_the_state_is_pulled( with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(True, 10)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ), patch("handler.streaming.states.pull_state_to_library", new=MagicMock()), - patch("handler.streaming.saves.pull_saves_to_library", new=MagicMock()), + patch("handler.streaming.saves.pull_saves_to_library", new=AsyncMock()), _spawns_nothing(), ): r = client.post( @@ -3038,7 +4102,10 @@ def test_save_and_exit_without_a_rom_drains_only_briefly( ) ) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(True, 10)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ), patch("handler.streaming.background.spawn_sync_task") as spawn, ): r = client.post( @@ -3200,7 +4267,7 @@ def test_work_running_under_a_claim_keeps_it_off_the_stale_list(): # runs and the test never waits on a clock. with ( patch.object(session_store, "_CLAIM_REFRESH_SECONDS", 0), - patch.object(session_store, "_HOLD_CEILING_SECONDS", 0), + patch.object(session_store, "HOLD_CEILING_SECONDS", 0), ): asyncio.run(session_store.hold_session_claim("cas-hold-claim", claim)) current = _load_session(key) @@ -3458,6 +4525,34 @@ def test_hydrate_skipped_when_resume_state_already_pushed(rom: Rom, admin_user: push.assert_not_called() +@pytest.mark.parametrize( + ("emulator", "name"), + [ + ("duckstation", "SLUS-00594_resume.20260918-010000000000.sav"), + ("rpcs3", "BLUS30443_1.20260918-010000000000.SAVESTAT"), + ], +) +def test_hydrate_pushes_nothing_to_an_exit_state_emulator( + rom: Rom, admin_user: User, emulator, name +): + """Their broker refuses a state file, and the save archive already carries + the exit state these library entries were pulled from.""" + db_state_handler.add_state(_state_for(rom, admin_user, name, emulator)) + container = {**_container_for(rom), "protocol": "webstation", "emulator": emulator} + with ( + patch( + "handler.filesystem.fs_asset_handler.read_file", + new=AsyncMock(return_value=b"state-bytes"), + ), + patch("handler.streaming.states.push_state_file", return_value=True) as push, + ): + pushed = asyncio.run( + states.hydrate_states_to_broker(admin_user.id, rom.id, _resolved(container)) + ) + assert pushed == 0 + push.assert_not_called() + + def test_hydrate_pushes_newest_state_under_container_name(rom: Rom, admin_user: User): """Only the newest capture is hydrated, and it lands under the unstamped name the emulator expects on disk.""" @@ -3701,6 +4796,7 @@ def test_store_state_screenshot_binds_to_state(admin_user: User, rom: Rom): state = db_state_handler.get_state_by_filename( user_id=admin_user.id, rom_id=rom.id, file_name="Game.03.p2s" ) + assert state is not None assert state.screenshot is not None assert state.screenshot.file_name == "Game.03.png" assert state.screenshot.is_gallery is False @@ -3723,6 +4819,7 @@ def test_store_state_screenshot_rejects_non_png(admin_user: User, rom: Rom): state = db_state_handler.get_state_by_filename( user_id=admin_user.id, rom_id=rom.id, file_name="Game.05.p2s" ) + assert state is not None assert state.screenshot is None @@ -3750,6 +4847,7 @@ def test_store_state_asset_binds_screenshot(admin_user: User, rom: Rom): state = db_state_handler.get_state_by_filename( user_id=admin_user.id, rom_id=rom.id, file_name="Game.03.p2s" ) + assert state is not None assert state.screenshot is not None assert state.screenshot.file_name == "Game.03.png" @@ -3813,6 +4911,7 @@ def test_store_state_asset_collision_keeps_disc_file_id_in_sync( ) ) updated = db_state_handler.get_state_by_id(existing.id) + assert updated is not None assert updated.disc_file_id == disc.id assert updated.file_size_bytes == 999 @@ -4034,10 +5133,11 @@ def test_resolve_save_archive_accepts_the_players_own_archive( archive = db_save_handler.add_save( _save_for(rom, admin_user, "Game [retroarch a].saves.zip", "retroarch", "h1") ) - resolved = saves.resolve_save_archive( + resolved, is_foreign = saves.resolve_save_archive( admin_user.id, rom, _resolved(_clearing_webstation(rom)), archive.id ) assert resolved.id == archive.id + assert is_foreign is False def test_resolve_save_archive_rejects_a_save_that_is_not_the_players( @@ -4077,10 +5177,11 @@ def test_resolve_save_archive_rejects_another_emulators_archive( other = db_save_handler.add_save( _save_for(rom, admin_user, "Game [pcsx2 a].saves.zip", "pcsx2", "h1") ) - with pytest.raises(HTTPException) as exc: - saves.resolve_save_archive( - admin_user.id, rom, _resolved(_clearing_webstation(rom)), other.id - ) + with patch("handler.streaming.saves.webstation.import_spec", return_value=None): + with pytest.raises(HTTPException) as exc: + saves.resolve_save_archive( + admin_user.id, rom, _resolved(_clearing_webstation(rom)), other.id + ) assert exc.value.status_code == 400 assert exc.value.detail == "Save was made by a different emulator" @@ -4090,10 +5191,11 @@ def test_resolve_save_archive_rejects_a_bare_save_file(rom: Rom, admin_user: Use loose = db_save_handler.add_save( _save_for(rom, admin_user, "Game.srm", "retroarch", "h1") ) - with pytest.raises(HTTPException) as exc: - saves.resolve_save_archive( - admin_user.id, rom, _resolved(_clearing_webstation(rom)), loose.id - ) + with patch("handler.streaming.saves.webstation.import_spec", return_value=None): + with pytest.raises(HTTPException) as exc: + saves.resolve_save_archive( + admin_user.id, rom, _resolved(_clearing_webstation(rom)), loose.id + ) assert exc.value.status_code == 400 assert exc.value.detail == "Save is not a restorable archive" @@ -4114,6 +5216,523 @@ def test_resolve_save_archive_rejects_a_pick_where_it_would_not_land( assert exc.value.detail == "This emulator always restores the newest save" +def test_resolve_save_archive_accepts_a_foreign_pick_the_broker_will_import( + rom: Rom, admin_user: User +): + """A pick that fails the native check is not turned away outright: it is + checked against the broker's own import-spec first.""" + other = db_save_handler.add_save( + _save_for(rom, admin_user, "Game [pcsx2 a].saves.zip", "pcsx2", "h1") + ) + spec = webstation.ImportSpec( + kinds=frozenset({"save"}), + state_channel="archive", + state_slot=0, + ) + with patch("handler.streaming.saves.webstation.import_spec", return_value=spec): + save, is_foreign = saves.resolve_save_archive( + admin_user.id, rom, _resolved(_clearing_webstation(rom)), other.id + ) + assert save.id == other.id + assert is_foreign is True + + +def test_resolve_save_archive_still_refuses_when_the_broker_has_no_import_spec( + rom: Rom, admin_user: User +): + other = db_save_handler.add_save( + _save_for(rom, admin_user, "Game [pcsx2 a].saves.zip", "pcsx2", "h1") + ) + with patch("handler.streaming.saves.webstation.import_spec", return_value=None): + with pytest.raises(HTTPException) as exc: + saves.resolve_save_archive( + admin_user.id, rom, _resolved(_clearing_webstation(rom)), other.id + ) + assert exc.value.status_code == 400 + assert exc.value.detail == "Save was made by a different emulator" + + +def test_resolve_resume_state_accepts_the_players_own_state(rom: Rom, admin_user: User): + state = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.01.p2s", "pcsx2") + ) + resolved, slot, is_foreign = states.resolve_resume_state( + admin_user.id, rom, _resolved(_webstation_for(rom)), state.id + ) + assert resolved.id == state.id + assert slot == 1 + assert is_foreign is False + + +def test_resolve_resume_state_rejects_a_state_that_is_not_visible( + rom: Rom, admin_user: User, viewer_user: User +): + state = db_state_handler.add_state( + _state_for(rom, viewer_user, "Game.01.p2s", "pcsx2") + ) + with pytest.raises(HTTPException) as exc: + states.resolve_resume_state( + admin_user.id, rom, _resolved(_webstation_for(rom)), state.id + ) + assert exc.value.status_code == 404 + + +def test_resolve_resume_state_accepts_a_foreign_pick_on_an_archive_channel( + rom: Rom, admin_user: User +): + """A pick from an emulator the container does not natively read is not + turned away: the broker's import-spec supplies the slot to resume from.""" + other = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.01.p2s", "pcsx2") + ) + spec = webstation.ImportSpec( + kinds=frozenset({"state"}), + state_channel="archive", + state_slot=2, + ) + with patch("handler.streaming.states.webstation.import_spec", return_value=spec): + resolved, slot, is_foreign = states.resolve_resume_state( + admin_user.id, rom, _resolved(_clearing_webstation(rom)), other.id + ) + assert resolved.id == other.id + assert slot == 2 + assert is_foreign is True + + +def test_resolve_resume_state_accepts_a_foreign_pick_on_a_push_channel( + rom: Rom, admin_user: User +): + other = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.01.p2s", "pcsx2") + ) + spec = webstation.ImportSpec( + kinds=frozenset({"state"}), + state_channel="push", + state_slot=1, + ) + with patch("handler.streaming.states.webstation.import_spec", return_value=spec): + resolved, slot, is_foreign = states.resolve_resume_state( + admin_user.id, rom, _resolved(_clearing_webstation(rom)), other.id + ) + assert slot == 1 + assert is_foreign is True + + +def test_resolve_resume_state_refuses_a_foreign_pick_when_the_channel_is_none( + rom: Rom, admin_user: User +): + other = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.01.p2s", "pcsx2") + ) + spec = webstation.ImportSpec( + kinds=frozenset(), state_channel="none", state_slot=None + ) + with patch("handler.streaming.states.webstation.import_spec", return_value=spec): + with pytest.raises(HTTPException) as exc: + states.resolve_resume_state( + admin_user.id, rom, _resolved(_clearing_webstation(rom)), other.id + ) + assert exc.value.status_code == 400 + assert exc.value.detail == "State was made by a different emulator" + + +def test_resolve_resume_state_rejects_an_unrecognized_slot_when_no_import_spec( + rom: Rom, admin_user: User +): + """A same-emulator state whose filename carries no slot, and no broker + import-spec to fall back on, is refused for its slot.""" + weird = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.state", "pcsx2") + ) + with patch("handler.streaming.states.webstation.import_spec", return_value=None): + with pytest.raises(HTTPException) as exc: + states.resolve_resume_state( + admin_user.id, rom, _resolved(_webstation_for(rom)), weird.id + ) + assert exc.value.status_code == 400 + assert exc.value.detail == "State filename carries no recognizable slot number" + + +def test_origin_of_tags_a_device_capture_as_hardware(): + assert imports.origin_of("retroarch", "device-123") == "hardware" + + +def test_origin_of_tags_an_untagged_save_as_unknown(): + assert imports.origin_of(None, None) == "unknown" + assert imports.origin_of("", None) == "unknown" + + +def test_origin_of_tags_a_streaming_emulator_as_standalone(): + assert imports.origin_of("retroarch", None) == "standalone" + + +def test_origin_of_tags_anything_else_as_emulatorjs(): + assert imports.origin_of("mgba-wasm", None) == "emulatorjs" + + +def test_build_import_archive_wraps_a_foreign_save_with_no_base(): + """A foreign save pick with no native base builds a fresh zip: no v1 + entries to carry over, one `.import/save/...` member.""" + member = imports.ForeignMember( + kind="save", name="Game.srm", content=b"save-bytes", origin="standalone" + ) + zip_bytes, _carried = imports.build_import_archive( + rom_id=7, base=None, members=[member] + ) + with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf: + names = zf.namelist() + assert ".import/save/Game.srm" in names + assert zf.read(".import/save/Game.srm") == b"save-bytes" + manifest = json.loads(zf.read(".broker-manifest.json")) + assert manifest["version"] == 2 + assert manifest["import"] == {"source": "romm", "rom_id": 7} + assert manifest["files"] == [ + {"path": ".import/save/Game.srm", "kind": "save", "origin": "standalone"} + ] + + +def test_build_import_archive_expands_a_foreign_zips_own_members(): + """A foreign pick that is itself a zip has its members unpacked under the + import prefix, not nested as a zip-within-zip.""" + from tests._zipfile_shim import reload_zipfile + + # zipfile-inflate64 in the import chain breaks writestr; restore stdlib first. + reload_zipfile() + inner = io.BytesIO() + with zipfile.ZipFile(inner, "w") as izf: + izf.writestr("save.mcr", b"card-bytes") + member = imports.ForeignMember( + kind="save", name="Game.saves.zip", content=inner.getvalue(), origin="hardware" + ) + zip_bytes, _carried = imports.build_import_archive( + rom_id=7, base=None, members=[member] + ) + with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf: + assert ".import/save/save.mcr" in zf.namelist() + assert zf.read(".import/save/save.mcr") == b"card-bytes" + + +def test_build_import_archive_keeps_a_native_base_alongside_a_foreign_state(): + """One native save and one foreign state in the same launch: the save + stays entirely on its own v1 entry, only the state gets an import + member. This is the mixed-kind case Appendix A(e) describes.""" + from tests._zipfile_shim import reload_zipfile + + # zipfile-inflate64 in the import chain breaks writestr; restore stdlib first. + reload_zipfile() + base_zip = io.BytesIO() + with zipfile.ZipFile(base_zip, "w") as bzf: + bzf.writestr("Game.srm", b"native-save-bytes") + bzf.writestr( + ".broker-manifest.json", + json.dumps({"version": 1, "files": [{"path": "Game.srm", "kind": "save"}]}), + ) + state_member = imports.ForeignMember( + kind="state", name="Game.00.pcsx2", content=b"state-bytes", origin="standalone" + ) + zip_bytes, _carried = imports.build_import_archive( + rom_id=7, base=("Game.saves.zip", base_zip.getvalue()), members=[state_member] + ) + with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf: + names = zf.namelist() + assert "Game.srm" in names + assert zf.read("Game.srm") == b"native-save-bytes" + assert ".import/state/Game.00.pcsx2" in names + manifest = json.loads(zf.read(".broker-manifest.json")) + assert manifest["version"] == 2 + paths = {f["path"] for f in manifest["files"]} + assert paths == {"Game.srm", ".import/state/Game.00.pcsx2"} + + +def test_build_import_archive_strips_the_bases_own_state_member_when_importing_a_foreign_state(): + """The base's own v1 state entry is stripped whenever a foreign state + rides in the same zip, so the two never collide on the emulator's one + state slot.""" + from tests._zipfile_shim import reload_zipfile + + # zipfile-inflate64 in the import chain breaks writestr; restore stdlib first. + reload_zipfile() + base_zip = io.BytesIO() + with zipfile.ZipFile(base_zip, "w") as bzf: + bzf.writestr("Game.srm", b"native-save-bytes") + bzf.writestr("Game.00.pcsx2", b"native-state-bytes") + bzf.writestr( + ".broker-manifest.json", + json.dumps( + { + "version": 1, + "files": [ + {"path": "Game.srm", "kind": "save"}, + {"path": "Game.00.pcsx2", "kind": "state"}, + ], + } + ), + ) + state_member = imports.ForeignMember( + kind="state", + name="Game.00.dolphin", + content=b"foreign-state", + origin="standalone", + ) + zip_bytes, _carried = imports.build_import_archive( + rom_id=7, base=("Game.saves.zip", base_zip.getvalue()), members=[state_member] + ) + with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf: + names = zf.namelist() + assert "Game.srm" in names + assert "Game.00.pcsx2" not in names + assert ".import/state/Game.00.dolphin" in names + + +def test_build_import_archive_leaves_a_foreign_save_archives_own_state_out(): + """Another emulator's save archive also carries its exit state, which a + save pick must not import as a save.""" + from tests._zipfile_shim import reload_zipfile + + reload_zipfile() + inner = io.BytesIO() + with zipfile.ZipFile(inner, "w") as izf: + izf.writestr("memcards/Game.mcd", b"card-bytes") + izf.writestr("savestates/Game.sav", b"state-bytes") + izf.writestr( + ".broker-manifest.json", + json.dumps( + { + "version": 1, + "files": [ + {"path": "memcards/Game.mcd", "kind": "save"}, + {"path": "savestates/Game.sav", "kind": "state"}, + ], + } + ), + ) + member = imports.ForeignMember( + kind="save", + name="Game [duckstation a].saves.zip", + content=inner.getvalue(), + origin="standalone", + ) + zip_bytes, _carried = imports.build_import_archive( + rom_id=7, base=None, members=[member] + ) + with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf: + names = zf.namelist() + assert ".import/save/memcards/Game.mcd" in names + assert not any(name.endswith("Game.sav") for name in names) + + +def test_build_import_archive_keeps_a_base_members_timestamp(): + from tests._zipfile_shim import reload_zipfile + + reload_zipfile() + base_zip = io.BytesIO() + with zipfile.ZipFile(base_zip, "w") as bzf: + bzf.writestr( + zipfile.ZipInfo("Game.srm", date_time=(2024, 1, 2, 3, 4, 6)), b"native" + ) + zip_bytes, _carried = imports.build_import_archive( + rom_id=7, + base=("Game.saves.zip", base_zip.getvalue()), + members=[ + imports.ForeignMember( + kind="state", name="Game.00.pcsx2", content=b"s", origin="standalone" + ) + ], + ) + with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf: + assert zf.getinfo("Game.srm").date_time == (2024, 1, 2, 3, 4, 6) + + +def test_build_import_archive_strips_dotfiles_and_macosx_junk(): + from tests._zipfile_shim import reload_zipfile + + # zipfile-inflate64 in the import chain breaks writestr; restore stdlib first. + reload_zipfile() + base_zip = io.BytesIO() + with zipfile.ZipFile(base_zip, "w") as bzf: + bzf.writestr("Game.srm", b"native-save-bytes") + bzf.writestr("__MACOSX/._Game.srm", b"junk") + bzf.writestr(".DS_Store", b"junk") + bzf.writestr( + ".broker-manifest.json", + json.dumps({"version": 1, "files": [{"path": "Game.srm", "kind": "save"}]}), + ) + zip_bytes, _carried = imports.build_import_archive( + rom_id=7, + base=("Game.saves.zip", base_zip.getvalue()), + members=[ + imports.ForeignMember( + kind="state", name="Game.00.pcsx2", content=b"s", origin="standalone" + ) + ], + ) + with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf: + names = zf.namelist() + assert not any( + "__MACOSX" in n + or n.split("/")[-1].startswith(".") + and n != ".broker-manifest.json" + for n in names + ) + + +def test_archive_budget_charges_bytes_and_members(): + budget = imports._ArchiveBudget(bytes_left=10, members_left=2) + budget.charge(4) + assert budget.bytes_left == 6 + assert budget.members_left == 1 + + +def test_archive_budget_raises_once_the_byte_budget_is_exceeded(): + budget = imports._ArchiveBudget(bytes_left=10, members_left=2000) + with pytest.raises(ValueError): + budget.charge(11) + + +def test_archive_budget_raises_once_the_member_budget_is_exceeded(): + budget = imports._ArchiveBudget(bytes_left=1_000_000, members_left=1) + budget.charge(1) + with pytest.raises(ValueError): + budget.charge(1) + + +def test_build_import_archive_rejects_a_foreign_member_over_the_expanded_byte_budget(): + """A member's own byte length is charged before it is staged, so an + oversized upload is rejected rather than fully expanded in memory.""" + member = imports.ForeignMember( + kind="save", name="Game.srm", content=b"x" * 10, origin="standalone" + ) + real_budget = imports._ArchiveBudget + with patch( + "handler.streaming.imports._ArchiveBudget", + lambda: real_budget(bytes_left=5, members_left=2000), + ): + with pytest.raises(ValueError): + imports.build_import_archive(rom_id=7, base=None, members=[member]) + + +def test_hydrate_import_archive_uploads_a_foreign_save_with_no_native_base( + rom: Rom, admin_user: User +): + save = db_save_handler.add_save( + _save_for(rom, admin_user, "Game [pcsx2 a].saves.zip", "pcsx2", "h1") + ) + upload = MagicMock(return_value="rom-1.zip") + with ( + patch( + "handler.streaming.imports.fs_asset_handler.read_file", + new=AsyncMock(return_value=b"picked-bytes"), + ), + patch("handler.streaming.imports.webstation.upload_archive", upload), + ): + result = asyncio.run( + imports.hydrate_import_archive( + admin_user.id, + rom, + _resolved(_clearing_webstation(rom)), + save=save, + save_is_foreign=True, + state=None, + ) + ) + assert result.path == "rom-1.zip" + assert result.state_imported is False + upload.assert_called_once() + uploaded_bytes = upload.call_args.args[2] + with zipfile.ZipFile(io.BytesIO(uploaded_bytes)) as zf: + assert f".import/save/{save.file_name}" in zf.namelist() + + +def test_hydrate_import_archive_falls_back_to_the_newest_native_save_as_base( + rom: Rom, admin_user: User +): + """A state-only foreign pick (no save_id) still carries the newest + native save as the base, as a launch with no pick does.""" + db_save_handler.add_save( + _save_for(rom, admin_user, "Game [retroarch a].saves.zip", "retroarch", "h1") + ) + state = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.00.pcsx2", "pcsx2") + ) + upload = MagicMock(return_value="rom-1.zip") + with ( + patch( + "handler.streaming.imports.fs_asset_handler.read_file", + new=AsyncMock(side_effect=lambda path: path.encode()), + ), + patch("handler.streaming.imports.webstation.upload_archive", upload), + ): + result = asyncio.run( + imports.hydrate_import_archive( + admin_user.id, + rom, + _resolved(_clearing_webstation(rom)), + save=None, + save_is_foreign=False, + state=state, + ) + ) + assert result.path == "rom-1.zip" + assert result.state_imported is True + uploaded_bytes = upload.call_args.args[2] + with zipfile.ZipFile(io.BytesIO(uploaded_bytes)) as zf: + assert ".import/state/Game.00.pcsx2" in zf.namelist() + + +def test_hydrate_import_archive_falls_through_when_the_only_foreign_read_fails( + rom: Rom, admin_user: User +): + """A native save plus a foreign state whose bytes are missing on disk: + there is nothing foreign to carry, so this must not upload a base-only + import archive. The caller falls back to ordinary save hydration.""" + save = db_save_handler.add_save( + _save_for(rom, admin_user, "Game [retroarch a].saves.zip", "retroarch", "h1") + ) + state = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.00.pcsx2", "pcsx2") + ) + upload = MagicMock(return_value="rom-1.zip") + with ( + patch( + "handler.streaming.imports.fs_asset_handler.read_file", + new=AsyncMock(side_effect=FileNotFoundError), + ), + patch("handler.streaming.imports.webstation.upload_archive", upload), + ): + result = asyncio.run( + imports.hydrate_import_archive( + admin_user.id, + rom, + _resolved(_clearing_webstation(rom)), + save=save, + save_is_foreign=False, + state=state, + ) + ) + assert result == imports.ImportHydration() + upload.assert_not_called() + + +def test_hydrate_import_archive_returns_none_when_nothing_is_foreign( + rom: Rom, admin_user: User +): + save = db_save_handler.add_save( + _save_for(rom, admin_user, "Game [retroarch a].saves.zip", "retroarch", "h1") + ) + result = asyncio.run( + imports.hydrate_import_archive( + admin_user.id, + rom, + _resolved(_clearing_webstation(rom)), + save=save, + save_is_foreign=False, + state=None, + ) + ) + assert result.path is None + assert result.state_imported is False + + def test_claim_hydrates_the_picked_save( client, access_token, rom: Rom, admin_user: User ): @@ -4140,6 +5759,172 @@ def test_claim_hydrates_the_picked_save( assert activate.call_args.kwargs["archive_path"] == "/config/picked.zip" +def test_claim_hydrates_a_foreign_save_through_the_import_path( + client, access_token, rom: Rom, admin_user: User +): + """A foreign save pick must be uploaded through imports.hydrate_import_archive, + not the native hydrate_saves_to_webstation path.""" + foreign = db_save_handler.add_save( + _save_for(rom, admin_user, "Game [pcsx2 a].saves.zip", "pcsx2", "h1") + ) + spec = webstation.ImportSpec( + kinds=frozenset({"save"}), + state_channel="archive", + state_slot=0, + ) + activate = MagicMock(return_value={"url": "/room/x"}) + hydrate_import = AsyncMock(return_value=imports.ImportHydration("rom-1.zip", False)) + with _streaming(_clearing_webstation(rom)): + with ( + patch("handler.streaming.webstation.activate", activate), + patch("handler.streaming.saves.webstation.import_spec", return_value=spec), + patch("endpoints.streaming.webstation.import_spec", return_value=spec), + patch("handler.streaming.imports.hydrate_import_archive", hydrate_import), + patch("handler.streaming.background.spawn_sync_task"), + patch("handler.streaming.states.hydrate_states_to_broker", new=MagicMock()), + ): + resp = _claim(client, access_token, rom.id, save_id=foreign.id) + assert resp.status_code == 202 + hydrate_import.assert_called_once() + call_kwargs = hydrate_import.call_args.kwargs + assert call_kwargs["save_is_foreign"] is True + assert call_kwargs["save"].id == foreign.id + + +def test_claim_hydrates_a_foreign_resume_state_through_the_import_path( + client, access_token, rom: Rom, admin_user: User +): + """A foreign resume pick must actually land in the uploaded archive, not + just be trusted to: this is what proves resume_via_import is only ever + set once the state import genuinely succeeded.""" + state = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.00.dolphin", "dolphin") + ) + spec = webstation.ImportSpec( + kinds=frozenset({"state"}), + state_channel="archive", + state_slot=0, + ) + activate = MagicMock(return_value={"url": "/room/x"}) + upload = MagicMock(return_value="rom-1.zip") + with _streaming(_clearing_webstation(rom)): + with ( + patch("handler.streaming.webstation.activate", activate), + patch("handler.streaming.states.webstation.import_spec", return_value=spec), + patch("endpoints.streaming.webstation.import_spec", return_value=spec), + patch( + "handler.streaming.imports.fs_asset_handler.read_file", + new=AsyncMock(side_effect=lambda path: path.encode()), + ), + patch("handler.streaming.imports.webstation.upload_archive", upload), + patch("handler.streaming.background.spawn_sync_task"), + ): + with _pushes() as sent: + r = _claim(client, access_token, rom.id, state_id=state.id) + assert r.status_code == 202 + upload.assert_called_once() + uploaded_bytes = upload.call_args.args[2] + with zipfile.ZipFile(io.BytesIO(uploaded_bytes)) as zf: + assert any(name.startswith(".import/state/") for name in zf.namelist()) + assert [event for event, _ in sent] == ["streaming:launch-ready"] + assert _launch_ready(sent)["resume"] is True + + +def test_a_missing_foreign_state_does_not_falsely_claim_resume_via_import( + client, access_token, rom: Rom, admin_user: User +): + """The foreign state's bytes are missing on disk, so the import archive + never actually carries it. the resume must not reach run_launch as + imported on the strength of the pre-win check alone, and the native save + hydration path must still get its turn.""" + state = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.00.dolphin", "dolphin") + ) + spec = webstation.ImportSpec( + kinds=frozenset({"state"}), + state_channel="archive", + state_slot=0, + ) + native_hydrate = AsyncMock(return_value=None) + run_launch_mock = AsyncMock() + with _streaming(_clearing_webstation(rom)): + with ( + patch("handler.streaming.states.webstation.import_spec", return_value=spec), + patch("endpoints.streaming.webstation.import_spec", return_value=spec), + patch( + "handler.streaming.imports.fs_asset_handler.read_file", + new=AsyncMock(side_effect=FileNotFoundError), + ), + patch( + "handler.streaming.saves.hydrate_saves_to_webstation", native_hydrate + ), + patch("handler.streaming.launch.run_launch", run_launch_mock), + ): + r = _claim(client, access_token, rom.id, state_id=state.id) + assert r.status_code == 202 + run_launch_mock.assert_called_once() + assert run_launch_mock.call_args.kwargs["resume_import"] == "lost" + native_hydrate.assert_called_once() + + +def test_claim_refuses_a_foreign_save_the_won_container_will_not_import( + client, access_token, rom: Rom, admin_user: User +): + """The won container's own import-spec decides: a pick it will not take is + refused and the claim released, never uploaded as a native archive.""" + foreign = db_save_handler.add_save( + _save_for(rom, admin_user, "Game [pcsx2 a].saves.zip", "pcsx2", "h1") + ) + spec = webstation.ImportSpec( + kinds=frozenset({"save"}), + state_channel="archive", + state_slot=0, + ) + native_hydrate = AsyncMock(return_value=None) + run_launch_mock = AsyncMock() + with _streaming(_clearing_webstation(rom)): + with ( + patch("handler.streaming.webstation.import_spec", side_effect=[spec, None]), + patch( + "handler.streaming.saves.hydrate_saves_to_webstation", native_hydrate + ), + patch("handler.streaming.launch.run_launch", run_launch_mock), + ): + r = _claim(client, access_token, rom.id, save_id=foreign.id) + assert _session_raw(_clearing_webstation(rom)) is None + assert r.status_code == 400 + native_hydrate.assert_not_called() + run_launch_mock.assert_not_called() + + +def test_claim_refuses_a_foreign_state_the_won_container_will_not_import( + client, access_token, rom: Rom, admin_user: User +): + """A foreign state the won container will not take must not fall through to + the native push, where the emulator would load another emulator's bytes.""" + state = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.00.dolphin", "dolphin") + ) + spec = webstation.ImportSpec( + kinds=frozenset({"state"}), + state_channel="archive", + state_slot=0, + ) + push = AsyncMock(return_value=True) + run_launch_mock = AsyncMock() + with _streaming(_clearing_webstation(rom)): + with ( + patch("handler.streaming.webstation.import_spec", side_effect=[spec, None]), + patch("handler.streaming.states.push_resume_state", push), + patch("handler.streaming.launch.run_launch", run_launch_mock), + ): + r = _claim(client, access_token, rom.id, state_id=state.id) + assert _session_raw(_clearing_webstation(rom)) is None + assert r.status_code == 400 + push.assert_not_called() + run_launch_mock.assert_not_called() + + def test_claim_with_an_unrestorable_pick_never_reserves_a_container( client, access_token, rom: Rom, admin_user: User ): @@ -4152,6 +5937,7 @@ def test_claim_with_an_unrestorable_pick_never_reserves_a_container( with _streaming(_clearing_webstation(rom)): with ( patch("handler.streaming.webstation.activate", activate), + patch("handler.streaming.saves.webstation.import_spec", return_value=None), _spawns_nothing(), ): refused = _claim(client, access_token, rom.id, save_id=loose.id) @@ -4184,24 +5970,874 @@ def test_claim_hydrates_saves_before_launch(client, access_token, rom: Rom): assert call_order == ["saves", "launch"] +def test_run_launch_sends_rom_identity_fields(rom: Rom, admin_user: User): + """The broker needs the ROM's identity triple to answer import-spec and + to fold a foreign pick's members against the right title.""" + rom.title_id = "SLUS-12345" + rom.save_target = "SLUS-12345" + rom.save_target_layout = SaveTargetLayout.FOLDER_EXACT + activate = MagicMock(return_value={"url": "/room/x"}) + session = {"broker_session_id": "s1", "claimed_at": "t1", "user_id": admin_user.id} + with ( + patch("handler.streaming.launch.webstation.activate", activate), + patch("handler.streaming.launch.lifecycle.hold_session_claim", new=AsyncMock()), + patch( + "handler.streaming.launch.lifecycle.publish_session_activity", + new=AsyncMock(), + ), + patch("handler.streaming.launch.stamp_launched", new=AsyncMock()), + patch("handler.streaming.launch.push_to_user", new=AsyncMock()), + patch("handler.streaming.launch.background.spawn_sync_task"), + patch( + "handler.streaming.launch.states.hydrate_states_to_broker", new=AsyncMock() + ), + ): + asyncio.run( + launch.run_launch( + container=_resolved(_webstation_for(rom)), + session_key="k1", + session=session, + user=admin_user, + rom=rom, + platform=rom.platform_slug, + rom_name=rom.name or rom.fs_name_no_ext, + rom_path="rom/path", + rom_language=None, + gui_language=None, + archive_path=None, + resume_state=None, + resume_slot=None, + resume_pushed=False, + resume_after_launch=False, + resume_import="none", + memory_card_synced=False, + multiplayer=False, + blank_card_id=None, + ) + ) + sent_rom = activate.call_args.kwargs["rom"] + assert sent_rom["title_id"] == "SLUS-12345" + assert sent_rom["save_target"] == "SLUS-12345" + assert sent_rom["save_target_layout"] == "folder-exact" + + +def test_run_launch_pushes_refusals_when_the_broker_refuses_an_import( + rom: Rom, admin_user: User +): + """An import refusal must reach the player's tabs as structured refusal + data, not just a flattened error string.""" + refusal = ImportRefusalSchema( + reason="shape_mismatch", + member=".import/save/Game.mcr", + expected="folder", + detail=None, + suggest_emulator=None, + docs=None, + ) + activate = MagicMock(side_effect=broker.ImportRefusedError([refusal], 2)) + session = {"broker_session_id": "s1", "claimed_at": "t1", "user_id": admin_user.id} + pushed = AsyncMock() + with ( + patch("handler.streaming.launch.webstation.activate", activate), + patch("handler.streaming.launch.lifecycle.hold_session_claim", new=AsyncMock()), + patch("handler.streaming.launch.lifecycle.abort_claim", new=AsyncMock()), + patch("handler.streaming.launch.push_to_user", pushed), + ): + asyncio.run( + launch.run_launch( + container=_resolved(_webstation_for(rom)), + session_key="k1", + session=session, + user=admin_user, + rom=rom, + platform=rom.platform_slug, + rom_name=rom.name or rom.fs_name_no_ext, + rom_path="rom/path", + rom_language=None, + gui_language=None, + archive_path=None, + resume_state=None, + resume_slot=None, + resume_pushed=False, + resume_after_launch=False, + resume_import="none", + memory_card_synced=False, + multiplayer=False, + blank_card_id=None, + ) + ) + payload = pushed.call_args.args[2] + assert payload["refusals"] == [ + { + "reason": "shape_mismatch", + "member": ".import/save/Game.mcr", + "expected": "folder", + "detail": None, + "suggest_emulator": None, + "docs": None, + } + ] + assert payload["refusals_truncated"] == 2 + assert "shape_mismatch" in payload["detail"] + + +def test_activate_refusal_frees_the_container_for_a_new_claim( + client, access_token, rom: Rom +): + """An import refusal at activate time must release the claim, not just + report it: a second claim on the same container has to succeed too, not + only see `streaming:launch-failed` and an emptied session record.""" + refusal = ImportRefusalSchema( + reason="shape_mismatch", + member=".import/save/Game.mcr", + expected="folder", + detail=None, + suggest_emulator=None, + docs=None, + ) + with _streaming(_webstation_for(rom)): + with ( + patch( + "handler.streaming.webstation.activate", + side_effect=broker.ImportRefusedError([refusal], 0), + ), + patch( + "handler.streaming.saves.hydrate_saves_to_webstation", new=AsyncMock() + ), + ): + with _pushes() as sent: + r = _claim(client, access_token, rom.id) + assert [event for event, _ in sent] == ["streaming:launch-failed"] + assert _session_raw(_webstation_for(rom)) is None + + with ( + patch( + "handler.streaming.webstation.activate", + return_value={"url": "/room/x"}, + ), + patch( + "handler.streaming.saves.hydrate_saves_to_webstation", new=AsyncMock() + ), + patch("handler.streaming.background.spawn_sync_task"), + ): + r2 = _claim(client, access_token, rom.id) + assert r.status_code == 202 + assert r2.status_code == 202 + assert _session_raw(_webstation_for(rom)) is not None + + +def test_run_launch_skips_the_state_push_when_resuming_via_import( + rom: Rom, admin_user: User +): + """A foreign state folded into the import archive must not also be + pushed through the ordinary state-file PUT.""" + state = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.00.dolphin", "dolphin") + ) + activate = MagicMock(return_value={"url": "/room/x"}) + session = {"broker_session_id": "s1", "claimed_at": "t1", "user_id": admin_user.id} + push_resume = AsyncMock() + with ( + patch("handler.streaming.launch.webstation.activate", activate), + patch("handler.streaming.launch.lifecycle.hold_session_claim", new=AsyncMock()), + patch( + "handler.streaming.launch.lifecycle.publish_session_activity", + new=AsyncMock(), + ), + patch("handler.streaming.launch.stamp_launched", new=AsyncMock()), + patch("handler.streaming.launch.push_to_user", new=AsyncMock()), + patch("handler.streaming.launch.background.spawn_sync_task"), + patch( + "handler.streaming.launch.states.hydrate_states_to_broker", new=AsyncMock() + ), + patch("handler.streaming.launch.states.push_resume_state", push_resume), + ): + asyncio.run( + launch.run_launch( + container=_resolved(_webstation_for(rom)), + session_key="k1", + session=session, + user=admin_user, + rom=rom, + platform=rom.platform_slug, + rom_name=rom.name or rom.fs_name_no_ext, + rom_path="rom/path", + rom_language=None, + gui_language=None, + archive_path="rom-1.zip", + resume_state=state, + resume_slot=0, + resume_pushed=False, + resume_after_launch=True, + resume_import="imported", + memory_card_synced=False, + multiplayer=False, + blank_card_id=None, + ) + ) + push_resume.assert_not_called() + + +def test_run_launch_sends_no_resume_slot_when_the_import_was_lost( + rom: Rom, admin_user: User +): + """A pick that never made it into its import archive must not have the + broker load that slot anyway, from whatever the archive does carry.""" + state = db_state_handler.add_state( + _state_for(rom, admin_user, "Game.00.dolphin", "dolphin") + ) + activate = MagicMock(return_value={"url": "/room/x"}) + session = {"broker_session_id": "s1", "claimed_at": "t1", "user_id": admin_user.id} + push_resume = AsyncMock() + with ( + patch("handler.streaming.launch.webstation.activate", activate), + patch("handler.streaming.launch.lifecycle.hold_session_claim", new=AsyncMock()), + patch( + "handler.streaming.launch.lifecycle.publish_session_activity", + new=AsyncMock(), + ), + patch("handler.streaming.launch.stamp_launched", new=AsyncMock()), + patch("handler.streaming.launch.background.spawn_sync_task"), + patch( + "handler.streaming.launch.states.hydrate_states_to_broker", new=AsyncMock() + ), + patch("handler.streaming.launch.states.push_resume_state", push_resume), + ): + with _pushes() as sent: + asyncio.run( + launch.run_launch( + container=_resolved(_webstation_for(rom)), + session_key="k1", + session=session, + user=admin_user, + rom=rom, + platform=rom.platform_slug, + rom_name=rom.name or rom.fs_name_no_ext, + rom_path="rom/path", + rom_language=None, + gui_language=None, + archive_path="rom-1.zip", + resume_state=state, + resume_slot=0, + resume_pushed=False, + resume_after_launch=True, + resume_import="lost", + memory_card_synced=False, + multiplayer=False, + blank_card_id=None, + ) + ) + assert activate.call_args.kwargs["resume_slot"] is None + push_resume.assert_not_called() + assert _launch_ready(sent)["resume"] is False + + def test_release_spawns_saves_pull(client, access_token, rom: Rom): """Releasing a session must schedule a background pull of in-game saves.""" with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with ( - patch("handler.streaming.commands.stop", return_value=None), + _stub_stop(), patch("handler.streaming.background.spawn_sync_task") as spawn, patch( - "handler.streaming.saves.pull_saves_to_library", new=MagicMock() + "handler.streaming.saves.pull_saves_to_library", + new_callable=AsyncMock, ) as pull, ): r = client.delete( f"/api/streaming/sessions/{rom.platform_slug}", headers=_auth(access_token), ) + spawn.assert_called_once() + asyncio.run(spawn.call_args[0][0]) assert r.status_code == 200 - spawn.assert_called_once() - assert pull.call_args[0][1] == rom.id + pull.assert_awaited_once() + assert pull.await_args_list[0].args[1] == rom.id + + +def test_a_claim_behind_an_exit_waits_for_that_exits_saves( + client, access_token, admin_user: User, rom: Rom +): + """Runs both ends for real: nothing else ties the key an exit marks to the + one the next claim waits on.""" + # Equal ids would let a claim that swaps them find the exit's key anyway. + if rom.id == admin_user.id: + rom = _rom_on("distinct_id") + order: list[str] = [] + real_wait = saves.wait_for_save_pull + + async def slow_pull(*args, **kwargs) -> bool: + await asyncio.sleep(saves._SAVE_PULL_POLL_SECONDS * 2) + order.append("filed") + return True + + async def hydrate(*args, **kwargs) -> bool: + order.append("hydrate") + return True + + async def wait_while_it_files(user_id: int, rom_id: int) -> bool: + filing = asyncio.ensure_future(spawn.call_args[0][0]) + done = await real_wait(user_id, rom_id, budget=5) + order.append("waited" if done else "gave up") + await filing + return done + + with ( + _streaming(_container_for(rom)), + patch("handler.streaming.saves.pull_saves_to_library", new=slow_pull), + ): + _claim_ok(client, access_token, rom.id) + with ( + _stub_stop(), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + with ( + patch( + "handler.streaming.saves.wait_for_save_pull", new=wait_while_it_files + ), + patch("handler.streaming.saves.hydrate_saves_to_broker", new=hydrate), + ): + r = _claim_ok(client, access_token, rom.id) + assert r.status_code == 202 + assert order == ["filed", "waited", "hydrate"] + + +async def _save_pull_pending(user_id: int, rom_id: int) -> bool: + """Whether a claim would wait on a save pull, read the way the claim reads it.""" + return not await saves.wait_for_save_pull(user_id, rom_id, budget=0) + + +def test_a_release_marks_its_save_pull_before_stopping_the_emulator( + client, access_token, admin_user: User, rom: Rom +): + """On a pool the player's next claim lands on a free sibling while this + container drains, so the pull has to be pending before the slow part.""" + head, tail = _pool_member(rom, 0), _pool_member(rom, 1) + at_stop: list[tuple[bool, bool]] = [] + + async def quiesce(container, session, *, save=True): + sibling_free = await session_store.get_live_session(_key_of(tail)) is None + at_stop.append((sibling_free, await _save_pull_pending(admin_user.id, rom.id))) + return commands.StopOutcome() + + with _streaming(head, tail): + _claim_ok(client, access_token, rom.id) + with ( + patch("handler.streaming.lifecycle.quiesce_container", new=quiesce), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + spawn.call_args[0][0].close() + assert r.status_code == 200 + assert at_stop == [(True, True)] + + +def test_an_abandoned_teardown_marks_its_save_pull_before_stopping_the_emulator( + client, access_token, admin_user: User, rom: Rom +): + container = _container_for(rom) + at_stop: list[bool] = [] + + async def quiesce(container, session, *, save=True): + at_stop.append(await _save_pull_pending(admin_user.id, rom.id)) + return commands.StopOutcome() + + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + session = json.loads(_session_raw(container)) + with ( + patch("handler.streaming.lifecycle.quiesce_container", new=quiesce), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + torn = asyncio.run( + lifecycle.teardown_abandoned_session( + _resolved(container), + _key_of(container), + session, + claimed_by=admin_user.id, + ) + ) + spawn.call_args[0][0].close() + assert torn is True + assert at_stop == [True] + + +def test_a_release_that_fails_before_its_pull_leaves_nothing_pending( + client, access_token, admin_user: User, rom: Rom +): + """Only a pull clears the mark, so a teardown that never gets to one has to, + or the player's next claim sits out the whole wait for nothing.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(side_effect=RuntimeError("broker gone")), + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + spawn.assert_not_called() + assert asyncio.run(_save_pull_pending(admin_user.id, rom.id)) is False + + +def test_an_abandoned_teardown_that_fails_before_its_pull_leaves_nothing_pending( + client, access_token, admin_user: User, rom: Rom +): + container = _container_for(rom) + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + session = json.loads(_session_raw(container)) + with ( + patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(side_effect=RuntimeError("broker gone")), + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + asyncio.run( + lifecycle.teardown_abandoned_session( + _resolved(container), + _key_of(container), + session, + claimed_by=admin_user.id, + ) + ) + spawn.assert_not_called() + assert asyncio.run(_save_pull_pending(admin_user.id, rom.id)) is False + + +def _run_exit_pulls(spawn: MagicMock) -> None: + """Run the save pulls a teardown spawned, and drop whatever else it did.""" + for spawned in (c.args[0] for c in spawn.call_args_list): + if spawned.cr_code.co_name == "pull_exit_saves": + asyncio.run(spawned) + else: + spawned.close() + + +def test_a_webstation_exit_that_changed_no_saves_lets_the_next_claim_straight_through( + client, access_token, rom: Rom, monkeypatch +): + """A webstation exit answers once the save dump is written, so its first + "nothing new" is final and retrying it only holds the next claim.""" + # Long enough that a single retry outlasts the claim's wait below. + monkeypatch.setattr(broker, "PULL_RETRY_DELAY", 1.0) + waited: list[bool] = [] + real_wait = saves.wait_for_save_pull + + async def wait_while_it_files(user_id: int, rom_id: int) -> bool: + filing = asyncio.ensure_future(pull) + waited.append(await real_wait(user_id, rom_id, budget=0.5)) + filing.cancel() + return waited[-1] + + with ( + _streaming(_webstation_for(rom)), + patch("handler.streaming.saves.fetch_save_archive", return_value=None), + ): + _claim_webstation_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.webstation.exit_session", + return_value={"state_saved": False, "state_slot": None}, + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + (pull,) = ( + c.args[0] + for c in spawn.call_args_list + if c.args[0].cr_code.co_name == "pull_exit_saves" + ) + with patch( + "handler.streaming.saves.wait_for_save_pull", new=wait_while_it_files + ): + r = _claim_webstation_ok(client, access_token, rom.id) + assert r.status_code == 202 + assert waited == [True] + + +def test_a_webstation_exit_that_never_answered_keeps_asking( + client, access_token, rom: Rom +): + """An exit that timed out or failed may still be writing the dump.""" + with _streaming(_webstation_for(rom)): + _claim_webstation_ok(client, access_token, rom.id) + with ( + patch("handler.streaming.webstation.exit_session", return_value=None), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + _run_exit_pulls(spawn) + assert fetch.call_count == broker.PULL_ATTEMPTS + + +@pytest.mark.parametrize( + ("exit_report", "wait", "attempts"), + [ + (None, True, broker.PULL_ATTEMPTS), + ({"state_saved": True, "state_slot": 10}, False, 1), + ({"state_saved": False, "state_slot": None}, True, 1), + ], +) +def test_a_webstation_save_and_exit_takes_one_answer_only_once_its_exit_answers( + client, + access_token, + rom: Rom, + exit_report: dict | None, + wait: bool, + attempts: int, +): + """This exit always blocks until the dump is written, whatever wait says, + but one that timed out or failed may still be writing it.""" + with _streaming(_webstation_for(rom)): + _claim_webstation_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.webstation.exit_session", return_value=exit_report + ), + patch( + "handler.streaming.states.pull_state_to_library", + new=AsyncMock(return_value=True), + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 0, "wait": wait}, + headers=_auth(access_token), + ) + _run_exit_pulls(spawn) + assert fetch.call_count == attempts + + +def test_a_release_keeps_asking_while_the_emulator_flushes( + client, access_token, rom: Rom +): + """A per-emulator broker acks the stop before the emulator has flushed its + saves, so an early "nothing new" is not the answer yet.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + _stub_stop(), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + _run_exit_pulls(spawn) + assert fetch.call_count == broker.PULL_ATTEMPTS + + +def test_an_abandoned_teardown_keeps_asking_while_the_emulator_flushes( + client, access_token, admin_user: User, rom: Rom +): + container = _container_for(rom) + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + session = json.loads(_session_raw(container)) + with ( + _stub_stop(), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + asyncio.run( + lifecycle.teardown_abandoned_session( + _resolved(container), + _key_of(container), + session, + claimed_by=admin_user.id, + ) + ) + _run_exit_pulls(spawn) + assert fetch.call_count == broker.PULL_ATTEMPTS + + +def test_a_force_release_keeps_asking_while_the_emulator_flushes( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + _stub_stop(), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.delete("/api/streaming/sessions", headers=_auth(access_token)) + _run_exit_pulls(spawn) + assert fetch.call_count == broker.PULL_ATTEMPTS + + +def _broker_saves(body: dict): + """A broker whose save-and-exit answers with `body`, and nothing else.""" + return lambda _container, path, *args, **kwargs: ( + body if path == "/save-and-exit" else None + ) + + +@pytest.mark.parametrize( + ("saved", "attempts"), [(True, 1), (False, broker.PULL_ATTEMPTS)] +) +def test_a_blocking_save_and_exit_takes_one_answer_only_once_the_broker_confirms( + client, access_token, rom: Rom, saved: bool, attempts: int +): + """A save-and-exit that timed out or failed may still be killing the + emulator, so only a confirmed one has finished writing.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.broker.request_safe", + side_effect=_broker_saves({"saved": saved, "slot": 10}), + ), + patch( + "handler.streaming.states.pull_state_to_library", + new=AsyncMock(return_value=True), + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + _run_exit_pulls(spawn) + assert fetch.call_count == attempts + + +def test_a_background_save_and_exit_keeps_asking_while_the_emulator_writes( + client, access_token, rom: Rom +): + """With wait=false the broker is still saving when the pull starts, so an + early "nothing new" is not the answer yet, even from a save it confirmed.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.broker.request_safe", + side_effect=_broker_saves({"saved": True, "slot": 10}), + ), + patch( + "handler.streaming.states.pull_state_to_library", + new=AsyncMock(return_value=True), + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 0, "wait": False}, + headers=_auth(access_token), + ) + _run_exit_pulls(spawn) + assert fetch.call_count == broker.PULL_ATTEMPTS + + +def test_save_and_exit_marks_the_save_pull_before_giving_up_the_key( + client, access_token, admin_user: User, rom: Rom +): + """With no state to wait on, the key is deleted outright, so a claim can win + it the moment it goes and has to find the pull already pending.""" + key = saves._save_pull_redis_key(admin_user.id, rom.id) + pending_at_release: list[int] = [] + real_release = streaming.release_own_session + + async def release_after_looking(*args, **kwargs): + pending_at_release.append(await async_cache.exists(key)) + return await real_release(*args, **kwargs) + + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), + ), + patch("handler.streaming.background.spawn_sync_task"), + patch.object(streaming, "release_own_session", release_after_looking), + ): + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + asyncio.run(async_cache.delete(key)) + assert r.status_code == 200 + assert pending_at_release == [1] + + +def test_a_claim_waits_for_a_running_save_pull(): + async def scenario() -> bool: + mark = await saves.mark_save_pull_pending(1, 2) + waiter = asyncio.create_task(saves.wait_for_save_pull(1, 2, budget=5)) + await asyncio.sleep(saves._SAVE_PULL_POLL_SECONDS * 2) + assert not waiter.done() + await saves.clear_save_pull_pending(mark) + return await waiter + + assert asyncio.run(scenario()) is True + + +def test_a_wedged_save_pull_does_not_hang_the_claim(): + """A claim is an interactive request: a pull that never finishes costs the + player the previous archive, not a claim that never answers.""" + + async def scenario() -> bool: + mark = await saves.mark_save_pull_pending(1, 2) + try: + return await saves.wait_for_save_pull(1, 2, budget=0.1) + finally: + await saves.clear_save_pull_pending(mark) + + assert asyncio.run(scenario()) is False + + +def test_a_claim_with_nothing_pending_hydrates_straight_away(): + assert asyncio.run(saves.wait_for_save_pull(1, 2, budget=5)) is True + + +def test_an_earlier_pull_finishing_leaves_a_later_exits_mark( + admin_user: User, rom: Rom +): + """A pull can outlast a claim's wait, so the player can play and exit again + while it runs, and its finishing must not let a claim past the later pull.""" + entry = _container_for(rom) + container = _resolved(entry) + session = {"user_id": admin_user.id, "rom_id": rom.id} + + async def scenario() -> tuple[bool, bool]: + with ( + _streaming(entry), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch("handler.streaming.saves.pull_saves_to_library", new=AsyncMock()), + ): + for _ in range(2): + mark = await lifecycle.mark_exit_saves_pending(container, session) + await lifecycle.collect_exit_saves( + container, session, mark, settled=False + ) + first, second = (c.args[0] for c in spawn.call_args_list) + await first + behind_second = await _save_pull_pending(admin_user.id, rom.id) + await second + return behind_second, await _save_pull_pending(admin_user.id, rom.id) + + assert asyncio.run(scenario()) == (True, False) + + +def test_an_exit_save_pull_runs_on_the_streaming_worker( + admin_user: User, rom: Rom, exit_pull_queue: MagicMock +): + """A web restart would otherwise cut a pull short and park the next claim.""" + container = _resolved(_container_for(rom)) + session = {"user_id": admin_user.id, "rom_id": rom.id, "broker_session_id": "b1"} + exit_pull_queue.enqueue.side_effect = None + + async def scenario() -> saves.SavePullMark | None: + mark = await lifecycle.mark_exit_saves_pending(container, session) + await lifecycle.collect_exit_saves(container, session, mark, settled=True) + return mark + + mark = asyncio.run(scenario()) + + assert mark is not None + (func,), kwargs = exit_pull_queue.enqueue.call_args + assert func is lifecycle.pull_exit_saves + assert kwargs["kwargs"] == { + "user_id": admin_user.id, + "rom_id": rom.id, + "token": mark.token, + "container_key": container.key, + "platform": container.platform, + "broker_session": "b1", + "settled": True, + } + assert kwargs["job_timeout"] == saves.SAVE_PULL_TTL_SECONDS + + +def test_a_pull_that_cannot_be_queued_lets_the_next_claim_through( + admin_user: User, rom: Rom, exit_pull_queue: MagicMock +): + container = _resolved(_container_for(rom)) + session = {"user_id": admin_user.id, "rom_id": rom.id} + exit_pull_queue.enqueue.side_effect = ConnectionError("redis went away") + + async def scenario() -> bool: + mark = await lifecycle.mark_exit_saves_pending(container, session) + await lifecycle.collect_exit_saves(container, session, mark, settled=False) + return await _save_pull_pending(admin_user.id, rom.id) + + assert asyncio.run(scenario()) is False + + +def test_a_queued_pull_for_a_container_no_longer_configured_clears_its_mark( + admin_user: User, rom: Rom +): + session = {"user_id": admin_user.id, "rom_id": rom.id} + + async def scenario() -> tuple[bool, AsyncMock]: + container = _resolved(_container_for(rom)) + mark = await lifecycle.mark_exit_saves_pending(container, session) + assert mark is not None + with ( + _streaming(), + patch( + "handler.streaming.saves.pull_saves_to_library", new=AsyncMock() + ) as pull, + ): + await lifecycle.pull_exit_saves( + user_id=mark.user_id, + rom_id=mark.rom_id, + token=mark.token, + container_key=container.key, + platform=container.platform, + broker_session=None, + settled=False, + ) + return await _save_pull_pending(admin_user.id, rom.id), pull + + pending, pull = asyncio.run(scenario()) + assert pending is False + pull.assert_not_awaited() # ── Resume-from-state ───────────────────────────────────────────────────────── @@ -4241,6 +6877,42 @@ def test_stamped_state_filename_round_trips_for_retroarch(): assert states.container_state_filename(stamped) == "Super Mario.state" +def test_exit_state_filenames_resolve_to_the_working_slot(): + """DuckStation and RPCS3 write one state per game, as they exit, with no + slot in its name, so the working slot is the only one a pick can mean.""" + assert states.slot_from_state_filename("duckstation", "SLUS-00594_resume.sav") == 0 + assert states.slot_from_state_filename("duckstation", "SLUS-00594.mcd") is None + assert states.slot_from_state_filename("rpcs3", "BLUS30443_1.SAVESTAT") == 0 + assert states.slot_from_state_filename("rpcs3", "BLUS30443_1.SAVESTAT.zst") == 0 + assert states.slot_from_state_filename("rpcs3", "BLUS30443_1.SAVESTAT.gz") == 0 + assert states.slot_from_state_filename("rpcs3", "PARAM.SFO") is None + + +@pytest.mark.parametrize( + ("emulator", "name", "shape"), + [ + ( + "duckstation", + "SLUS-00594_resume.sav", + r"SLUS-00594_resume\.\d{8}-\d{12}\.sav", + ), + ( + "rpcs3", + "BLUS30443_1.SAVESTAT.zst", + r"BLUS30443_1\.\d{8}-\d{12}\.SAVESTAT\.zst", + ), + ], +) +def test_stamped_exit_state_filename_round_trips(emulator, name, shape): + """Every exit is its own library entry, and the stamped name still resolves + a slot: otherwise the entries the stamp creates could never be picked.""" + when = datetime(2026, 7, 21, 4, 56, 45, 123456, tzinfo=timezone.utc) + stamped = states.stamped_state_filename(emulator, name, when) + assert re.fullmatch(shape, stamped) + assert states.container_state_filename(stamped) == name + assert states.slot_from_state_filename(emulator, stamped) == 0 + + class _ResumeClaim(NamedTuple): response: httpx.Response ready: dict[str, Any] @@ -4329,7 +7001,8 @@ def test_claim_with_wrong_emulator_state_400( state = db_state_handler.add_state( _state_for(rom, admin_user, "Game.state", "retroarch") ) - r = _resume_claim(client, access_token, rom, state.id).response + with patch("handler.streaming.states.webstation.import_spec", return_value=None): + r = _resume_claim(client, access_token, rom, state.id).response assert r.status_code == 400 @@ -4337,7 +7010,8 @@ def test_claim_with_unparseable_slot_400( client, access_token, rom: Rom, admin_user: User ): state = db_state_handler.add_state(_state_for(rom, admin_user, "Game.p2s", "pcsx2")) - r = _resume_claim(client, access_token, rom, state.id).response + with patch("handler.streaming.states.webstation.import_spec", return_value=None): + r = _resume_claim(client, access_token, rom, state.id).response assert r.status_code == 400 @@ -4467,6 +7141,275 @@ def test_webstation_resume_state_is_pushed_after_activate( assert order.push.call_args[0][1] == "Game.03.p2s" +@pytest.mark.parametrize( + ("emulator", "name"), + [ + ("duckstation", "SLUS-00594_resume.20260918-010000000000.sav"), + ("rpcs3", "BLUS30443_1.20260918-010000000000.SAVESTAT"), + ], +) +def test_an_exit_state_resume_is_the_activate_slot_alone( + client, access_token, rom: Rom, admin_user: User, emulator, name +): + """These brokers refuse a state file mid-session and resume from the exit + state the save archive brings back, so the slot on the activate is the whole + resume. A push would only be refused and report the resume as lost.""" + state = db_state_handler.add_state(_state_for(rom, admin_user, name, emulator)) + activate = MagicMock(return_value={"url": "/room/x"}) + push = MagicMock(return_value=False) + with _streaming({**_webstation_for(rom), "emulator": emulator}): + with ( + patch("handler.streaming.webstation.activate", activate), + patch("handler.streaming.states.push_state_file", push), + patch( + "handler.streaming.saves.hydrate_saves_to_webstation", + new=AsyncMock(return_value="/romm/saves/archive.tar"), + ), + patch( + "handler.filesystem.fs_asset_handler.read_file", + new=AsyncMock(return_value=b"state-bytes"), + ), + patch("handler.streaming.background.spawn_sync_task"), + patch( + "handler.streaming.states.hydrate_states_to_broker", new=MagicMock() + ) as hydrate, + ): + with _pushes() as sent: + r = _claim(client, access_token, rom.id, state_id=state.id) + assert r.status_code == 202 + assert activate.call_args.kwargs["resume_slot"] == 0 + push.assert_not_called() + assert _launch_ready(sent)["resume"] is True + assert hydrate.call_args.kwargs["resume_pushed"] is True + + +@pytest.mark.parametrize( + ("emulator", "older_name", "newer_name"), + [ + ( + "duckstation", + "SLUS-00594_resume.20260917-010000000000.sav", + "SLUS-00594_resume.20260918-010000000000.sav", + ), + ( + "rpcs3", + "BLUS30443_1.20260917-010000000000.SAVESTAT", + "BLUS30443_1.20260918-010000000000.SAVESTAT", + ), + ], +) +def test_an_older_exit_state_resume_rides_the_import_archive( + client, access_token, rom: Rom, admin_user: User, emulator, older_name, newer_name +): + """Picking anything but the newest capture on one of these containers must + still reach the game: the save archive on its own only ever carries the + newest exit state, so an older pick needs the import channel or it is + silently swapped for a state the player never chose.""" + older = db_state_handler.add_state( + _state_for(rom, admin_user, older_name, emulator) + ) + db_state_handler.add_state(_state_for(rom, admin_user, newer_name, emulator)) + activate = MagicMock(return_value={"url": "/room/x"}) + upload = MagicMock(return_value="rom-1.zip") + spec = webstation.ImportSpec( + kinds=frozenset({"state"}), + state_channel="archive", + state_slot=0, + ) + with _streaming({**_webstation_for(rom), "emulator": emulator}): + with ( + patch("handler.streaming.webstation.activate", activate), + patch("handler.streaming.webstation.import_spec", return_value=spec), + patch( + "handler.streaming.imports.fs_asset_handler.read_file", + new=AsyncMock(side_effect=lambda path: path.encode()), + ), + patch("handler.streaming.imports.webstation.upload_archive", upload), + patch("handler.streaming.background.spawn_sync_task"), + ): + with _pushes() as sent: + r = _claim(client, access_token, rom.id, state_id=older.id) + assert r.status_code == 202 + upload.assert_called_once() + uploaded_bytes = upload.call_args.args[2] + with zipfile.ZipFile(io.BytesIO(uploaded_bytes)) as zf: + assert any(name.startswith(".import/state/") for name in zf.namelist()) + assert _launch_ready(sent)["resume"] is True + + +def test_an_older_exit_state_stays_off_the_import_path_without_broker_support( + client, access_token, rom: Rom, admin_user: User +): + """A broker that predates imports would never place an `.import/` member, + so the archive goes out untouched and the resume is reported lost rather + than claiming the archive's own exit state was the pick.""" + older = db_state_handler.add_state( + _state_for( + rom, + admin_user, + "SLUS-00594_resume.20260917-010000000000.sav", + "duckstation", + ) + ) + db_state_handler.add_state( + _state_for( + rom, + admin_user, + "SLUS-00594_resume.20260918-010000000000.sav", + "duckstation", + ) + ) + hydrate_import = AsyncMock() + run_launch_mock = AsyncMock() + with _streaming({**_webstation_for(rom), "emulator": "duckstation"}): + with ( + patch("handler.streaming.webstation.import_spec", return_value=None), + patch("handler.streaming.imports.hydrate_import_archive", hydrate_import), + patch( + "handler.streaming.saves.hydrate_saves_to_webstation", + new=AsyncMock(return_value="/romm/saves/archive.zip"), + ), + patch("handler.streaming.launch.run_launch", run_launch_mock), + ): + r = _claim(client, access_token, rom.id, state_id=older.id) + assert r.status_code == 202 + hydrate_import.assert_not_called() + assert run_launch_mock.call_args.kwargs["resume_import"] == "lost" + assert run_launch_mock.call_args.kwargs["archive_path"] == "/romm/saves/archive.zip" + + +def _duckstation_pairing(rom: Rom, user: User) -> tuple[Save, Save, State]: + """An older and a newer DuckStation archive, plus the newest capture.""" + older, newer = ( + db_save_handler.add_save( + _save_for( + rom, user, f"Game [duckstation {tag}].saves.zip", "duckstation", tag + ) + ) + for tag in ("a", "b") + ) + state = db_state_handler.add_state( + _state_for(rom, user, "SLUS-00594_resume.sav", "duckstation") + ) + return older, newer, state + + +def _clearing_duckstation(rom: Rom) -> dict: + return { + **_webstation_for(rom), + "emulator": "duckstation", + "clears_stale_saves": True, + } + + +def test_an_older_save_with_the_newest_state_imports_the_picked_state( + client, access_token, rom: Rom, admin_user: User +): + """The older archive only carries its own exit state, so the picked state + rides the import archive on top of it instead of being silently swapped.""" + older, _, state = _duckstation_pairing(rom, admin_user) + activate = MagicMock(return_value={"url": "/room/x"}) + upload = MagicMock(return_value="rom-1.zip") + spec = webstation.ImportSpec( + kinds=frozenset({"state"}), state_channel="archive", state_slot=0 + ) + with _streaming(_clearing_duckstation(rom)): + with ( + patch("handler.streaming.webstation.activate", activate), + patch("handler.streaming.webstation.import_spec", return_value=spec), + patch( + "handler.streaming.imports.fs_asset_handler.read_file", + new=AsyncMock(side_effect=lambda path: path.encode()), + ), + patch("handler.streaming.imports.webstation.upload_archive", upload), + patch("handler.streaming.background.spawn_sync_task"), + ): + with _pushes() as sent: + r = _claim( + client, access_token, rom.id, state_id=state.id, save_id=older.id + ) + assert r.status_code == 202 + with zipfile.ZipFile(io.BytesIO(upload.call_args.args[2])) as zf: + assert any(name.startswith(".import/state/") for name in zf.namelist()) + assert _launch_ready(sent)["resume"] is True + + +def test_an_older_save_with_the_newest_state_reports_the_resume_lost_without_imports( + client, access_token, rom: Rom, admin_user: User +): + """Without an import channel the older archive's own exit state would load, + so the launch must not report the picked state as resumed.""" + older, _, state = _duckstation_pairing(rom, admin_user) + run_launch_mock = AsyncMock() + with _streaming(_clearing_duckstation(rom)): + with ( + patch("handler.streaming.webstation.import_spec", return_value=None), + patch( + "handler.streaming.saves.hydrate_saves_to_webstation", + new=AsyncMock(return_value="/romm/saves/archive.zip"), + ), + patch("handler.streaming.launch.run_launch", run_launch_mock), + ): + r = _claim( + client, access_token, rom.id, state_id=state.id, save_id=older.id + ) + assert r.status_code == 202 + assert run_launch_mock.call_args.kwargs["resume_import"] == "lost" + + +def test_the_newest_save_with_the_newest_state_resumes_from_the_archive( + client, access_token, rom: Rom, admin_user: User +): + """Naming the newest archive explicitly is the default pairing, so the + archive's own exit state is the pick and nothing is imported.""" + _, newer, state = _duckstation_pairing(rom, admin_user) + hydrate_import = AsyncMock() + run_launch_mock = AsyncMock() + with _streaming(_clearing_duckstation(rom)): + with ( + patch("handler.streaming.webstation.import_spec") as spec, + patch("handler.streaming.imports.hydrate_import_archive", hydrate_import), + patch( + "handler.streaming.saves.hydrate_saves_to_webstation", + new=AsyncMock(return_value="/romm/saves/archive.zip"), + ), + patch("handler.streaming.launch.run_launch", run_launch_mock), + ): + r = _claim( + client, access_token, rom.id, state_id=state.id, save_id=newer.id + ) + assert r.status_code == 202 + spec.assert_not_called() + hydrate_import.assert_not_called() + assert run_launch_mock.call_args.kwargs["resume_import"] == "none" + + +def test_an_exit_state_resume_with_no_archive_reports_the_resume_lost( + client, access_token, rom: Rom, admin_user: User +): + """The archive is the whole resume on these brokers, so without one the slot + would load whatever the container last held and the player would not be told.""" + state = db_state_handler.add_state( + _state_for(rom, admin_user, "SLUS-00594_resume.sav", "duckstation") + ) + activate = MagicMock(return_value={"url": "/room/x"}) + with _streaming({**_webstation_for(rom), "emulator": "duckstation"}): + with ( + patch("handler.streaming.webstation.activate", activate), + patch( + "handler.streaming.saves.hydrate_saves_to_webstation", + new=AsyncMock(return_value=None), + ), + patch("handler.streaming.background.spawn_sync_task"), + patch("handler.streaming.states.hydrate_states_to_broker", new=MagicMock()), + ): + with _pushes() as sent: + r = _claim(client, access_token, rom.id, state_id=state.id) + assert r.status_code == 202 + assert activate.call_args.kwargs["resume_slot"] is None + assert _launch_ready(sent)["resume"] is False + + def test_webstation_claim_without_a_state_boots_clean(client, access_token, rom: Rom): """A restored archive puts in-game saves back, nothing more: no picked state means no resume_slot, even though the archive carries the exit @@ -4496,14 +7439,14 @@ def test_stopping_a_webstation_broker_reports_the_state_it_captured(rom: Rom): "handler.streaming.webstation.exit_session", return_value={"state_saved": True, "state_slot": 10}, ): - assert commands.stop(_resolved(container)) == 10 + assert commands.stop(_resolved(container)) == (10, True) with patch( "handler.streaming.webstation.exit_session", return_value={"state_saved": False, "state_slot": 10}, ): - assert commands.stop(_resolved(container)) is None + assert commands.stop(_resolved(container)) == (None, True) with patch("handler.streaming.webstation.exit_session", return_value=None): - assert commands.stop(_resolved(container)) is None + assert commands.stop(_resolved(container)) == (None, False) def test_stopping_without_saving_asks_the_broker_to_write_no_state(rom: Rom): @@ -4514,7 +7457,7 @@ def test_stopping_without_saving_asks_the_broker_to_write_no_state(rom: Rom): "handler.streaming.webstation.exit_session", return_value={"state_saved": False, "state_slot": None}, ) as exit_call: - assert commands.stop(_resolved(container), save=False) is None + assert commands.stop(_resolved(container), save=False).state_slot is None assert exit_call.call_args.kwargs["save"] is False @@ -4533,7 +7476,7 @@ def test_a_webstation_exit_carries_slot_zero_rather_than_dropping_it(rom: Rom): def test_stopping_a_legacy_broker_reports_no_state(rom: Rom): """The per-emulator brokers stop without saving, so nothing is pulled.""" with patch("handler.streaming.broker.request_safe", return_value={}): - assert commands.stop(_resolved(_container_for(rom))) is None + assert commands.stop(_resolved(_container_for(rom))) == (None, False) def test_releasing_a_webstation_session_pulls_the_exit_state( @@ -4579,7 +7522,7 @@ def test_releasing_without_saving_files_no_state(client, access_token, rom: Rom) """The stop button is the deliberate way out without saving, so the exit writes nothing and there is no state to pull into the library.""" pull = AsyncMock(return_value=True) - stop = MagicMock(return_value=None) + stop = MagicMock(return_value=commands.StopOutcome()) with _streaming(_webstation_for(rom)): with ( patch( @@ -4656,7 +7599,7 @@ def test_admin_can_release_other_users_session( """An admin may release a session claimed by someone else.""" with _streaming(_container_for(rom)): _claim_ok(client, viewer_access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None) as stop: + with _stub_stop() as stop: r = client.delete( f"/api/streaming/sessions/{rom.platform_slug}", headers=_auth(access_token), @@ -4852,7 +7795,9 @@ def test_store_memory_card_version_stores_new(admin_user: User): ) assert stored is not None wf.assert_awaited_once() - assert db_memory_card_handler.get_latest_version(card.id).content_hash == "hash-new" + latest = db_memory_card_handler.get_latest_version(card.id) + assert latest is not None + assert latest.content_hash == "hash-new" def test_store_memory_card_version_dedups_identical(admin_user: User): @@ -4944,6 +7889,46 @@ def _http_error(code: int, headers: dict[str, str] | None = None): return urllib.error.HTTPError("http://broker/memory-card", code, "err", hdrs, None) +def test_raise_http_error_raises_import_refused_as_a_typed_error(): + """A refused import must reach the caller as structured data, not folded + into the generic 502 string every other broker error becomes.""" + payload = json.dumps( + { + "detail": { + "error": "import_refused", + "refusals": [ + { + "reason": "shape_mismatch", + "member": ".import/save/Game.mcr", + "expected": "folder", + "detail": "wanted a directory member", + "suggest_emulator": None, + "docs": None, + } + ], + "truncated": 0, + } + } + ).encode() + exc = _http_error(422) + with patch.object(exc, "read", return_value=payload): + with pytest.raises(broker.ImportRefusedError) as raised: + broker.raise_http_error(exc) + assert raised.value.truncated == 0 + assert len(raised.value.refusals) == 1 + assert raised.value.refusals[0].reason == "shape_mismatch" + assert raised.value.refusals[0].member == ".import/save/Game.mcr" + + +def test_raise_http_error_still_raises_502_for_a_plain_broker_error(): + """An ordinary broker error (not an import refusal) is still a plain 502.""" + exc = _http_error(500) + with patch.object(exc, "read", return_value=b"boom"): + with pytest.raises(HTTPException) as raised: + broker.raise_http_error(exc) + assert raised.value.status_code == 502 + + def test_fetch_memory_card_returns_bytes(rom: Rom): resp = MagicMock() resp.__enter__.return_value.read.side_effect = _reads(b"card-bytes") @@ -4991,6 +7976,85 @@ def test_fetch_memory_card_transport_error_raises(rom: Rom): memory_cards.fetch_card(_resolved(_mc_container_for(rom))) +def test_import_spec_parses_the_brokers_discovery_response(rom: Rom): + body = json.dumps( + { + "import_api": 1, + "manifest_version": 2, + "kinds": [ + { + "kind": "save", + "shapes": ["folder"], + "requires_resume_slot": False, + "max_members": 8, + }, + { + "kind": "state", + "shapes": ["file"], + "requires_resume_slot": True, + "max_members": 1, + }, + ], + "state_channel": "archive", + "state_slot": 0, + } + ).encode() + resp = MagicMock() + resp.__enter__.return_value.read.side_effect = _reads(body) + resp.__enter__.return_value.status = 200 + with patch("handler.streaming.broker.urllib.request.urlopen", return_value=resp): + spec = webstation.import_spec( + _resolved(_webstation_for(rom)), "dolphin", rom.platform_slug + ) + assert spec is not None + assert spec.state_channel == "archive" + assert spec.state_slot == 0 + assert spec.accepts("save") + assert spec.accepts("state") + assert not spec.accepts("memcard") + + +def test_import_spec_returns_none_and_caches_on_404(rom: Rom): + """A broker that predates imports answers 404; that answer is stable for + the worker's life, so it is cached rather than re-checked every claim.""" + container = _resolved(_webstation_for(rom)) + with patch( + "handler.streaming.broker.urllib.request.urlopen", + side_effect=_http_error(404), + ) as urlopen: + first = webstation.import_spec(container, "dolphin", rom.platform_slug) + second = webstation.import_spec(container, "dolphin", rom.platform_slug) + assert first is None + assert second is None + assert urlopen.call_count == 1 + + +def test_import_spec_never_asks_a_legacy_broker(rom: Rom): + """Declared imports are a webstation contract; a per-emulator broker is + never asked, so a foreign pick there is refused without a round trip.""" + with patch("handler.streaming.broker.urllib.request.urlopen") as urlopen: + spec = webstation.import_spec( + _resolved(_container_for(rom)), "pcsx2", rom.platform_slug + ) + assert spec is None + urlopen.assert_not_called() + + +def test_import_spec_returns_none_uncached_on_a_transient_failure(rom: Rom): + """A network blip is not the same stable answer a 404/422 is, so it must + never be cached (a future call should try again).""" + container = _resolved(_webstation_for(rom)) + with patch( + "handler.streaming.broker.urllib.request.urlopen", + side_effect=OSError("unreachable"), + ) as urlopen: + first = webstation.import_spec(container, "dolphin", rom.platform_slug) + second = webstation.import_spec(container, "dolphin", rom.platform_slug) + assert first is None + assert second is None + assert urlopen.call_count == 2 + + def test_claim_hydrates_memory_card_before_launch(client, access_token, rom: Rom): """On a sync container the whole card hydrates before launch, and the legacy per-file save path is skipped.""" @@ -5064,7 +8128,10 @@ def test_save_and_exit_evacuates_card(client, access_token, rom: Rom): ): _mc_claim(client, access_token, rom.id) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(True, 1)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 1, True), + ), patch( "handler.streaming.memory_cards.evacuate_card", new=AsyncMock(return_value=True), @@ -5101,7 +8168,7 @@ def test_release_evacuates_card(client, access_token, rom: Rom): ): _mc_claim(client, access_token, rom.id) with ( - patch("handler.streaming.commands.stop", return_value=None) as stop, + _stub_stop() as stop, patch( "handler.streaming.memory_cards.evacuate_card", new=AsyncMock(return_value=True), @@ -5141,7 +8208,7 @@ def test_release_frees_the_claim_when_teardown_raises(client, access_token, rom: ): _mc_claim(client, access_token, rom.id) with ( - patch("handler.streaming.commands.stop", return_value=None), + _stub_stop(), patch( "handler.streaming.memory_cards.evacuate_session_card", new=AsyncMock(side_effect=OSError("broker went away")), @@ -5174,7 +8241,8 @@ def test_save_and_exit_wait_false_forces_blocking_on_card_sync( _mc_claim(client, access_token, rom.id) with ( patch( - "handler.streaming.commands.save_and_exit", return_value=(True, 1) + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 1, True), ) as save, patch( "handler.streaming.memory_cards.evacuate_card", @@ -5690,7 +8758,9 @@ def test_concurrent_adopts_record_one_decision(admin_user: User, rom: Rom): ) assert first is not None assert second is None - assert db_container_adoption_handler.get_adoption(key).outcome == "adopt" + adoption = db_container_adoption_handler.get_adoption(key) + assert adoption is not None + assert adoption.outcome == "adopt" # ── Playtime ────────────────────────────────────────────────────────────────── @@ -5767,7 +8837,7 @@ def test_releasing_a_session_takes_it_off_the_activity_board( container = _container_for(rom) with _streaming(container): _claim_ok(client, access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): r = client.delete( f"/api/streaming/sessions/{rom.platform_slug}", headers=_auth(access_token), @@ -6107,6 +9177,19 @@ def test_joinable_hides_a_solo_session( assert body["sessions"] == [] +def test_joinable_skips_the_rom_lookup_for_a_session_nobody_may_join( + client, access_token, viewer_access_token, rom: Rom +): + """Home polls this listing, and most live sessions are solo.""" + container = {"host": "http://192.168.1.10:3000", "platform": rom.platform_slug} + with _streaming(container): + _claim_ok(client, access_token, rom.id) + with patch("handler.streaming.access.session_rom") as lookup: + _joinable(client, viewer_access_token) + + lookup.assert_not_called() + + def test_joinable_hides_a_session_nobody_could_join( client, access_token, viewer_access_token, rom: Rom ): @@ -6240,6 +9323,116 @@ def test_joining_a_rom_on_a_hidden_platform_is_404_masked( join_broker.assert_not_called() +def _ws_pool_member(rom: Rom, index: int, **overrides) -> dict: + """One member of a pool of webstation containers, the broker a joiner needs, + on a distinct host so the room URL says which member answered.""" + return _webstation( + **{ + "host": f"http://192.168.1.1{index}:3000", + "broker_host": f"http://192.168.1.1{index}:8000", + "platforms": {rom.platform_slug: "pcsx2"}, + **overrides, + } + ) + + +def _joined_room(url: str = "/webstation/?token=abc"): + return patch("handler.streaming.webstation.join", return_value={"url": url}) + + +def test_joining_walks_past_a_session_whose_rom_is_hidden( + client, + access_token, + editor_access_token, + viewer_access_token, + viewer_user: User, + rom: Rom, + second_rom: Rom, +): + """A hidden ROM earlier in the pool is not the caller's answer, so it must + not mask the joinable session behind it.""" + _hide(PermEntity.ROMS, rom.id, viewer_user.id) + with _streaming(_ws_pool_member(rom, 0), _ws_pool_member(rom, 1)): + _claim_multiplayer(client, access_token, rom.id) + _claim_multiplayer(client, editor_access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + +def test_joining_walks_past_the_callers_own_session( + client, access_token, viewer_access_token, rom: Rom, second_rom: Rom +): + """Joining is for somebody else's game: the caller's own session is the one + they already hold, and the listing leaves it out for the same reason.""" + with _streaming(_ws_pool_member(rom, 0), _ws_pool_member(rom, 1)): + _claim_multiplayer(client, viewer_access_token, rom.id) + _claim_multiplayer(client, access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + +def test_joining_walks_past_a_session_on_another_platform( + client, + access_token, + editor_access_token, + viewer_access_token, + rom: Rom, + second_rom: Rom, +): + """A container serves several platforms and holds one session, so a member + busy with another platform is not this platform's session to join.""" + member = _ws_pool_member( + rom, 0, platforms={rom.platform_slug: "pcsx2", "ngc": "dolphin"} + ) + with _streaming(member, _ws_pool_member(rom, 1)): + _claim_multiplayer(client, access_token, rom.id) + key = session_store.session_redis_key(_key_of(member)) + raw = asyncio.run(async_cache.get(key)) + assert raw is not None + session = json.loads(raw) + session["platform"] = "ngc" + asyncio.run(async_cache.set(key, json.dumps(session))) + _claim_multiplayer(client, editor_access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + +def test_joining_a_named_container_busy_with_another_platform_is_a_404( + client, access_token, viewer_access_token, rom: Rom +): + """Naming the container skips the walk, not its platform check: the game there + now may be another platform's, never the one the caller asked to join.""" + member = _ws_pool_member( + rom, 0, platforms={rom.platform_slug: "pcsx2", "ngc": "dolphin"} + ) + with _streaming(member): + _claim_multiplayer(client, access_token, rom.id) + key = session_store.session_redis_key(_key_of(member)) + raw = asyncio.run(async_cache.get(key)) + assert raw is not None + session = json.loads(raw) + session["platform"] = "ngc" + asyncio.run(async_cache.set(key, json.dumps(session))) + with _joined_room(): + r = _join( + client, + viewer_access_token, + rom.platform_slug, + container=_key_of(member), + ) + + assert r.status_code == 404 + + def test_joining_a_solo_session_finds_nothing_to_join( client, access_token, viewer_access_token, rom: Rom ): @@ -6314,7 +9507,7 @@ def test_joining_requires_auth(client, rom: Rom): def _expand(entry: dict) -> list[ResolvedContainer]: """The records the resolver builds for one raw config entry.""" with _streaming(entry): - return list(streaming.resolve_containers()) + return list(resolve_containers()) def test_expand_platform_block_overrides_container_defaults(): diff --git a/backend/tests/endpoints/test_sync.py b/backend/tests/endpoints/test_sync.py index 198afec56..37b9215ea 100644 --- a/backend/tests/endpoints/test_sync.py +++ b/backend/tests/endpoints/test_sync.py @@ -8,9 +8,11 @@ from io import BytesIO from typing import Any from unittest import mock +import pytest from fastapi import status from handler.database import ( + db_deleted_asset_handler, db_device_handler, db_device_save_sync_handler, db_play_session_handler, @@ -22,6 +24,7 @@ from models.assets import Save from models.device import Device, SyncMode from models.platform import Platform from models.rom import Rom +from models.sync_session import SyncSessionStatus from models.user import User from utils.validation import MAX_ROM_IDS_PER_QUERY @@ -56,6 +59,54 @@ class TestSyncNegotiate: assert data["total_upload"] == 1 assert data["operations"][0]["action"] == "upload" + @pytest.mark.parametrize( + "content_hash,expected_action", + [("deadbeef", "delete"), ("f00d", "upload")], + ids=["the-deleted-version", "bytes-the-deletion-never-covered"], + ) + def test_negotiate_a_slot_the_owner_deleted( + self, + client, + access_token: str, + admin_user: User, + rom: Rom, + content_hash: str, + expected_action: str, + ): + """Server emptied the slot: only the bytes it lost are dropped.""" + device = db_device_handler.add_device( + Device( + id=f"neg-dev-deleted-{content_hash}", + user_id=admin_user.id, + sync_enabled=True, + ) + ) + db_deleted_asset_handler.record_deletion( + user_id=admin_user.id, + rom_id=rom.id, + slot="autosave", + content_hash="deadbeef", + ) + + data = _negotiate( + client, + access_token, + device.id, + [ + { + "rom_id": rom.id, + "file_name": "test_save.sav", + "slot": "autosave", + "content_hash": content_hash, + "updated_at": "2026-01-09T00:00:00Z", + "file_size_bytes": 1024, + } + ], + ) + + assert data[f"total_{expected_action}"] == 1 + assert data["operations"][0]["action"] == expected_action + def test_negotiate_server_has_save_client_doesnt( self, client, access_token: str, admin_user: User, save: Save ): @@ -297,6 +348,56 @@ class TestNegotiateRomIdsScope: assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT +class TestConcurrentNegotiations: + """A session belongs to a launch, and a device can have two games open.""" + + def _negotiate(self, client, access_token: str, device_id: str) -> int: + response = client.post( + "/api/sync/negotiate", + json={"device_id": device_id, "saves": []}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + assert response.status_code == status.HTTP_200_OK + return int(response.json()["session_id"]) + + def test_a_second_negotiation_leaves_the_first_session_open( + self, client, access_token: str, admin_user: User + ): + device = db_device_handler.add_device( + Device(id="concurrent-dev-1", user_id=admin_user.id) + ) + + first = self._negotiate(client, access_token, device.id) + second = self._negotiate(client, access_token, device.id) + assert first != second + + still_open = db_sync_session_handler.get_session(first, admin_user.id) + assert still_open is not None + assert still_open.status == SyncSessionStatus.IN_PROGRESS + + def test_the_first_launch_can_still_complete_its_own_session( + self, client, access_token: str, admin_user: User + ): + # The push after an exit takes seconds, and pressing Play again inside + # them used to cancel the session it was about to close. + device = db_device_handler.add_device( + Device(id="concurrent-dev-2", user_id=admin_user.id) + ) + + first = self._negotiate(client, access_token, device.id) + self._negotiate(client, access_token, device.id) + + response = client.post( + f"/api/sync/sessions/{first}/complete", + json={"operations_completed": 1, "operations_failed": 0}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["session"]["status"] == "COMPLETED" + assert response.json()["session"]["operations_completed"] == 1 + + class TestSyncSessions: def test_complete_session(self, client, access_token: str, admin_user: User): device = db_device_handler.add_device( @@ -345,6 +446,31 @@ class TestSyncSessions: ) assert response.status_code == status.HTTP_400_BAD_REQUEST + def test_complete_a_session_the_cleanup_gave_up_on( + self, client, access_token: str, admin_user: User + ): + # A game open past the cutoff, or a client asleep and back again: the + # counts it returns with are the record, not the cleanup's guess. + device = db_device_handler.add_device( + Device(id="session-dev-stale", user_id=admin_user.id) + ) + sync_session = db_sync_session_handler.create_session( + device_id=device.id, user_id=admin_user.id + ) + db_sync_session_handler.fail_stale_sessions( + older_than=datetime.now(timezone.utc) + timedelta(minutes=1) + ) + + response = client.post( + f"/api/sync/sessions/{sync_session.id}/complete", + json={"operations_completed": 2, "operations_failed": 0}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["session"]["status"] == "COMPLETED" + assert response.json()["session"]["operations_completed"] == 2 + def test_list_sessions(self, client, access_token: str, admin_user: User): device = db_device_handler.add_device( Device(id="session-dev-list", user_id=admin_user.id) @@ -891,15 +1017,14 @@ class TestNegotiateAdvanced: device = db_device_handler.add_device( Device(id="sess-cancel-dev", user_id=admin_user.id) ) - db_sync_session_handler.create_session( + created = db_sync_session_handler.create_session( device_id=device.id, user_id=admin_user.id ) - db_sync_session_handler.cancel_active_sessions(device.id, admin_user.id) - - sessions = db_sync_session_handler.get_sessions( - admin_user.id, device_id=device.id + # Nothing cancels a session any more, but a row left in that state by a + # server that once did is still one this endpoint has to refuse. + cancelled = db_sync_session_handler.update_session( + created.id, {"status": SyncSessionStatus.CANCELLED} ) - cancelled = sessions[0] response = client.post( f"/api/sync/sessions/{cancelled.id}/complete", @@ -952,35 +1077,6 @@ class TestSyncCompleteWithPlaySessions: assert data["play_session_ingest"]["created_count"] == 2 assert data["play_session_ingest"]["skipped_count"] == 0 - def test_play_sessions_have_sync_session_id( - self, client, access_token: str, admin_user: User, rom: Rom - ): - device = db_device_handler.add_device( - Device(id="sync-ps-dev-2", user_id=admin_user.id) - ) - sync_session = db_sync_session_handler.create_session( - device_id=device.id, user_id=admin_user.id - ) - - client.post( - f"/api/sync/sessions/{sync_session.id}/complete", - json={ - "operations_completed": 0, - "operations_failed": 0, - "play_sessions": [ - _play_session(rom_id=rom.id, start_offset_hours=-3), - ], - }, - headers={"Authorization": f"Bearer {access_token}"}, - ) - - sessions = db_play_session_handler.get_sessions( - user_id=admin_user.id, rom_id=rom.id - ) - assert len(sessions) >= 1 - linked = [s for s in sessions if s.sync_session_id == sync_session.id] - assert len(linked) == 1 - def test_play_sessions_use_device_from_sync_session( self, client, access_token: str, admin_user: User, rom: Rom ): diff --git a/backend/tests/handler/auth/test_permissions_resolver.py b/backend/tests/handler/auth/test_permissions_resolver.py index 2e95d9f62..50012c77d 100644 --- a/backend/tests/handler/auth/test_permissions_resolver.py +++ b/backend/tests/handler/auth/test_permissions_resolver.py @@ -52,7 +52,9 @@ def _make_group(name, grants, *, is_default=False): def _set_group(user: User, group_id: int) -> User: db_user_handler.update_user(user.id, {"permission_group_id": group_id}) - return db_user_handler.get_user(user.id) + refreshed = db_user_handler.get_user(user.id) + assert refreshed is not None + return refreshed def _add_override(user_id, entity, action, *, granted, own_only=False): @@ -107,6 +109,7 @@ def test_kiosk_leaves_logged_in_users_alone( def test_kiosk_honors_write_override_on_logged_in_user(kiosk_mode, viewer_user): _add_override(viewer_user.id, PermEntity.ROMS, PermAction.WRITE, granted=True) user = db_user_handler.get_user(viewer_user.id) + assert user is not None assert "roms.write" in {s.value for s in user.oauth_scopes} assert resolve_permissions(user).allows(PermEntity.ROMS, PermAction.WRITE) @@ -144,6 +147,7 @@ def test_explicit_group_overrides_role_fallback(editor_user): def test_override_grants_extra_capability(viewer_user): _add_override(viewer_user.id, PermEntity.ROMS, PermAction.WRITE, granted=True) user = db_user_handler.get_user(viewer_user.id) + assert user is not None assert "roms.write" in {s.value for s in user.oauth_scopes} perms = resolve_permissions(user) assert perms.allows(PermEntity.ROMS, PermAction.WRITE) @@ -155,6 +159,7 @@ def test_override_revokes_group_capability(viewer_user): viewer_user.id, PermEntity.COLLECTIONS, PermAction.WRITE, granted=False ) user = db_user_handler.get_user(viewer_user.id) + assert user is not None assert "collections.write" not in {s.value for s in user.oauth_scopes} diff --git a/backend/tests/handler/auth/test_redis_session_middleware.py b/backend/tests/handler/auth/test_redis_session_middleware.py index eb6a97572..1497d9d9e 100644 --- a/backend/tests/handler/auth/test_redis_session_middleware.py +++ b/backend/tests/handler/auth/test_redis_session_middleware.py @@ -11,8 +11,8 @@ from starlette.routing import Route from starlette.testclient import TestClient from handler.auth.constants import SESSION_COOKIE_NAME +from handler.auth.middleware import redis_session_middleware from handler.auth.middleware.redis_session_middleware import RedisSessionMiddleware -from handler.socket_handler import socket_handler USERNAME = "user_1" @@ -81,7 +81,9 @@ class TestRedisSessionMiddleware: class TestRevokedSessionsCloseTheirSockets: @pytest.fixture def close_login_sessions(self, mocker): - return mocker.patch.object(socket_handler, "close_login_sessions", AsyncMock()) + return mocker.patch.object( + redis_session_middleware, "close_login_session_sockets", AsyncMock() + ) def test_logging_out_closes_that_sessions_sockets( self, close_login_sessions diff --git a/backend/tests/handler/database/test_deleted_assets_handler.py b/backend/tests/handler/database/test_deleted_assets_handler.py new file mode 100644 index 000000000..2254e6293 --- /dev/null +++ b/backend/tests/handler/database/test_deleted_assets_handler.py @@ -0,0 +1,72 @@ +from handler.database import db_deleted_asset_handler +from models.deleted_asset import MAX_REMEMBERED_HASHES, DeletedAsset +from models.rom import Rom +from models.user import User + + +def _record(user: User, rom: Rom, slot: str, content_hash: str) -> DeletedAsset: + return db_deleted_asset_handler.record_deletion( + user_id=user.id, rom_id=rom.id, slot=slot, content_hash=content_hash + ) + + +class TestRecordDeletion: + def test_remembers_the_slot_that_was_emptied(self, rom: Rom, admin_user: User): + record = _record(admin_user, rom, "autosave", "abc123") + + assert record.id is not None + assert record.slot == "autosave" + assert record.content_hashes == ["abc123"] + + def test_a_slot_emptied_twice_keeps_one_record(self, rom: Rom, admin_user: User): + # A device may still hold either version, so both stay on the one row. + _record(admin_user, rom, "autosave", "old") + _record(admin_user, rom, "autosave", "new") + + [record] = db_deleted_asset_handler.get_deletions( + user_id=admin_user.id, rom_ids=[rom.id] + ) + assert record.content_hashes == ["old", "new"] + + def test_a_named_slot_is_its_own_record(self, rom: Rom, admin_user: User): + for slot in ("autosave", "main_quest"): + _record(admin_user, rom, slot, "abc123") + + slots = { + record.slot + for record in db_deleted_asset_handler.get_deletions( + user_id=admin_user.id, rom_ids=[rom.id] + ) + } + assert slots == {"autosave", "main_quest"} + + +class TestGetDeletions: + def test_an_empty_scope_asks_about_nothing(self, rom: Rom, admin_user: User): + _record(admin_user, rom, "autosave", "abc123") + + assert db_deleted_asset_handler.get_deletions(admin_user.id, rom_ids=[]) == [] + + +class TestRememberedVersions: + def test_the_same_version_twice_is_remembered_once( + self, rom: Rom, admin_user: User + ): + for _ in range(3): + record = _record(admin_user, rom, "repeats", "same") + + assert record.content_hashes == ["same"] + + def test_a_version_lost_again_is_the_newest(self, rom: Rom, admin_user: User): + for content_hash in ("first", "second", "first"): + record = _record(admin_user, rom, "relost", content_hash) + + assert record.content_hashes == ["second", "first"] + + def test_the_oldest_versions_fall_off(self, rom: Rom, admin_user: User): + for index in range(MAX_REMEMBERED_HASHES + 5): + record = _record(admin_user, rom, "many", f"hash-{index}") + + assert len(record.content_hashes) == MAX_REMEMBERED_HASHES + assert record.content_hashes[-1] == f"hash-{MAX_REMEMBERED_HASHES + 4}" + assert "hash-0" not in record.content_hashes diff --git a/backend/tests/handler/database/test_music_playlists_handler.py b/backend/tests/handler/database/test_music_playlists_handler.py index 45307da7c..c74a15b7b 100644 --- a/backend/tests/handler/database/test_music_playlists_handler.py +++ b/backend/tests/handler/database/test_music_playlists_handler.py @@ -32,11 +32,12 @@ def track_ids(rom: Rom) -> list[int]: def test_playlist_crud(admin_user: User, playlist: MusicPlaylist): - assert db_music_playlist_handler.get_playlist(playlist.id).name == "Focus" - assert ( - db_music_playlist_handler.get_playlist_by_name("Focus", admin_user.id).id - == playlist.id - ) + fetched = db_music_playlist_handler.get_playlist(playlist.id) + assert fetched is not None + assert fetched.name == "Focus" + by_name = db_music_playlist_handler.get_playlist_by_name("Focus", admin_user.id) + assert by_name is not None + assert by_name.id == playlist.id assert db_music_playlist_handler.get_playlist_by_name("Focus", 999999) is None updated = db_music_playlist_handler.update_playlist( diff --git a/backend/tests/handler/database/test_platforms_handler.py b/backend/tests/handler/database/test_platforms_handler.py index 6ede30241..c32911d99 100644 --- a/backend/tests/handler/database/test_platforms_handler.py +++ b/backend/tests/handler/database/test_platforms_handler.py @@ -25,7 +25,9 @@ def test_lookup_returns_the_exactly_named_folder_when_one_exists(): Platform(name="PlayStation", slug="psx", fs_slug="psx") ) - assert db_platform_handler.get_platform_by_fs_slug("psx").id == exact.id + found = db_platform_handler.get_platform_by_fs_slug("psx") + assert found is not None + assert found.id == exact.id def test_rescan_preserves_user_authored_fields(platform): diff --git a/backend/tests/handler/database/test_roms_filter_cache.py b/backend/tests/handler/database/test_roms_filter_cache.py index a6a606352..e51adf715 100644 --- a/backend/tests/handler/database/test_roms_filter_cache.py +++ b/backend/tests/handler/database/test_roms_filter_cache.py @@ -15,11 +15,9 @@ These tests pin down that machinery: import json from datetime import datetime, timezone -from typing import cast import pytest from sqlalchemy import select -from sqlalchemy.orm import Query from tests.conftest import session as session_factory from handler.database import db_rom_handler @@ -120,7 +118,7 @@ class TestStoreVersionedCache: class TestCacheHitMatchesMiss: def test_with_filter_values_hit_matches_miss(self, rom_with_metadata: Rom): - query = cast(Query[Rom], select(Rom)) + query = select(Rom) cache_key = "all:test-filters" miss = db_rom_handler.with_filter_values(query=query, cache_key=cache_key) @@ -143,7 +141,7 @@ class TestCacheHitMatchesMiss: def test_with_filter_values_without_cache_key_does_not_cache( self, rom_with_metadata: Rom ): - query = cast(Query[Rom], select(Rom)) + query = select(Rom) result = db_rom_handler.with_filter_values(query=query) # Nothing written, and a sane shape is still returned. @@ -151,7 +149,7 @@ class TestCacheHitMatchesMiss: assert result["genres"] == ["RPG"] def test_with_char_index_hit_matches_miss(self, rom: Rom): - query = cast(Query[Rom], select(Rom)) + query = select(Rom) cache_key = "all:test-charindex" miss = db_rom_handler.with_char_index( @@ -187,7 +185,7 @@ class TestCacheHitMatchesMiss: assert dict(hit) == dict(miss) == {"t": 0} def test_get_rom_id_index_hit_matches_miss(self, rom: Rom): - query = cast(Query[Rom], select(Rom)) + query = select(Rom) cache_key = "all:test-idindex" miss = db_rom_handler.get_rom_id_index(query=query, cache_key=cache_key) @@ -227,7 +225,7 @@ class TestFilterValuesSchemaDrift: """ def test_legacy_unnamespaced_entry_is_not_read(self, rom_with_metadata: Rom): - query = cast(Query[Rom], select(Rom)) + query = select(Rom) cache_key = "all:schema-drift" version = _filter_values_cache_version() @@ -345,7 +343,7 @@ class TestRomUserCacheVersion: class TestInvalidateFilterValuesCache: def test_deletes_prior_version_keys_and_set(self, rom_with_metadata: Rom): - query = cast(Query[Rom], select(Rom)) + query = select(Rom) # Populate both caches under the current version. db_rom_handler.with_filter_values(query=query, cache_key="all:filters") @@ -373,7 +371,7 @@ class TestInvalidateFilterValuesCache: def test_recomputes_under_new_version_after_invalidation( self, rom_with_metadata: Rom ): - query = cast(Query[Rom], select(Rom)) + query = select(Rom) cache_key = "all:filters" db_rom_handler.with_filter_values(query=query, cache_key=cache_key) diff --git a/backend/tests/handler/database/test_roms_hash_search.py b/backend/tests/handler/database/test_roms_hash_search.py index f6e83606e..f37580b05 100644 --- a/backend/tests/handler/database/test_roms_hash_search.py +++ b/backend/tests/handler/database/test_roms_hash_search.py @@ -7,7 +7,7 @@ taking anything away from the name search. """ import pytest -from sqlalchemy.orm import Query +from sqlalchemy import select from handler.database import db_collection_handler, db_rom_handler from models.collection import SmartCollection @@ -62,8 +62,8 @@ def _search_ids(term: str) -> list[int]: def _search_sql(term: str) -> str: - query = db_rom_handler._filter_by_search_term(Query(Rom.id), term) - return str(query.statement.compile(compile_kwargs={"literal_binds": True})) + query = db_rom_handler._filter_by_search_term(select(Rom.id), term) + return str(query.compile(compile_kwargs={"literal_binds": True})) @pytest.fixture diff --git a/backend/tests/handler/database/test_roms_hltb_length.py b/backend/tests/handler/database/test_roms_hltb_length.py index c21e7095e..84611315f 100644 --- a/backend/tests/handler/database/test_roms_hltb_length.py +++ b/backend/tests/handler/database/test_roms_hltb_length.py @@ -39,7 +39,7 @@ def _make_rom(platform: Platform, fs_name: str, **metadata) -> Rom: def _filtered_names(**kwargs) -> set[str]: - return {rom.name for rom in db_rom_handler.get_roms_scalar(**kwargs)} + return {rom.name or "" for rom in db_rom_handler.get_roms_scalar(**kwargs)} @pytest.fixture @@ -96,7 +96,7 @@ class TestLengthSort: page = db_rom_handler.get_roms_scalar(order_by="hltb_main_story")[ offset : offset + 3 ] - paged.extend(rom.name for rom in page) + paged.extend(rom.name or "" for rom in page) assert sorted(paged) == sorted(f"tied-{i}" for i in range(10)) diff --git a/backend/tests/handler/database/test_roms_metadata_sort.py b/backend/tests/handler/database/test_roms_metadata_sort.py index 4db233195..92ad93da5 100644 --- a/backend/tests/handler/database/test_roms_metadata_sort.py +++ b/backend/tests/handler/database/test_roms_metadata_sort.py @@ -49,7 +49,7 @@ def _make_rom(platform: Platform, fs_name: str, **metadata) -> Rom: def _ordered_names(**kwargs) -> list[str]: - return [rom.name for rom in db_rom_handler.get_roms_scalar(**kwargs)] + return [rom.name or "" for rom in db_rom_handler.get_roms_scalar(**kwargs)] class TestMetadataSortQueryShape: @@ -182,7 +182,10 @@ class TestSortIndexes: def roms_index_sorting(self) -> dict[str, dict[str, tuple[str, ...]]]: with sync_engine.connect() as connection: return { - index["name"]: index.get("column_sorting") or {} + index["name"]: { + column: tuple(order) + for column, order in (index.get("column_sorting") or {}).items() + } for index in sa.inspect(connection).get_indexes("roms") if index["name"] } diff --git a/backend/tests/handler/database/test_roms_released_days.py b/backend/tests/handler/database/test_roms_released_days.py index c94ead90b..cecf73579 100644 --- a/backend/tests/handler/database/test_roms_released_days.py +++ b/backend/tests/handler/database/test_roms_released_days.py @@ -53,7 +53,7 @@ def _names( released_before_year=before_year, order_by="first_release_date", ) - return [rom.name for rom in roms] + return [rom.name or "" for rom in roms] class TestMatching: diff --git a/backend/tests/handler/database/test_roms_rom_user_sort.py b/backend/tests/handler/database/test_roms_rom_user_sort.py index d6fa66d5d..33374f2db 100644 --- a/backend/tests/handler/database/test_roms_rom_user_sort.py +++ b/backend/tests/handler/database/test_roms_rom_user_sort.py @@ -6,6 +6,7 @@ to 0 in an existing row, which renders as unset and sorts as unset. """ from datetime import datetime, timezone +from typing import Any import pytest from sqlalchemy.dialects import mysql @@ -47,7 +48,7 @@ def _set_rom_user_fields(rom: Rom, user: User, fields: dict[str, object]) -> Non def _ordered_names( - user: User, order_by: str, order_dir: str, *, attr: str = "name", **kwargs: object + user: User, order_by: str, order_dir: str, *, attr: str = "name", **kwargs: Any ) -> list[str]: return [ getattr(rom, attr) diff --git a/backend/tests/handler/database/test_sync_sessions_handler.py b/backend/tests/handler/database/test_sync_sessions_handler.py index d5281add0..86f03fd7f 100644 --- a/backend/tests/handler/database/test_sync_sessions_handler.py +++ b/backend/tests/handler/database/test_sync_sessions_handler.py @@ -1,7 +1,10 @@ +from datetime import datetime, timedelta, timezone + import pytest from sqlalchemy.exc import NoResultFound from handler.database import db_device_handler, db_sync_session_handler +from handler.database.sync_sessions_handler import STALE_SESSION_MESSAGE from models.device import Device from models.sync_session import SyncSessionStatus from models.user import User @@ -98,11 +101,68 @@ class TestCompleteSession: result = db_sync_session_handler.complete_session( created.id, operations_completed=10, operations_failed=2 ) + assert result is not None assert result.status == SyncSessionStatus.COMPLETED assert result.operations_completed == 10 assert result.operations_failed == 2 assert result.completed_at is not None + def test_completes_a_session_the_cleanup_gave_up_on(self, admin_user: User): + # Counts, and the play sessions a client carries with them, are worth + # more than the cleanup's guess that nobody would ever report them. + device = db_device_handler.add_device( + Device(id="comp-dev-2", user_id=admin_user.id) + ) + created = db_sync_session_handler.create_session(device.id, admin_user.id) + db_sync_session_handler.fail_stale_sessions( + older_than=datetime.now(timezone.utc) + timedelta(minutes=1) + ) + + result = db_sync_session_handler.complete_session( + created.id, operations_completed=3 + ) + + assert result is not None + assert result.status == SyncSessionStatus.COMPLETED + assert result.operations_completed == 3 + # The row is a completed session now, not one still carrying why it was + # given up on. + assert result.error_message is None + + def test_leaves_a_session_something_failed_on_purpose(self, admin_user: User): + # Only the cleanup's own failure reopens: it says nobody reported this + # session, where a worker's failure is a report of what happened. + device = db_device_handler.add_device( + Device(id="comp-dev-4", user_id=admin_user.id) + ) + created = db_sync_session_handler.create_session(device.id, admin_user.id) + db_sync_session_handler.fail_session(created.id, error_message="the wire went") + + assert db_sync_session_handler.complete_session(created.id) is None + + stored = db_sync_session_handler.get_session(created.id, admin_user.id) + assert stored is not None + assert stored.status == SyncSessionStatus.FAILED + assert stored.error_message == "the wire went" + + def test_a_second_completion_changes_nothing(self, admin_user: User): + # The statement decides it, so a completion and the cleanup landing + # together cannot both win. + device = db_device_handler.add_device( + Device(id="comp-dev-3", user_id=admin_user.id) + ) + created = db_sync_session_handler.create_session(device.id, admin_user.id) + db_sync_session_handler.complete_session(created.id, operations_completed=4) + + assert ( + db_sync_session_handler.complete_session(created.id, operations_completed=9) + is None + ) + + stored = db_sync_session_handler.get_session(created.id, admin_user.id) + assert stored is not None + assert stored.operations_completed == 4 + class TestFailSession: def test_marks_failed_with_error(self, admin_user: User): @@ -171,33 +231,67 @@ class TestNoResultFoundOnMissingSession: db_sync_session_handler.fail_session(999999, error_message="test") -class TestCancelActiveSessions: - def test_cancels_active_sessions(self, admin_user: User): +class TestFailStaleSessions: + def test_fails_sessions_left_open(self, admin_user: User): + # Nothing else closes one now that a negotiation leaves the device's + # other sessions alone, so a client that never comes back is what this + # exists for. device = db_device_handler.add_device( - Device(id="cancel-dev-1", user_id=admin_user.id) + Device(id="stale-dev-1", user_id=admin_user.id) ) - db_sync_session_handler.create_session(device.id, admin_user.id) - s2 = db_sync_session_handler.create_session(device.id, admin_user.id) + pending = db_sync_session_handler.create_session(device.id, admin_user.id) + running = db_sync_session_handler.create_session(device.id, admin_user.id) db_sync_session_handler.update_session( - s2.id, {"status": SyncSessionStatus.IN_PROGRESS} + running.id, {"status": SyncSessionStatus.IN_PROGRESS} ) - count = db_sync_session_handler.cancel_active_sessions(device.id, admin_user.id) + count = db_sync_session_handler.fail_stale_sessions( + older_than=datetime.now(timezone.utc) + timedelta(minutes=1) + ) assert count == 2 - active = db_sync_session_handler.get_active_session(device.id, admin_user.id) - assert active is None + for session_id in (pending.id, running.id): + failed = db_sync_session_handler.get_session(session_id, admin_user.id) + assert failed is not None + assert failed.status == SyncSessionStatus.FAILED + # Failed rather than cancelled, and the row is the only place the + # difference can be recorded. + assert failed.error_message == STALE_SESSION_MESSAGE + assert failed.completed_at is not None - def test_does_not_cancel_completed(self, admin_user: User): + def test_leaves_a_session_still_in_its_launch(self, admin_user: User): + # A game can be open for hours, so only a session older than the cutoff + # is past accounting for. device = db_device_handler.add_device( - Device(id="cancel-dev-2", user_id=admin_user.id) + Device(id="stale-dev-2", user_id=admin_user.id) + ) + created = db_sync_session_handler.create_session(device.id, admin_user.id) + + count = db_sync_session_handler.fail_stale_sessions( + older_than=datetime.now(timezone.utc) - timedelta(hours=24) + ) + assert count == 0 + + still_open = db_sync_session_handler.get_session(created.id, admin_user.id) + assert still_open is not None + assert still_open.status == SyncSessionStatus.PENDING + + def test_leaves_a_finished_session_alone(self, admin_user: User): + device = db_device_handler.add_device( + Device(id="stale-dev-3", user_id=admin_user.id) ) created = db_sync_session_handler.create_session(device.id, admin_user.id) db_sync_session_handler.complete_session(created.id) - count = db_sync_session_handler.cancel_active_sessions(device.id, admin_user.id) + count = db_sync_session_handler.fail_stale_sessions( + older_than=datetime.now(timezone.utc) + timedelta(minutes=1) + ) assert count == 0 + completed = db_sync_session_handler.get_session(created.id, admin_user.id) + assert completed is not None + assert completed.status == SyncSessionStatus.COMPLETED + class TestGetSessions: def test_list_sessions_for_user(self, admin_user: User): diff --git a/backend/tests/handler/notification_channels/test_apprise_channel.py b/backend/tests/handler/notification_channels/test_apprise_channel.py new file mode 100644 index 000000000..8fc13c143 --- /dev/null +++ b/backend/tests/handler/notification_channels/test_apprise_channel.py @@ -0,0 +1,481 @@ +import logging +from typing import Any + +import pytest +from apprise import Apprise, NotifyFormat, NotifyType + +from handler.notification_channels import apprise_channel +from handler.notification_channels.apprise_channel import ( + AppriseError, + FieldValue, + build_url, + checked_fields, + describe, + fields_from_url, + find_service, + merge_fields, + send, + services, + split_fields, +) +from handler.notification_channels.messages import OutboundMessage +from handler.notification_channels.webhook import ERROR_DETAIL_CHARS +from models.notification import NotificationLevel + +from .fixtures import make_notification + +_DISCORD = {"webhook_id": "1234567890", "webhook_token": "abcdefghijklmnop"} +_JSON = {"host": "hooks.example.com", "path": "romm"} + + +def _message(**overrides: Any) -> OutboundMessage: + fields: dict[str, Any] = { + "notification": make_notification(), + "title": "Maintenance tonight", + "body": "RomM restarts at 23:00", + "url": "https://romm.example.com/platforms", + } + return OutboundMessage(**{**fields, **overrides}) + + +def _keys(service_id: str, advanced: bool = False) -> list[str]: + return [f.key for f in find_service(service_id).fields if f.advanced is advanced] + + +class TestCatalog: + def test_lists_what_apprise_reaches_but_nothing_local(self): + ids = [service.id for service in services()] + + assert {"discord", "ntfy", "tgram", "json"} <= set(ids) + # Local schemas, and FCM whose key file Apprise opens itself. + assert not {"syslog", "fcm"} & set(ids) + names = [service.name.lower() for service in services()] + assert names == sorted(names) + + def test_requires_only_what_every_template_needs(self): + discord = find_service("discord") + slack = find_service("slack") + + assert [f.key for f in discord.fields if f.required] == [ + "webhook_id", + "webhook_token", + ] + # A bot token or three webhook tokens: neither is needed by both. + assert not any(f.required for f in slack.fields) + + def test_a_list_stands_in_for_its_singular_tokens(self): + targets = find_service("ntfy").field("targets") + + assert "topic" not in _keys("ntfy") + assert targets is not None + assert (targets.type, targets.required) == ("list", True) + + def test_offers_the_schema_only_when_there_is_a_choice(self): + schema = find_service("ntfy").field("schema") + + assert schema is not None + assert (schema.values, schema.default) == (("ntfy", "ntfys"), "ntfys") + assert find_service("discord").field("schema") is None + + def test_leaves_out_options_romm_sets_or_that_read_files(self): + options = _keys("discord", advanced=True) + + assert "ping" in options + assert not {"template", "cto", "rto", "retry", "redirect", "url"} & set(options) + + def test_json_takes_a_path_after_its_host(self): + assert "path" in _keys("json") + + @pytest.mark.parametrize( + "service,url_fields", + [ + ("discord", ("webhook_id", "webhook_token")), + ( + "ntfy", + ("schema", "host", "port", "user", "password", "token", "targets"), + ), + ("pover", ()), + ("matrix", ()), + ], + ) + def test_knows_what_a_services_own_url_fills_in(self, service, url_fields): + assert find_service(service).url_fields == url_fields + + def test_points_at_the_setup_guide_on_apprises_wiki(self): + assert find_service("discord").setup_url == ( + "https://github.com/caronc/apprise/wiki/Notify_discord" + ) + + @pytest.mark.parametrize( + "service,key", [("mastodon", "token"), ("rocket", "webhook"), ("json", "path")] + ) + def test_treats_credentials_as_secrets_even_unflagged(self, service, key): + field = find_service(service).field(key) + + assert field is not None + assert field.private + + +class TestBuildUrl: + @pytest.mark.parametrize( + "service,fields,url", + [ + ("discord", _DISCORD, "discord://1234567890/abcdefghijklmnop"), + ( + "discord", + {**_DISCORD, "botname": "RomM", "image": True, "ping": ["@here"]}, + "discord://RomM@1234567890/abcdefghijklmnop?image=yes&ping=%40here", + ), + ("ntfy", {"targets": ["romm"]}, "ntfys://romm"), + ( + "ntfy", + {"host": "ntfy.example.com", "targets": ["romm"], "token": "tk_1"}, + "ntfys://tk_1@ntfy.example.com/romm", + ), + ( + "ntfy", + { + "schema": "ntfy", + "host": "192.168.1.5", + "port": 8080, + "user": "me", + "password": "p@ss/word", + "targets": ["a", "b"], + }, + "ntfy://me:p%40ss%2Fword@192.168.1.5:8080/a/b", + ), + ( + "gotify", + {"host": "push.example.com", "path": "gotify", "token": "abc"}, + "gotifys://push.example.com/gotify/abc", + ), + ( + "json", + {"host": "hooks.example.com", "path": "/api/romm"}, + "jsons://hooks.example.com/api/romm", + ), + ], + ) + def test_fills_in_the_template_the_fields_make_up(self, service, fields, url): + assert build_url(find_service(service), fields) == url + checked_fields(service, fields) + + def test_says_what_is_missing(self): + with pytest.raises(ValueError, match="^Discord needs Webhook Token$"): + build_url(find_service("discord"), {"webhook_id": "1234567890"}) + + def test_refuses_fields_no_template_takes_together(self): + fields: dict[str, FieldValue] = { + "host": "h.example.com", + "targets": ["a"], + "user": "u", + "token": "t", + } + + with pytest.raises(ValueError, match="can't take these fields together"): + build_url(find_service("ntfy"), {**fields, "password": "p"}) + + @pytest.mark.parametrize( + "host", ["example.com/hook?x=1", "{port}.example.com", "example.com:8080"] + ) + def test_a_host_is_only_a_host(self, host): + with pytest.raises(ValueError, match="isn't a hostname"): + build_url(find_service("json"), {"host": host, "port": 80}) + + @pytest.mark.parametrize("host", ["ntfy.example.com", "192.168.1.5", "[::1]"]) + def test_takes_names_and_addresses_as_hosts(self, host): + assert build_url( + find_service("ntfy"), {"host": host, "targets": ["romm"]} + ).startswith(f"ntfys://{host}/") + + def test_ignores_fields_the_form_never_offered(self): + url = build_url( + find_service("discord"), {**_DISCORD, "template": "/etc/passwd"} + ) + + assert "template" not in url + + @pytest.mark.parametrize("service", ["syslog", "fcm", "nowhere"]) + def test_knows_only_the_services_it_lists(self, service): + with pytest.raises(ValueError, match="no such service"): + find_service(service) + + +class TestFields: + def test_describes_the_service_and_hides_its_token(self): + assert describe("discord", _DISCORD) == ("Discord", "discord://1...0/a...p/") + + def test_describes_fields_it_can_no_longer_use_as_nothing(self): + assert describe("discord", {}) == (None, "") + + def test_hides_secrets_apprise_would_show(self): + _, target = describe("json", {"host": "hooks.example.com", "path": "t0ken"}) + + assert target == "jsons://hooks.example.com/****" + + def test_hands_the_form_what_isnt_secret_and_names_the_secrets(self): + assert split_fields("discord", {**_DISCORD, "botname": "RomM"}) == ( + {"botname": "RomM"}, + ["webhook_id", "webhook_token"], + ) + + def test_check_keeps_only_the_fields_the_service_takes(self): + assert ( + checked_fields("discord", {**_DISCORD, "junk": "x", "botname": ""}) + == _DISCORD + ) + + def test_a_refusal_hides_the_secret_it_quotes(self): + with pytest.raises(ValueError, match=r"Token \(\*\*\*\*\)"): + checked_fields("slack", {"access_token": "nope-abc"}) + + +class TestFieldsFromUrl: + @pytest.mark.parametrize( + "url,service,fields", + [ + ( + "https://discord.com/api/webhooks/1234567890/abcdefghijklmnop", + "discord", + _DISCORD, + ), + ( + "discord://RomM@1234567890/abcdefghijklmnop?image=yes&cto=99", + "discord", + {"botname": "RomM", **_DISCORD, "image": True}, + ), + ( + "ntfy://me:p%40ss@192.168.1.5:8080/a/b", + "ntfy", + { + "schema": "ntfy", + "user": "me", + "password": "p@ss", + "host": "192.168.1.5", + "port": 8080, + "targets": ["a", "b"], + }, + ), + ( + "jsons://hooks.example.com/api/romm", + "json", + {"host": "hooks.example.com", "path": "api/romm"}, + ), + ], + ) + def test_reads_a_url_back_into_its_service_and_fields(self, url, service, fields): + found, read = fields_from_url(url) + + assert (found.id, read) == (service, fields) + checked_fields(service, read) + + @pytest.mark.parametrize( + "url,reason", + [ + ("syslog://", "doesn't offer"), + ("FCM://project/device", "doesn't offer"), + ("fcm://project/device", "doesn't offer|can't read"), + ( + "discord://1234567890/abcdefghijklmnop?template=/etc/passwd", + "local files", + ), + ("nowhere://romm", "can't read"), + ("https://discord.com/api/webhooks/1 2", "without spaces"), + ], + ) + def test_says_why_it_cant_read_a_url(self, url, reason): + with pytest.raises(ValueError, match=reason): + fields_from_url(url) + + +class TestMergeFields: + _NTFY: dict[str, FieldValue] = { + "host": "ntfy.example.com", + "targets": ["romm"], + "token": "tk_1", + } + + def test_a_secret_left_out_stays(self): + merged = merge_fields("discord", _DISCORD, {"webhook_id": "1234567890"}) + + assert merged == _DISCORD + + def test_an_empty_secret_goes(self): + given: dict[str, FieldValue] = { + **self._NTFY, + "token": "", + "user": "me", + "password": "pw", + } + + assert merge_fields("ntfy", self._NTFY, given) == { + "host": "ntfy.example.com", + "targets": ["romm"], + "user": "me", + "password": "pw", + } + + @pytest.mark.parametrize( + "change", + [{"host": "elsewhere.example.com"}, {"port": 8443}, {"schema": "ntfy"}], + ) + def test_a_kept_secret_does_not_follow_the_channel_elsewhere(self, change): + given: dict[str, FieldValue] = { + "host": "ntfy.example.com", + "targets": ["romm"], + **change, + } + + with pytest.raises(ValueError, match="Enter Token again"): + merge_fields("ntfy", self._NTFY, given) + + def test_a_secret_given_again_goes_to_the_new_address(self): + given: dict[str, FieldValue] = { + "host": "elsewhere.example.com", + "targets": ["romm"], + "token": "tk_2", + } + + assert merge_fields("ntfy", self._NTFY, given) == given + + +class TestSend: + @pytest.fixture + def notify(self, mocker): + """Stands in for Apprise's notify; keeps what it got and returns `result`.""" + calls: list[tuple[Apprise, dict[str, Any]]] = [] + + def install(result: bool = True, log: Any = None): + def fake(self: Apprise, **kwargs: Any) -> bool: + calls.append((self, kwargs)) + if log: + log() + return result + + mocker.patch.object(apprise_channel.Apprise, "notify", fake) + return calls + + return install + + def test_sends_the_title_body_and_link(self, notify): + calls = notify() + + send("json", _JSON, _message()) + + [(_, kwargs)] = calls + assert kwargs == { + "title": "Maintenance tonight", + "body": "RomM restarts at 23:00\n\nhttps://romm.example.com/platforms", + "notify_type": NotifyType.INFO, + "body_format": NotifyFormat.TEXT, + } + + def test_mentions_ping_nobody(self, notify): + calls = notify() + + send("json", _JSON, _message(title="@everyone look", body="<@123> and @here")) + + [(_, kwargs)] = calls + assert kwargs["title"] == "@\u200beveryone look" + assert kwargs["body"].startswith("<\u200b@123> and @\u200bhere") + + def test_a_title_alone_is_also_the_body(self, notify): + calls = notify() + + send("json", _JSON, _message(body=None, url=None)) + + [(_, kwargs)] = calls + assert kwargs["body"] == "Maintenance tonight" + + @pytest.mark.parametrize( + "level,notify_type", + [ + (NotificationLevel.INFO, NotifyType.INFO), + (NotificationLevel.SUCCESS, NotifyType.SUCCESS), + (NotificationLevel.WARNING, NotifyType.WARNING), + (NotificationLevel.ERROR, NotifyType.FAILURE), + ], + ) + def test_carries_the_level(self, notify, level, notify_type): + calls = notify() + + send("json", _JSON, _message(notification=make_notification(level=level))) + + [(_, kwargs)] = calls + assert kwargs["notify_type"] == notify_type + + def test_sends_as_romm_with_its_icon(self, notify): + calls = notify() + + send("discord", _DISCORD, _message()) + + [(apprise, _)] = calls + plugin = apprise[0] + assert plugin.app_id == "RomM" + assert plugin.image_url(NotifyType.INFO) == apprise_channel.ROMM_ICON_URL + + def test_holds_a_service_to_its_own_limits(self, notify): + calls = notify() + + # Apprise gives email 15 seconds to connect. + send("mailto", {"host": "smtp.example.com", "user": "me"}, _message()) + + [(apprise, _)] = calls + plugin = apprise[0] + assert plugin.socket_connect_timeout == apprise_channel.CONNECT_TIMEOUT_SECONDS + assert (plugin.retry, plugin.redirects) == (0, False) + + def test_a_refusal_says_what_apprise_warned_and_the_start_of_the_reply( + self, notify + ): + reply = b'{"message": "Invalid Form Body", "code": 50035}' + b"x" * 500 + + def log(): + logger = logging.getLogger("apprise") + logger.warning("Failed to send Discord notification: error=400.") + logger.debug("Response Details:\r\n%r", reply) + logger.debug("Sent nothing else worth keeping") + + notify(result=False, log=log) + + with pytest.raises(AppriseError) as caught: + send("json", _JSON, _message()) + + warning, answered = str(caught.value).split(" Reply: ") + assert warning == "Failed to send Discord notification: error=400." + assert answered.startswith('{"message": "Invalid Form Body", "code": 50035}') + assert len(answered) == ERROR_DETAIL_CHARS + + def test_an_empty_reply_adds_nothing(self, notify): + def log(): + logger = logging.getLogger("apprise") + logger.warning("Failed to send JSON POST notification: error=500.") + logger.debug("Response Details:\r\n%r", b"") + + notify(result=False, log=log) + + with pytest.raises(AppriseError, match=r"error=500\.$"): + send("json", _JSON, _message()) + + def test_a_warning_outside_a_send_goes_to_the_server_log(self, mocker): + server_log = mocker.patch.object(apprise_channel, "log") + + logging.getLogger("apprise").warning("A plugin failed to load") + + server_log.warning.assert_called_once_with("Apprise: A plugin failed to load") + + def test_keeps_no_warning_logged_outside_a_send(self, notify, mocker): + mocker.patch.object(apprise_channel, "log") + logging.getLogger("apprise").warning("Something from another send") + notify(result=False) + + with pytest.raises(AppriseError, match="^JSON did not take the notification$"): + send("json", _JSON, _message()) + + def test_an_unreachable_service_is_an_apprise_error(self): + with pytest.raises(AppriseError, match="Connection error"): + send( + "json", + {"schema": "json", "host": "127.0.0.1", "port": 1}, + _message(), + ) diff --git a/backend/tests/handler/notification_channels/test_channels.py b/backend/tests/handler/notification_channels/test_channels.py index 3a39d6f5a..d45529feb 100644 --- a/backend/tests/handler/notification_channels/test_channels.py +++ b/backend/tests/handler/notification_channels/test_channels.py @@ -18,12 +18,12 @@ from handler.notification_channels.confirmation import CodeCooldownError from models.notification_channel import ( NotificationChannelMinLevel, NotificationChannelType, - WebhookFormat, ) from models.user import Role ADMIN = MagicMock(id=1, role=Role.ADMIN) USER = MagicMock(id=2, role=Role.USER) +DISCORD = {"webhook_id": "1234567890", "webhook_token": "abcdefghijklmnop"} @pytest.fixture @@ -62,33 +62,60 @@ class TestCreate: channel = await create_channel( USER, NotificationChannelType.WEBHOOK, - "Discord", + "Hooks", NotificationChannelMinLevel.WARNING, None, - url="https://discord.com/api/webhooks/1/t", - format=WebhookFormat.DISCORD, + url="https://hooks.example.com/romm", ) assert channel.confirmed_at is not None assert read_config(channel.config) == { - "url": "https://discord.com/api/webhooks/1/t", - "format": "discord", + "url": "https://hooks.example.com/romm", "secret": None, } - async def test_a_discord_webhook_keeps_no_secret(self, db): + async def test_an_admin_forwards_through_apprise(self, db): channel = await create_channel( - USER, - NotificationChannelType.WEBHOOK, - "Discord", + ADMIN, + NotificationChannelType.APPRISE, + "Phone", NotificationChannelMinLevel.INFO, None, - url="https://discord.com/api/webhooks/1/t", - format=WebhookFormat.DISCORD, - secret="unused", + service="ntfy", + fields={"targets": ["romm"]}, ) - assert read_config(channel.config)["secret"] is None + assert channel.confirmed_at is not None + assert read_config(channel.config) == { + "service": "ntfy", + "fields": {"targets": ["romm"]}, + } + + async def test_a_user_may_not_use_apprise(self, db): + with pytest.raises(ChannelError, match="Only admins"): + await create_channel( + USER, + NotificationChannelType.APPRISE, + "Phone", + NotificationChannelMinLevel.INFO, + None, + service="ntfy", + fields={"targets": ["romm"]}, + ) + + db.add_channel.assert_not_called() + + async def test_fields_apprise_cannot_use_are_refused(self, db): + with pytest.raises(ChannelError, match="needs Webhook Token"): + await create_channel( + ADMIN, + NotificationChannelType.APPRISE, + "Discord", + NotificationChannelMinLevel.INFO, + None, + service="discord", + fields={"webhook_id": "1234567890"}, + ) async def test_a_user_stays_off_the_local_network(self, db): with pytest.raises(ChannelError): @@ -171,7 +198,7 @@ class TestCreate: class TestUpdate: async def test_keeps_the_secret_unless_given(self, db): - stored = _stored(url="https://hooks.example.com/a", format="json", secret="k") + stored = _stored(url="https://hooks.example.com/a", secret="k") updated = await update_channel( stored, USER, {}, url="https://hooks.example.com/b" @@ -179,41 +206,22 @@ class TestUpdate: assert read_config(updated.config) == { "url": "https://hooks.example.com/b", - "format": "json", "secret": "k", } @pytest.mark.parametrize( - "change", - [ - {"url": "https://elsewhere.example.com/a"}, - {"url": "https://hooks.example.com:8443/a"}, - {"format": WebhookFormat.NTFY}, - ], + "url", ["https://elsewhere.example.com/a", "https://hooks.example.com:8443/a"] ) - async def test_a_kept_secret_does_not_follow_it_elsewhere(self, db, change): - stored = _stored(url="https://hooks.example.com/a", format="json", secret="k") + async def test_a_kept_secret_does_not_follow_it_elsewhere(self, db, url): + stored = _stored(url="https://hooks.example.com/a", secret="k") with pytest.raises(ChannelError, match="secret again"): - await update_channel(stored, USER, {}, **change) + await update_channel(stored, USER, {}, url=url) db.update_channel.assert_not_called() - async def test_moving_to_discord_drops_the_secret_it_never_sends(self, db): - stored = _stored(url="https://hooks.example.com/a", format="json", secret="k") - - updated = await update_channel( - stored, - USER, - {}, - url="https://discord.com/api/webhooks/1/t", - format=WebhookFormat.DISCORD, - ) - - assert read_config(updated.config)["secret"] is None - async def test_a_secret_given_again_goes_to_the_new_url(self, db): - stored = _stored(url="https://hooks.example.com/a", format="json", secret="k") + stored = _stored(url="https://hooks.example.com/a", secret="k") updated = await update_channel( stored, @@ -227,14 +235,71 @@ class TestUpdate: assert read_config(updated.config)["secret"] == "k2" async def test_an_empty_secret_drops_it(self, db): - stored = _stored(url="https://hooks.example.com/a", format="json", secret="k") + stored = _stored(url="https://hooks.example.com/a", secret="k") updated = await update_channel(stored, USER, {}, secret="", secret_given=True) assert read_config(updated.config)["secret"] is None + async def test_apprise_fields_left_out_stay(self, db): + stored = _stored( + NotificationChannelType.APPRISE, service="discord", fields=DISCORD + ) + + await update_channel(stored, ADMIN, {"name": "Phone"}) + + db.update_channel.assert_called_once_with(4, ADMIN.id, {"name": "Phone"}) + + async def test_an_apprise_secret_left_blank_stays(self, db): + stored = _stored( + NotificationChannelType.APPRISE, service="discord", fields=DISCORD + ) + + updated = await update_channel( + stored, ADMIN, {}, fields={"webhook_id": "987654321", "botname": "RomM"} + ) + + assert read_config(updated.config)["fields"] == { + "webhook_id": "987654321", + "webhook_token": DISCORD["webhook_token"], + "botname": "RomM", + } + + async def test_new_apprise_fields_are_checked(self, db): + stored = _stored( + NotificationChannelType.APPRISE, service="ntfy", fields={"targets": ["a"]} + ) + + with pytest.raises(ChannelError, match="ntfy needs Targets"): + await update_channel(stored, ADMIN, {}, fields={"targets": []}) + + db.update_channel.assert_not_called() + + async def test_a_kept_apprise_secret_does_not_follow_a_new_host(self, db): + stored = _stored( + NotificationChannelType.APPRISE, + service="ntfy", + fields={"host": "ntfy.example.com", "targets": ["a"], "token": "tk_1"}, + ) + + with pytest.raises(ChannelError, match="Enter Token again"): + await update_channel( + stored, ADMIN, {}, fields={"host": "evil.example.com", "targets": ["a"]} + ) + + db.update_channel.assert_not_called() + + async def test_a_demoted_admin_can_rename_but_not_repoint_it(self, db): + stored = _stored( + NotificationChannelType.APPRISE, service="discord", fields=DISCORD + ) + + await update_channel(stored, USER, {"name": "Old phone"}) + with pytest.raises(ChannelError, match="Only admins"): + await update_channel(stored, USER, {}, fields=DISCORD) + async def test_turning_it_back_on_forgets_past_failures(self, db): - stored = _stored(url="https://hooks.example.com/a", format="json") + stored = _stored(url="https://hooks.example.com/a") stored.enabled = False updated = await update_channel(stored, USER, {"enabled": True}) diff --git a/backend/tests/handler/notification_channels/test_delivery.py b/backend/tests/handler/notification_channels/test_delivery.py index 948940c16..f37fff322 100644 --- a/backend/tests/handler/notification_channels/test_delivery.py +++ b/backend/tests/handler/notification_channels/test_delivery.py @@ -1,15 +1,20 @@ -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock import pytest -from handler.notification_channels import delivery +from handler.notification_channels import apprise_channel, delivery, webhook +from handler.notification_channels.apprise_channel import AppriseError +from handler.notification_channels.config import seal_config from handler.notification_channels.delivery import ( deliver_to_channel, enqueue_channel_deliveries, forwards, + sample_message, + send_to_channel, ) from handler.notification_channels.webhook import WebhookError from models.notification import NotificationKind, NotificationLevel, NotificationTopic +from models.notification_channel import NotificationChannelType from models.user import Role from .fixtures import make_notification @@ -88,6 +93,44 @@ class TestEnqueue: enqueue_channel_deliveries([(5, make_notification())]) +class TestSendToChannel: + async def test_an_apprise_channel_goes_out_through_apprise(self, mocker): + send = mocker.patch.object(apprise_channel, "send") + channel = _channel( + type=NotificationChannelType.APPRISE, + config=seal_config({"service": "ntfy", "fields": {"targets": ["romm"]}}), + ) + message = sample_message() + + await send_to_channel(channel, message, allow_private=True) + + send.assert_called_once_with("ntfy", {"targets": ["romm"]}, message) + + async def test_only_an_admins_apprise_channel_goes_out(self, mocker): + send = mocker.patch.object(apprise_channel, "send") + channel = _channel( + type=NotificationChannelType.APPRISE, + config=seal_config({"service": "ntfy", "fields": {"targets": ["romm"]}}), + ) + + with pytest.raises(AppriseError, match="Only admins"): + await send_to_channel(channel, sample_message(), allow_private=False) + + send.assert_not_called() + + async def test_a_webhook_gets_its_url_and_secret(self, mocker): + send = mocker.patch.object(webhook, "send", AsyncMock()) + channel = _channel( + type=NotificationChannelType.WEBHOOK, + config=seal_config({"url": "https://hooks.example.com", "secret": "k"}), + ) + + await send_to_channel(channel, sample_message(), allow_private=False) + + config, _ = send.await_args.args + assert config == {"url": "https://hooks.example.com", "secret": "k"} + + class TestDeliverToChannel: @pytest.fixture def db(self, mocker): diff --git a/backend/tests/handler/notification_channels/test_webhook.py b/backend/tests/handler/notification_channels/test_webhook.py index 9ae0b0dc6..ff4fed7e6 100644 --- a/backend/tests/handler/notification_channels/test_webhook.py +++ b/backend/tests/handler/notification_channels/test_webhook.py @@ -14,10 +14,7 @@ from handler.notification_channels.webhook import ( build_request, check_url, send, - split_ntfy_url, ) -from models.notification import NotificationLevel -from models.notification_channel import WebhookFormat from .fixtures import make_actor, make_notification @@ -31,10 +28,10 @@ def _message(**overrides) -> OutboundMessage: ) -class TestJsonFormat: +class TestBuildRequest: def test_carries_the_notification_and_its_text(self): request = build_request( - WebhookConfig(url="https://hooks.example.com/romm", format="json"), + WebhookConfig(url="https://hooks.example.com/romm"), _message(actor=make_actor()), ) @@ -48,7 +45,7 @@ class TestJsonFormat: def test_is_signed_with_the_secret(self): request = build_request( - WebhookConfig(url="https://hooks.example.com", format="json", secret="k"), + WebhookConfig(url="https://hooks.example.com", secret="k"), _message(), ) @@ -56,101 +53,18 @@ class TestJsonFormat: assert request.headers[webhook.SIGNATURE_HEADER] == f"sha256={expected}" -class TestDiscordFormat: - def test_sends_an_embed_that_pings_nobody(self): - request = build_request( - WebhookConfig(url="https://discord.com/api/webhooks/1/t", format="discord"), - _message(level=NotificationLevel.ERROR, actor=make_actor()), - "#romm", - ) - - payload = json.loads(request.content) - [embed] = payload["embeds"] - assert embed["title"] == "Maintenance tonight" - assert embed["description"] == "RomM restarts at 23:00" - assert embed["url"] == "https://romm.example.com/platforms" - assert embed["color"] == webhook.DISCORD_COLORS[NotificationLevel.ERROR] - assert embed["footer"] == {"text": "#romm · From admin"} - assert payload["allowed_mentions"] == {"parse": []} - - def test_names_the_channel_alone_without_a_sender(self): - request = build_request( - WebhookConfig(url="https://discord.com/api/webhooks/1/t", format="discord"), - _message(), - "#romm", - ) - - [embed] = json.loads(request.content)["embeds"] - assert embed["footer"] == {"text": "#romm"} - - def test_keeps_within_discords_limits(self): - message = OutboundMessage( - notification=make_notification(), - title="t" * 300, - body="b" * 5000, - url=None, - ) - - [embed] = json.loads( - build_request( - WebhookConfig( - url="https://discord.com/api/webhooks/1/t", format="discord" - ), - message, - ).content - )["embeds"] - - assert (len(embed["title"]), len(embed["description"])) == (256, 4096) - assert "url" not in embed - - -class TestNtfyFormat: - def test_publishes_json_to_the_server_with_the_topic(self): - request = build_request( - WebhookConfig( - url="https://ntfy.example.com/sub/romm", format="ntfy", secret="tk_1" - ), - _message(level=NotificationLevel.ERROR), - ) - - payload = json.loads(request.content) - assert request.url == "https://ntfy.example.com/sub" - assert payload["topic"] == "romm" - assert payload["message"] == "RomM restarts at 23:00" - assert payload["priority"] == webhook.NTFY_ERROR_PRIORITY - assert payload["click"] == "https://romm.example.com/platforms" - assert request.headers["Authorization"] == "Bearer tk_1" - assert webhook.SIGNATURE_HEADER not in request.headers - - @pytest.mark.parametrize( - "url,expected", - [ - ("https://ntfy.sh/romm", ("https://ntfy.sh/", "romm")), - ("https://host/ntfy/romm/", ("https://host/ntfy", "romm")), - ], - ) - def test_splits_a_topic_url(self, url, expected): - assert split_ntfy_url(url) == expected - - def test_a_url_without_a_topic_is_refused(self): - with pytest.raises(ValueError, match="topic"): - split_ntfy_url("https://ntfy.sh/") - - class TestCheckUrl: @pytest.mark.parametrize("url", ["ftp://example.com/x", "not a url", "https://"]) def test_refuses_anything_but_http(self, url): with pytest.raises(ValueError): - check_url(url, WebhookFormat.JSON, allow_private=True) + check_url(url, allow_private=True) def test_keeps_a_user_off_the_local_network(self): with pytest.raises(ValueError): - check_url( - "http://192.168.1.10/hook", WebhookFormat.JSON, allow_private=False - ) + check_url("http://192.168.1.10/hook", allow_private=False) def test_lets_an_admin_reach_the_local_network(self): - check_url("http://192.168.1.10/hook", WebhookFormat.JSON, allow_private=True) + check_url("http://192.168.1.10/hook", allow_private=True) @pytest.mark.parametrize( "url", @@ -162,7 +76,7 @@ class TestCheckUrl: ) def test_refuses_a_port_that_isnt_one(self, url): with pytest.raises(ValueError, match="port"): - check_url(url, WebhookFormat.JSON, allow_private=True) + check_url(url, allow_private=True) def _serve(mocker, handler) -> None: @@ -173,7 +87,7 @@ def _serve(mocker, handler) -> None: ) -_CONFIG = WebhookConfig(url="https://hooks.example.com/romm", format="json") +_CONFIG = WebhookConfig(url="https://hooks.example.com/romm") class TestSend: @@ -207,14 +121,10 @@ class TestSend: async def test_a_refusal_says_who_refused_and_why(self, respond): respond(404, '{"message": "Unknown Webhook"}') - with pytest.raises(WebhookError, match="discord.com answered 404: .*Unknown"): - await send( - WebhookConfig( - url="https://discord.com/api/webhooks/1/t", format="discord" - ), - _message(), - allow_private=False, - ) + with pytest.raises( + WebhookError, match="hooks.example.com answered 404: .*Unknown" + ): + await send(_CONFIG, _message(), allow_private=False) async def test_a_redirect_is_a_delivery_that_did_not_land(self, mocker): _serve( diff --git a/backend/tests/handler/sync/test_comparison.py b/backend/tests/handler/sync/test_comparison.py index ece41358a..c4f7b6a6a 100644 --- a/backend/tests/handler/sync/test_comparison.py +++ b/backend/tests/handler/sync/test_comparison.py @@ -2,7 +2,11 @@ from datetime import datetime, timezone -from handler.sync.comparison import SyncComparisonResult, compare_save_state +from handler.sync.comparison import ( + SyncComparisonResult, + compare_missing_server_save, + compare_save_state, +) class TestCompareIdenticalHashes: @@ -141,3 +145,20 @@ class TestCompareReturnType: assert isinstance(result, SyncComparisonResult) assert isinstance(result.action, str) assert isinstance(result.reason, str) + + +class TestCompareMissingServerSave: + def test_a_version_the_slot_lost_is_deleted(self): + result = compare_missing_server_save("abc123", ["def456", "abc123"]) + assert result.action == "delete" + + def test_bytes_nobody_deleted_are_uploaded(self): + # Offering it back costs a deletion that misses that device; deleting + # it would cost the save. + assert compare_missing_server_save("fresh", ["abc123"]).action == "upload" + + def test_a_client_that_reports_no_digest_is_uploaded(self): + assert compare_missing_server_save(None, ["abc123"]).action == "upload" + + def test_a_slot_that_lost_nothing_is_uploaded(self): + assert compare_missing_server_save("abc123", ()).action == "upload" diff --git a/backend/tests/handler/test_db_handler.py b/backend/tests/handler/test_db_handler.py index d1fc1333f..f9845ab91 100644 --- a/backend/tests/handler/test_db_handler.py +++ b/backend/tests/handler/test_db_handler.py @@ -32,9 +32,9 @@ def test_platforms(): platforms = db_platform_handler.get_platforms() assert len(platforms) == 1 - platform = db_platform_handler.get_platform_by_fs_slug(platform.fs_slug) - assert platform is not None - assert platform.name == "test_platform" + fetched = db_platform_handler.get_platform_by_fs_slug(platform.fs_slug) + assert fetched is not None + assert fetched.name == "test_platform" db_platform_handler.mark_missing_platforms([]) platforms = db_platform_handler.get_platforms() @@ -509,13 +509,17 @@ def test_primary_region_mirrors_the_first_parsed_region(platform: Platform): """The generated column tracks regions[0] without the scan writing it.""" rom = _add_sibling(platform, "(USA, Europe)", 4321, ["USA", "Europe"]) - assert db_rom_handler.get_rom(rom.id).generated_primary_region == "USA" + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + assert refreshed.generated_primary_region == "USA" def test_primary_region_is_null_without_region_tags(platform: Platform): rom = _add_sibling(platform, "(Unknown)", 4322, []) - assert db_rom_handler.get_rom(rom.id).generated_primary_region is None + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None + assert refreshed.generated_primary_region is None def test_group_by_meta_id_prefers_the_higher_priority_region(platform: Platform): @@ -759,17 +763,21 @@ def test_bulk_mark_present_skips_already_present(platform: Platform): ) ) - present_updated_at = db_rom_handler.get_rom(present.id).updated_at + present_before = db_rom_handler.get_rom(present.id) + assert present_before is not None + present_updated_at = present_before.updated_at db_rom_handler.bulk_mark_present(platform.id, [present.id, missing.id]) # Already-present ROM is not re-stamped. present_after = db_rom_handler.get_rom(present.id) + assert present_after is not None assert present_after.missing_from_fs is False assert present_after.updated_at == present_updated_at # Actually-missing ROM is flipped to present. missing_after = db_rom_handler.get_rom(missing.id) + assert missing_after is not None assert missing_after.missing_from_fs is False diff --git a/backend/tests/handler/test_rom_files.py b/backend/tests/handler/test_rom_files.py index ff509ddcb..c75a2721a 100644 --- a/backend/tests/handler/test_rom_files.py +++ b/backend/tests/handler/test_rom_files.py @@ -71,11 +71,17 @@ def _folder_rom( sha1_hash="row-sha1", ) ) - return db_rom_handler.get_rom(rom.id) + return _reload(rom.id) + + +def _reload(rom_id: int) -> Rom: + rom = db_rom_handler.get_rom(rom_id) + assert rom is not None + return rom def _files_by_name(rom_id: int) -> dict[str, RomFile]: - return {f.file_name: f for f in db_rom_handler.get_rom(rom_id).files} + return {f.file_name: f for f in _reload(rom_id).files} async def test_registers_new_nested_file(platform, admin_user, library): @@ -92,7 +98,7 @@ async def test_registers_new_nested_file(platform, admin_user, library): assert ( new.md5_hash == hashlib.md5(b"patch bytes", usedforsecurity=False).hexdigest() ) - after = db_rom_handler.get_rom(rom.id) + after = _reload(rom.id) assert after.fs_size_bytes == len(b"game") + len(b"readme") + len(b"patch bytes") assert after.md5_hash == "stored-md5" @@ -110,7 +116,7 @@ async def test_top_level_addition_updates_rom_hashes_and_size( hashlib.md5(a + b, usedforsecurity=False).hexdigest() for a, b in ((b"game", b"extra"), (b"extra", b"game")) } - after = db_rom_handler.get_rom(rom.id) + after = _reload(rom.id) assert after.md5_hash in either_order assert after.fs_size_bytes == len(b"game") + len(b"extra") assert ( @@ -144,18 +150,18 @@ async def test_removes_rows_for_vanished_files(platform, admin_user, library): assert result.removed_files == 1 assert set(_files_by_name(rom.id)) == {"game.bin"} # A nested file leaves the top level, and so the rom hash, alone. - assert db_rom_handler.get_rom(rom.id).md5_hash == "stored-md5" + assert _reload(rom.id).md5_hash == "stored-md5" async def test_clears_missing_flag(platform, admin_user, library): rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"}) db_rom_handler.update_rom(rom.id, {"missing_from_fs": True}) - rom = db_rom_handler.get_rom(rom.id) + rom = _reload(rom.id) result = await refresh_rom_files(rom) assert not result.changed - assert db_rom_handler.get_rom(rom.id).missing_from_fs is False + assert _reload(rom.id).missing_from_fs is False async def test_empty_folder_keeps_recorded_rows(platform, admin_user, library): @@ -176,7 +182,7 @@ async def test_edited_file_is_rehashed_in_place(platform, admin_user, library): result = await refresh_rom_files(rom) assert result.updated_files == 1 - after = db_rom_handler.get_rom(rom.id) + after = _reload(rom.id) assert after.files[0].id == row_id assert ( after.files[0].md5_hash @@ -212,7 +218,7 @@ async def test_disabled_hashing_keeps_stored_rom_hashes( result = await refresh_rom_files(rom) assert result.new_files == 1 - after = db_rom_handler.get_rom(rom.id) + after = _reload(rom.id) assert (after.crc_hash, after.md5_hash, after.sha1_hash) == ( "stored-crc", "stored-md5", @@ -264,9 +270,10 @@ async def test_a_newly_read_identity_is_persisted(platform, admin_user, library) "get_rom_files", AsyncMock(return_value=_unchanged_parse(rom, identity)), ): - await refresh_rom_files(rom) + result = await refresh_rom_files(rom) - refreshed = db_rom_handler.get_rom(rom.id) + assert result.changed + refreshed = _reload(rom.id) assert refreshed.title_id == "0100ABCD12340000" assert refreshed.save_target == "0100ABCD12340000" assert refreshed.save_target_layout == SaveTargetLayout.FOLDER_EXACT @@ -277,7 +284,7 @@ async def test_a_stored_identity_survives_a_parse_that_read_none( ): rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"}) db_rom_handler.update_rom(rom.id, {"title_id": "ULUS-10041"}) - rom = db_rom_handler.get_rom(rom.id) + rom = _reload(rom.id) with patch.object( fs_rom_handler, @@ -286,4 +293,22 @@ async def test_a_stored_identity_survives_a_parse_that_read_none( ): await refresh_rom_files(rom) - assert db_rom_handler.get_rom(rom.id).title_id == "ULUS-10041" + assert _reload(rom.id).title_id == "ULUS-10041" + + +async def test_a_category_settled_on_a_reused_row_is_persisted( + platform, admin_user, library +): + """Extraction settles a Switch file's category on the row it reused.""" + rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"}) + + async def settle_category(*_args, **_kwargs) -> ParsedRomFiles: + parsed = _unchanged_parse(rom, RomIdentity()) + parsed.rom_files[0].category = RomFileCategory.DLC + return parsed + + with patch.object(fs_rom_handler, "get_rom_files", settle_category): + result = await refresh_rom_files(rom) + + assert result.updated_files == 1 + assert _files_by_name(rom.id)["game.bin"].category == RomFileCategory.DLC diff --git a/backend/tests/handler/test_socket_handler.py b/backend/tests/handler/test_socket_handler.py index 6b71869b3..0e610ad76 100644 --- a/backend/tests/handler/test_socket_handler.py +++ b/backend/tests/handler/test_socket_handler.py @@ -4,16 +4,19 @@ from unittest.mock import AsyncMock, MagicMock import pytest from handler import socket_handler as socket_handler_module +from handler.database import db_user_handler from handler.socket_handler import ( LOGIN_SESSION_ID_KEY, SocketHandler, + close_login_session_sockets, netplay_socket_handler, socket_handler, ) +from utils import auth as auth_utils def test_netplay_cannot_join_the_main_servers_rooms(): - # Netplay clients are unauthenticated and name their own rooms, so an emit to + # Netplay clients may be anonymous and name their own rooms, so an emit to # `user:{id}` or `admin` must not reach a netplay socket that picked that name. netplay = netplay_socket_handler.socket_server.manager main = socket_handler.socket_server.manager @@ -89,7 +92,7 @@ class TestLoginSessionSockets: await handler.bind_to_login_session("sid-1", "s1") - cache.sadd.assert_awaited_once_with("session_sockets:s1", "sid-1") + cache.sadd.assert_awaited_once_with("session_sockets:socketio:s1", "sid-1") cache.expire.assert_awaited_once() assert socket_session == {LOGIN_SESSION_ID_KEY: "s1"} @@ -103,7 +106,7 @@ class TestLoginSessionSockets: await handler.unbind_from_login_session("sid-1") - cache.srem.assert_awaited_once_with("session_sockets:s1", "sid-1") + cache.srem.assert_awaited_once_with("session_sockets:socketio:s1", "sid-1") async def test_unbinding_an_anonymous_socket_touches_nothing(self, mocker, cache): handler = SocketHandler(path="/test") @@ -124,7 +127,7 @@ class TestLoginSessionSockets: await handler.close_login_sessions(["s1"]) - cache.delete.assert_awaited_once_with("session_sockets:s1") + cache.delete.assert_awaited_once_with("session_sockets:socketio:s1") disconnect.assert_awaited_once_with("sid-1") async def test_a_broker_failure_moves_on_to_the_next_session(self, mocker, cache): @@ -139,3 +142,70 @@ class TestLoginSessionSockets: await handler.close_login_sessions(["s1", "s2"]) assert disconnect.await_count == 2 + + async def test_each_server_keeps_its_own_sockets(self, mocker, cache): + handler = SocketHandler(path="/test", channel="netplay") + + @asynccontextmanager + async def session(sid: str): + yield {} + + mocker.patch.object(handler.socket_server, "session", session) + + await handler.bind_to_login_session("sid-1", "s1") + + cache.sadd.assert_awaited_once_with("session_sockets:netplay:s1", "sid-1") + + +async def test_revoking_a_session_closes_its_sockets_on_every_server(mocker): + main = mocker.patch.object(socket_handler, "close_login_sessions", AsyncMock()) + netplay = mocker.patch.object( + netplay_socket_handler, "close_login_sessions", AsyncMock() + ) + + await close_login_session_sockets(["s1"]) + + main.assert_awaited_once_with(["s1"]) + netplay.assert_awaited_once_with(["s1"]) + + +class TestAuthenticate: + @pytest.fixture + def handler(self) -> SocketHandler: + return SocketHandler(path="/test") + + @pytest.fixture + def bind(self, mocker, handler) -> AsyncMock: + return mocker.patch.object(handler, "bind_to_login_session", AsyncMock()) + + @pytest.fixture + def user(self, mocker) -> MagicMock: + user = MagicMock(enabled=True) + mocker.patch.object(db_user_handler, "get_user_by_username", return_value=user) + return user + + def _session(self, mocker, **session) -> None: + mocker.patch.object( + auth_utils, "get_session_from_environ", AsyncMock(return_value=session) + ) + + async def test_resolves_and_binds_a_login_session( + self, mocker, handler, bind, user + ): + self._session(mocker, iss="romm:auth", sub="sam", session_id="s1") + + assert await handler.authenticate("sid-1", {}) is user + bind.assert_awaited_once_with("sid-1", "s1") + + async def test_rejects_a_foreign_issuer(self, mocker, handler, bind, user): + self._session(mocker, iss="other", sub="sam", session_id="s1") + + assert await handler.authenticate("sid-1", {}) is None + bind.assert_not_awaited() + + async def test_rejects_a_disabled_user(self, mocker, handler, bind, user): + user.enabled = False + self._session(mocker, iss="romm:auth", sub="sam", session_id="s1") + + assert await handler.authenticate("sid-1", {}) is None + bind.assert_not_awaited() diff --git a/backend/tests/models/test_rom.py b/backend/tests/models/test_rom.py index 28f67f5fc..2bee89b16 100644 --- a/backend/tests/models/test_rom.py +++ b/backend/tests/models/test_rom.py @@ -52,6 +52,28 @@ def test_rom_with_libretro_match_is_identified(rom: Rom): assert rom.is_identified is True +@pytest.mark.parametrize( + "fs_path, fs_name, file_path, file_name, expected", + [ + ("roms/ps2", "gta.iso", "roms/ps2", "gta.iso", True), + ("roms/ps2/Action", "gta.iso", "roms/ps2/Action", "gta.iso", True), + ("ps2", "gta.iso", "ps2", "gta.iso", True), + ("roms/ps2", "FF X", "roms/ps2/FF X", "disc1.iso", True), + ("ps2", "FF X", "ps2/FF X", "disc1.iso", True), + ("roms/ps2/RPG", "FF X", "roms/ps2/RPG/FF X", "disc1.iso", True), + ("roms/ps2", "FF X", "roms/ps2/FF X/dlc", "extra.bin", False), + ("ps2", "FF X", "ps2/FF X/dlc", "extra.bin", False), + ], +) +def test_is_top_level_at_any_folder_depth( + fs_path: str, fs_name: str, file_path: str, file_name: str, expected: bool +): + rom = Rom(fs_path=fs_path, fs_name=fs_name) + file = RomFile(rom=rom, file_path=file_path, file_name=file_name) + + assert file.is_top_level is expected + + def _archive(**kwargs) -> RomFile: return RomFile( file_name="sf2.zip", diff --git a/backend/tests/streaming_stubs.py b/backend/tests/streaming_stubs.py new file mode 100644 index 000000000..89ba8a39d --- /dev/null +++ b/backend/tests/streaming_stubs.py @@ -0,0 +1,20 @@ +"""Streaming queue stub shared by the streaming endpoint and reaper tests.""" + +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Any +from unittest.mock import MagicMock, patch + +from handler.streaming import background + + +@contextmanager +def exit_pulls_spawned_inline() -> Iterator[MagicMock]: + """Run each queued exit save pull as a spawned task, as no worker runs here.""" + + def enqueue(func: Any, *, kwargs: dict[str, Any], **_: Any) -> None: + background.spawn_sync_task(func(**kwargs)) + + with patch("handler.streaming.lifecycle.streaming_queue") as queue: + queue.enqueue.side_effect = enqueue + yield queue diff --git a/backend/tests/tasks/test_cron_config.py b/backend/tests/tasks/test_cron_config.py index 1e512aa82..d02e00956 100644 --- a/backend/tests/tasks/test_cron_config.py +++ b/backend/tests/tasks/test_cron_config.py @@ -27,6 +27,8 @@ def _task(mocker, *, enabled=True, cron_string="0 4 * * *", task_type=TaskType.C task.enabled = enabled task.cron_string = cron_string task.timeout = 100 + task.result_ttl = TASK_RESULT_TTL + task.queue_name = QueuePrio.LOW.value task.title = "Test Task" task.description = "test task" task.task_type = task_type @@ -72,6 +74,13 @@ class TestCronConfig: register = registered(tasks) assert register.call_args.args[1] == QueuePrio.LOW.value + def test_a_task_can_name_its_own_queue(self, mocker, registered): + task = _task(mocker) + task.queue_name = "streaming" + register = registered({"reaper": task}) + + assert register.call_args.args[1] == "streaming" + def test_history_outlives_rq_s_own_result_ttl(self, mocker, registered): # `register()` defaults this, and a default is written onto the job, so # leaving it out would pin every cron job to RQ's 500 seconds. @@ -79,6 +88,13 @@ class TestCronConfig: assert register.call_args.kwargs["result_ttl"] == TASK_RESULT_TTL + def test_a_task_can_keep_no_history(self, mocker, registered): + task = _task(mocker) + task.result_ttl = 0 + register = registered({"frequent": task}) + + assert register.call_args.kwargs["result_ttl"] == 0 + def test_each_entry_gets_its_own_cron_identity(self, mocker, registered): # Every entry runs the same function, so an unnamed one would inherit # that func name and share one job history with all the others. diff --git a/backend/tests/tasks/test_reap_streaming_sessions.py b/backend/tests/tasks/test_reap_streaming_sessions.py new file mode 100644 index 000000000..130f209d6 --- /dev/null +++ b/backend/tests/tasks/test_reap_streaming_sessions.py @@ -0,0 +1,324 @@ +import asyncio +import json +from collections.abc import Iterator +from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from tests.streaming_stubs import exit_pulls_spawned_inline + +from handler.redis_handler import STREAMING_QUEUE_NAME, async_cache +from handler.streaming import commands, session_store +from handler.streaming.config import ResolvedContainer, reset_cache, resolve_entry +from tasks.registry import SCHEDULED_TASKS +from tasks.scheduled.reap_streaming_sessions import ( + ReapStreamingSessionsTask, + reap_streaming_sessions_task, +) +from tasks.tasks import run_task_by_name + +N64 = { + "platform": "n64", + "host": "http://192.168.1.10:3000", + "broker_host": "http://192.168.1.10:8000", +} +PSX = { + "platform": "psx", + "host": "http://192.168.1.11:3000", + "broker_host": "http://192.168.1.11:8000", +} + + +@pytest.fixture(autouse=True) +async def clear_streaming_sessions(): + await async_cache.flushall() + + +@pytest.fixture(autouse=True) +def exit_pull_queue(): + with exit_pulls_spawned_inline() as queue: + yield queue + + +@contextmanager +def _streaming(*containers: dict, enabled: bool = True) -> Iterator[None]: + cfg = MagicMock() + cfg.STREAMING_ENABLED = enabled + cfg.STREAMING_CONTAINERS = list(containers) + reset_cache() + with patch("handler.streaming.config.cm.get_config", return_value=cfg): + try: + yield + finally: + reset_cache() + + +def _resolved(entry: dict) -> ResolvedContainer: + container = resolve_entry(entry) + assert container is not None + return container + + +def _ago(seconds: int) -> str: + return (datetime.now(timezone.utc) - timedelta(seconds=seconds)).isoformat() + + +async def _hold(entry: dict, *, idle_seconds: int, **fields: Any) -> dict[str, Any]: + """Store a claim on `entry` whose heartbeat is `idle_seconds` old.""" + session = { + "user_id": 1, + "platform": entry["platform"], + "claimed_at": _ago(idle_seconds + 600), + "last_seen": _ago(idle_seconds), + **fields, + } + await async_cache.set( + session_store.session_redis_key(_resolved(entry).key), json.dumps(session) + ) + return session + + +def _stub_teardown(teardown: Any = None) -> Any: + return patch( + "tasks.scheduled.reap_streaming_sessions.teardown_abandoned_session", + new=teardown or AsyncMock(return_value=True), + ) + + +async def _stored(entry: dict) -> dict[str, Any] | None: + return await session_store.get_session(_resolved(entry).key) + + +STALE = session_store._STREAMING_SESSION_STALE_SECONDS + 60 + + +def test_the_reaper_runs_every_minute(): + assert SCHEDULED_TASKS["reap_streaming_sessions"] is reap_streaming_sessions_task + assert reap_streaming_sessions_task.cron_string == "* * * * *" + + +@pytest.mark.parametrize("enabled", [True, False]) +def test_the_reaper_is_scheduled_only_with_streaming_on(enabled: bool): + with _streaming(N64, enabled=enabled): + assert ReapStreamingSessionsTask().enabled is enabled + + +def test_the_job_outlives_a_slow_teardown(): + """RQ kills a job at its timeout, and a teardown may hold its marker right + up to the ceiling.""" + assert reap_streaming_sessions_task.timeout >= session_store.HOLD_CEILING_SECONDS + + +def test_the_reaper_has_a_worker_of_its_own(): + """A teardown can hold its job for minutes, and the shared worker would + make every other task wait behind it.""" + assert reap_streaming_sessions_task.queue_name == STREAMING_QUEUE_NAME + + +def test_a_run_keeps_no_job_history(): + """At one run a minute, a day of kept results would bury every other task.""" + assert reap_streaming_sessions_task.result_ttl == 0 + + +async def test_a_stale_session_goes_through_the_abandoned_teardown(): + with _streaming(N64): + session = await _hold(N64, idle_seconds=STALE) + with _stub_teardown() as teardown: + await ReapStreamingSessionsTask().run() + + teardown.assert_awaited_once_with( + _resolved(N64), _resolved(N64).key, session, claimed_by=None + ) + + +async def test_fresh_sessions_and_drain_markers_are_left_alone(): + with _streaming(N64, PSX): + await _hold(N64, idle_seconds=10) + await async_cache.set( + session_store.session_redis_key(_resolved(PSX).key), + session_store.drain_marker("draining"), + ) + with _stub_teardown() as teardown: + await ReapStreamingSessionsTask().run() + + teardown.assert_not_awaited() + + +async def test_a_shared_container_tears_down_under_the_sessions_own_platform(): + """Records sharing a key differ in emulator and card sync, so the session's + saves have to go out under the platform it was claimed for.""" + shared = { + "host": N64["host"], + "broker_host": N64["broker_host"], + "platforms": {"n64": "mupen64plus", "psx": "duckstation"}, + } + with _streaming(shared): + await _hold(N64, idle_seconds=STALE, platform="psx") + with _stub_teardown() as teardown: + await ReapStreamingSessionsTask().run() + + teardown.assert_awaited_once() + (record, _, _), _ = teardown.call_args + assert record.platform == "psx" + + +async def test_one_failing_container_does_not_cut_the_others_short(): + """The job's event loop stops when the run returns, so a sibling teardown + still in flight would be frozen partway.""" + finished: list[str] = [] + + async def teardown(record: ResolvedContainer, *args: Any, **kwargs: Any) -> bool: + if record.platform == "n64": + raise ConnectionError("redis went away") + await asyncio.sleep(0.05) + finished.append(record.platform) + return True + + with _streaming(N64, PSX): + await _hold(N64, idle_seconds=STALE) + await _hold(PSX, idle_seconds=STALE) + with _stub_teardown(teardown): + await ReapStreamingSessionsTask().run() + + assert finished == ["psx"] + + +async def test_nothing_runs_while_streaming_is_disabled(): + with _streaming(N64, enabled=False): + await _hold(N64, idle_seconds=STALE) + with _stub_teardown() as teardown: + await ReapStreamingSessionsTask().run() + + teardown.assert_not_awaited() + + +async def test_nothing_is_reaped_right_after_a_backend_restart(): + """No heartbeat lands while the backend is down, though the stream plays on.""" + with _streaming(N64): + await _hold(N64, idle_seconds=STALE) + await session_store.start_restart_grace() + with _stub_teardown() as teardown: + await ReapStreamingSessionsTask().run() + + teardown.assert_not_awaited() + + +async def test_reaping_resumes_once_the_restart_grace_lapses(): + with _streaming(N64): + await _hold(N64, idle_seconds=STALE) + await session_store.start_restart_grace() + await async_cache.delete(session_store._RESTART_GRACE_KEY) + with _stub_teardown() as teardown: + await ReapStreamingSessionsTask().run() + + teardown.assert_awaited_once() + + +async def test_the_restart_grace_lasts_one_stale_window(): + await session_store.start_restart_grace() + + ttl = await async_cache.ttl(session_store._RESTART_GRACE_KEY) + assert 0 < ttl <= session_store._STREAMING_SESSION_STALE_SECONDS + + +async def test_a_reaped_session_frees_its_container_and_leaves_a_notice(): + with _streaming(N64): + session = await _hold(N64, idle_seconds=STALE) + with ( + patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(return_value=commands.StopOutcome()), + ) as quiesce, + patch("handler.streaming.lifecycle.record_play_session") as played, + ): + await ReapStreamingSessionsTask().run() + + quiesce.assert_awaited_once() + played.assert_awaited_once_with(session) + assert await _stored(N64) is None + notice = await session_store.get_termination(_resolved(N64).key, 1) + assert notice is not None and notice["reason"] == "abandoned" + + +async def test_a_failure_before_the_stop_leaves_the_session_for_the_next_run(): + """Freeing the container then would let a claim launch over an emulator still + running on a card nobody evacuated.""" + with _streaming(N64): + session = await _hold(N64, idle_seconds=STALE) + with ( + patch( + "handler.streaming.lifecycle.mark_exit_saves_pending", + side_effect=[ConnectionError("redis blinked"), None], + ), + patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(return_value=commands.StopOutcome()), + ) as quiesce, + patch("handler.streaming.lifecycle.record_play_session"), + ): + await ReapStreamingSessionsTask().run() + quiesce.assert_not_awaited() + assert await _stored(N64) == session + + await ReapStreamingSessionsTask().run() + + quiesce.assert_awaited_once() + assert await _stored(N64) is None + + +async def test_a_reaped_session_queues_its_exit_save_pull(exit_pull_queue: MagicMock): + exit_pull_queue.enqueue.side_effect = None + with _streaming(N64): + await _hold(N64, idle_seconds=STALE, rom_id=7) + with ( + patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(return_value=commands.StopOutcome()), + ), + patch("handler.streaming.lifecycle.record_play_session"), + # The registry's instance read the config at import, with streaming off. + patch.object(reap_streaming_sessions_task, "enabled", True), + ): + await run_task_by_name("reap_streaming_sessions") + + exit_pull_queue.enqueue.assert_called_once() + assert exit_pull_queue.enqueue.call_args.kwargs["kwargs"]["rom_id"] == 7 + + +async def test_overlapping_runs_tear_a_session_down_once(): + """Two workers can both see the same stale session; the drain marker's + compare-and-set lets only one of them stop the emulator.""" + stops = 0 + + async def quiesce(*args: Any, **kwargs: Any) -> commands.StopOutcome: + nonlocal stops + stops += 1 + await asyncio.sleep(0.05) + return commands.StopOutcome() + + # Both runs read the stale session before either marks it. + both_read = asyncio.Barrier(2) + + async def read_together(key: str) -> dict[str, Any] | None: + session = await session_store.get_abandoned_session(key) + await both_read.wait() + return session + + with _streaming(N64): + await _hold(N64, idle_seconds=STALE) + with ( + patch( + "tasks.scheduled.reap_streaming_sessions.get_abandoned_session", + new=read_together, + ), + patch("handler.streaming.lifecycle.quiesce_container", new=quiesce), + patch("handler.streaming.lifecycle.record_play_session"), + ): + await asyncio.gather( + ReapStreamingSessionsTask().run(), ReapStreamingSessionsTask().run() + ) + + assert stops == 1 + assert await _stored(N64) is None diff --git a/backend/tests/tasks/test_tasks.py b/backend/tests/tasks/test_tasks.py index afda3c9c2..2e48c8f93 100644 --- a/backend/tests/tasks/test_tasks.py +++ b/backend/tests/tasks/test_tasks.py @@ -1,3 +1,4 @@ +import asyncio from unittest.mock import AsyncMock, MagicMock, patch import httpx @@ -14,6 +15,7 @@ from tasks.tasks import ( report_task_failure, run_task_by_name, ) +from utils.background_tasks import fire_and_forget class ConcretePeriodicTask(PeriodicTask): @@ -186,6 +188,26 @@ class TestRunTaskByName: with pytest.raises(TaskNotFoundException, match="some_task"): await run_task_by_name("some_task") + async def test_waits_for_what_the_task_spawned(self, mocker): + """RQ runs each job on a loop that never runs again once the job returns, + so work the task spawned and left running would be frozen partway.""" + finished = asyncio.Event() + + async def later() -> None: + await asyncio.sleep(0.05) + finished.set() + + async def run() -> None: + fire_and_forget(later()) + + task = MagicMock() + task.run = run + mocker.patch("tasks.registry.get_task", return_value=task) + + await run_task_by_name("some_task") + + assert finished.is_set() + @pytest.fixture def notify(mocker): @@ -221,6 +243,29 @@ class TestRunTaskByNameNotifications: assert data == {"task": "cleanup_missing_roms", "title": "Cleanup Missing ROMs"} notify_admins.assert_not_awaited() + async def test_reports_success_only_once_spawned_work_is_done(self, mocker, notify): + """Spawned work that then overran the job timeout would read as both a + success and a failure.""" + finished = asyncio.Event() + + async def later() -> None: + await asyncio.sleep(0.05) + finished.set() + + async def run() -> None: + fire_and_forget(later()) + + task = _task(mocker) + task.run = run + finished_when_notified: list[bool] = [] + notify.side_effect = lambda *args: finished_when_notified.append( + finished.is_set() + ) + + await run_task_by_name("cleanup_missing_roms", run_by_user_id=4) + + assert finished_when_notified == [True] + async def test_a_scheduled_success_stays_quiet(self, mocker, notify, notify_admins): _task(mocker, return_value=None) diff --git a/backend/tests/test_migrations.py b/backend/tests/test_migrations.py index 9bd22089d..6d31acf12 100644 --- a/backend/tests/test_migrations.py +++ b/backend/tests/test_migrations.py @@ -233,6 +233,8 @@ def _replay(connection: sa.Connection, filename: str) -> None: ("0130_notifications.py", "notifications"), ("0131_notification_channels.py", "notification_channels"), ("0132_audit_events.py", "audit_events"), + ("0135_drop_play_session_sync_link.py", "play_sessions"), + ("0136_deleted_assets.py", "deleted_assets"), ], ) def test_a_revision_replayed_over_the_migrated_schema_is_a_no_op( @@ -245,6 +247,29 @@ def test_a_revision_replayed_over_the_migrated_schema_is_a_no_op( assert _schema_of(connection, table) == before +def test_the_play_session_sync_link_revision_reverses_and_replays(): + """0135 drops a column whose constraint each dialect handles differently. + + MariaDB and MySQL index the foreign key themselves and refuse to drop the + column while it stands; PostgreSQL takes both with the column and needs the + index 0124 made. Each step is guarded, so both directions replay. + """ + migration = _load_migration("0135_drop_play_session_sync_link.py") + + with sync_engine.begin() as connection: + before = _schema_of(connection, "play_sessions") + with Operations.context(MigrationContext.configure(connection)): + migration.downgrade() + assert has_column(connection, "play_sessions", "sync_session_id") + + migration.downgrade() + migration.upgrade() + migration.upgrade() + + assert not has_column(connection, "play_sessions", "sync_session_id") + assert _schema_of(connection, "play_sessions") == before + + def test_the_rom_similarity_revision_fills_in_a_missing_index(): """0122 meets its own table on a replay, with only some of its indexes. diff --git a/backend/tests/utils/test_background_tasks.py b/backend/tests/utils/test_background_tasks.py new file mode 100644 index 000000000..65a9a055f --- /dev/null +++ b/backend/tests/utils/test_background_tasks.py @@ -0,0 +1,49 @@ +import asyncio +from contextlib import suppress +from unittest.mock import patch + +from utils import background_tasks + + +async def test_waiting_skips_another_loops_tasks(): + """A task left on a loop that is not running can never finish.""" + other_loop = asyncio.new_event_loop() + stranded = other_loop.create_task(asyncio.sleep(60)) + background_tasks._background_tasks.add(stranded) + try: + await asyncio.wait_for(background_tasks.wait_for_background_tasks(), timeout=1) + finally: + background_tasks._background_tasks.discard(stranded) + stranded.cancel() + with suppress(asyncio.CancelledError): + await asyncio.to_thread(other_loop.run_until_complete, stranded) + other_loop.close() + + +async def test_waiting_covers_tasks_spawned_while_waiting(): + finished = asyncio.Event() + + async def second() -> None: + await asyncio.sleep(0.01) + finished.set() + + async def first() -> None: + await asyncio.sleep(0.01) + background_tasks.fire_and_forget(second()) + + background_tasks.fire_and_forget(first()) + await background_tasks.wait_for_background_tasks() + + assert finished.is_set() + + +async def test_waiting_logs_what_a_task_raised(): + async def failing() -> None: + raise ConnectionError("redis went away") + + background_tasks.fire_and_forget(failing()) + with patch.object(background_tasks, "log") as log: + await background_tasks.wait_for_background_tasks() + + log.error.assert_called_once() + assert isinstance(log.error.call_args.kwargs["exc_info"], ConnectionError) diff --git a/backend/tests/utils/test_gamelist_exporter.py b/backend/tests/utils/test_gamelist_exporter.py index 5ba929f69..66e956f7b 100644 --- a/backend/tests/utils/test_gamelist_exporter.py +++ b/backend/tests/utils/test_gamelist_exporter.py @@ -63,9 +63,10 @@ def platform_with_roms(admin_user: User): ) # Re-fetch to get joined metadata - rom = db_rom_handler.get_rom(rom.id) + refreshed = db_rom_handler.get_rom(rom.id) + assert refreshed is not None - return platform, [rom] + return platform, [refreshed] @pytest.fixture diff --git a/backend/tests/utils/test_openapi.py b/backend/tests/utils/test_openapi.py new file mode 100644 index 000000000..45815a64a --- /dev/null +++ b/backend/tests/utils/test_openapi.py @@ -0,0 +1,51 @@ +from fastapi import FastAPI +from pydantic import BaseModel + +from utils.openapi import publish_socket_payloads + + +class _Inner(BaseModel): + value: int + + +class _Payload(BaseModel): + name: str + inner: _Inner + + +class _Route(BaseModel): + ok: bool + + +def _app() -> FastAPI: + app = FastAPI() + + @app.get("/route") + def route() -> _Route: + return _Route(ok=True) + + publish_socket_payloads(app, [_Payload]) + return app + + +def test_payload_and_its_nested_models_join_route_schemas(): + schemas = _app().openapi()["components"]["schemas"] + + assert "_Route" in schemas + assert schemas["_Payload"]["properties"]["inner"] == { + "$ref": "#/components/schemas/_Inner" + } + assert "_Inner" in schemas + + +def test_schema_is_built_once(): + app = _app() + + assert app.openapi() is app.openapi() + + +def test_app_without_routes_still_gets_the_payloads(): + app = FastAPI() + publish_socket_payloads(app, [_Payload]) + + assert "_Payload" in app.openapi()["components"]["schemas"] diff --git a/backend/tools/generate_test_data.py b/backend/tools/generate_test_data.py index 0b3bb8d3c..7305266cb 100644 --- a/backend/tools/generate_test_data.py +++ b/backend/tools/generate_test_data.py @@ -1552,7 +1552,6 @@ def main() -> int: "user_id": uid, "device_id": dev, "rom_id": rng.choice(rom_id_list), - "sync_session_id": None, "save_slot": rng.choice(["1", "2", "auto", None]), "start_time": start, "end_time": start + timedelta(milliseconds=dur), diff --git a/backend/utils/archives.py b/backend/utils/archives.py index e1ca2bfa3..638442bd6 100644 --- a/backend/utils/archives.py +++ b/backend/utils/archives.py @@ -117,7 +117,7 @@ def read_tar_file( # Find the largest file among regular files only largest_file = max(regular_files, key=lambda x: x.size) - with f.extractfile(largest_file) as ef: # type: ignore + with f.extractfile(largest_file) as ef: # type: ignore[union-attr] with ef: while chunk := ef.read(FILE_READ_CHUNK_SIZE): yield chunk diff --git a/backend/utils/background_tasks.py b/backend/utils/background_tasks.py index ad215d86e..0ec6363dd 100644 --- a/backend/utils/background_tasks.py +++ b/backend/utils/background_tasks.py @@ -2,12 +2,25 @@ import asyncio from collections.abc import Coroutine from typing import Any +from logger.logger import log + # The event loop only holds weak refs to tasks; hold strong refs until they finish. _background_tasks: set[asyncio.Task[Any]] = set() -def fire_and_forget(coro: Coroutine[Any, Any, Any]) -> None: +def fire_and_forget(coro: Coroutine[Any, Any, Any]) -> asyncio.Task[Any]: """Schedule a coroutine without awaiting it.""" task = asyncio.create_task(coro) _background_tasks.add(task) task.add_done_callback(_background_tasks.discard) + return task + + +async def wait_for_background_tasks() -> None: + """Await every task scheduled on this loop, for a caller whose loop stops when it returns.""" + loop = asyncio.get_running_loop() + while pending := [task for task in _background_tasks if task.get_loop() is loop]: + # Gathering retrieves each exception, so asyncio no longer logs it for us. + for outcome in await asyncio.gather(*pending, return_exceptions=True): + if isinstance(outcome, Exception): + log.error("background task failed", exc_info=outcome) diff --git a/backend/utils/database.py b/backend/utils/database.py index 0d086cccd..e84e75186 100644 --- a/backend/utils/database.py +++ b/backend/utils/database.py @@ -24,7 +24,6 @@ POSTGRESQL_FK_INDEXES: tuple[tuple[str, str, str], ...] = ( ("music_favorite_tracks", "ix_music_favorite_tracks_rom_file_id", "rom_file_id"), ("play_sessions", "ix_play_sessions_rom_id", "rom_id"), ("play_sessions", "ix_play_sessions_device_id", "device_id"), - ("play_sessions", "ix_play_sessions_sync_session_id", "sync_session_id"), ("saves", "ix_saves_user_id", "user_id"), ("states", "ix_states_user_id", "user_id"), ("screenshots", "ix_screenshots_user_id", "user_id"), diff --git a/backend/utils/openapi.py b/backend/utils/openapi.py new file mode 100644 index 000000000..fde6accc6 --- /dev/null +++ b/backend/utils/openapi.py @@ -0,0 +1,29 @@ +from collections.abc import Sequence +from typing import Any + +from fastapi import FastAPI +from pydantic import BaseModel +from pydantic.json_schema import models_json_schema + + +def publish_socket_payloads(app: FastAPI, models: Sequence[type[BaseModel]]) -> None: + """Add Socket.IO payload models to the app's OpenAPI components. + + No route references them, so FastAPI would leave them out, and the + frontend's generated types would lack the shapes its socket handlers read. + """ + build_schema = app.openapi + + def openapi() -> dict[str, Any]: + if app.openapi_schema is None: + schema = build_schema() + _, definitions = models_json_schema( + [(model, "serialization") for model in models], + ref_template="#/components/schemas/{model}", + ) + components = schema.setdefault("components", {}).setdefault("schemas", {}) + components.update(definitions.get("$defs", {})) + return schema + return app.openapi_schema + + app.openapi = openapi # type: ignore[method-assign] diff --git a/docker/init_scripts/init b/docker/init_scripts/init index 19356f76e..44435aa75 100755 --- a/docker/init_scripts/init +++ b/docker/init_scripts/init @@ -272,6 +272,12 @@ start_bin_rq_scan_worker() { start_rq_worker rq_scan_worker scans } +# Streaming teardowns get a worker of their own, see STREAMING_QUEUE_NAME. +start_bin_rq_streaming_worker() { + info_log "Starting RQ streaming worker" + start_rq_worker rq_streaming_worker streaming +} + # Set PYTHONPATH so RQ can find the tasks module. # Use a worker class that drops the noisy per-sweep "cleaning registries for # queue" log line. The maintenance interval keeps its default (~10 min) so @@ -356,6 +362,7 @@ shutdown() { # shutdown in reverse order stop_process_pid rq_worker stop_process_pid rq_scan_worker + stop_process_pid rq_streaming_worker stop_process_pid rq_cron stop_process_pid sync_watcher stop_process_pid watcher @@ -418,6 +425,8 @@ while ! ((exited)); do watchdog_process_pid rq_scan_worker + watchdog_process_pid rq_streaming_worker + # only start the watcher if enabled if [[ ${ENABLE_RESCAN_ON_FILESYSTEM_CHANGE} == "true" ]]; then watchdog_process_pid watcher diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index cb8b358d5..d872c9718 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -311,7 +311,8 @@ backend/ │ │ ├── update_switch_titledb.py # Refresh Switch TitleDB │ │ ├── update_launchbox_metadata.py # Refresh LaunchBox data │ │ ├── convert_images_to_webp.py # Artwork WebP conversion -│ │ └── cleanup_netplay.py # Prune stale netplay rooms +│ │ ├── cleanup_netplay.py # Prune stale netplay rooms +│ │ └── reap_streaming_sessions.py # Stop abandoned streaming sessions │ └── manual/ # On-demand tasks │ ├── cleanup_missing_roms.py # Drop DB entries for missing files │ ├── cleanup_orphaned_resources.py # Remove unreferenced artwork @@ -819,7 +820,7 @@ Migrations support batch mode for SQLite and DB-specific SQL for MariaDB/MySQL/P **Base URL:** `/api` **Documentation:** Swagger UI at `/api/docs`, ReDoc at `/api/redoc` -**Pagination:** `fastapi-pagination` with `LimitOffsetParams` (`limit`, `offset`, `total`) +**Pagination:** `PageParams` (`limit`, `offset`) via the `PAGE_QUERY` dependency, returning a `LimitOffsetPage` (`items`, `total`, `limit`, `offset`); both live in `endpoints/responses/base.py`. Routes with a smaller page cap subclass `PageParams` (`MusicPageParams`, `AuditPageParams`) ### 6.1 Authentication (`/api`) @@ -1096,19 +1097,29 @@ curl -X POST "$ROMM/api/notifications" -H "Authorization: Bearer $TOKEN" \ #### Notification channels (`/api/notification-channels`) -Each user forwards their own notifications to webhooks and email addresses. A channel filters by minimum level and by topic (`scans`, `tasks`, `streaming`, `account`, `custom`); every stored notification that passes goes out in its own RQ job, retried at 30 s, 2 min and 10 min. A channel that fails 10 deliveries in a row turns itself off and tells its owner. +Each user forwards their own notifications to other services. A channel is one of three types: -| Method | Path | Scope | Description | -| ------ | ------------------- | -------- | ------------------------------------------------------ | -| GET | `/` | ME_READ | Caller's channels, secrets masked | -| POST | `/` | ME_WRITE | Add a webhook, or an email address that gets a code | -| PATCH | `/{id}` | ME_WRITE | Change it; a blank URL or secret keeps the current one | -| DELETE | `/{id}` | ME_WRITE | Delete it | -| POST | `/{id}/test` | ME_WRITE | Send a sample notification now | -| POST | `/{id}/confirm` | ME_WRITE | Confirm an email address with its code | -| POST | `/{id}/resend-code` | ME_WRITE | Email a new code (once a minute) | +- `apprise`: any of the 100+ services [Apprise](https://github.com/caronc/apprise#supported-notifications) reaches (Discord, Telegram, ntfy, Slack, Gotify…), set up through that service's own fields. **Admins only**, since Apprise opens its own connections, past the SSRF guard. The owner's role is checked again at every delivery, so a demoted admin's channel fails until it turns off. +- `webhook`: RomM's own JSON payload (below), POSTed to an http(s) URL. +- `email`: a plain-text email over the server's SMTP, to an address confirmed with a 6-digit code first. -A webhook's `format` is `json` (RomM's payload below), `discord` (an embed that mentions nobody) or `ntfy` (JSON publishing to the topic's server, with the secret as its access token). Only an admin's webhooks may reach private addresses; everyone else's go through the SSRF guard. A kept secret doesn't follow a channel to another origin or format; it has to be given again. A delivery gets 15 s in all, and only the start of a refusal's body is read. Text for RomM's own kinds is English until outbound messages are translated. Links are absolute only when `ROMM_BASE_URL` is shareable. +A channel filters by minimum level and by topic (`scans`, `tasks`, `streaming`, `account`, `custom`); every stored notification that passes goes out in its own RQ job, retried at 30 s, 2 min and 10 min. A channel that fails 10 deliveries in a row turns itself off and tells its owner. + +| Method | Path | Scope | Description | +| ------ | ------------------------- | -------- | ---------------------------------------------------------------------------------------------- | +| GET | `/` | ME_READ | Caller's channels, secrets masked | +| GET | `/apprise-services` | ME_READ | Every Apprise service and its fields (admins only, else 403) | +| POST | `/apprise-services/parse` | ME_READ | Read a pasted URL (Discord's own, or an Apprise one) into its service and fields (admins only) | +| POST | `/` | ME_WRITE | Add a channel; an email address gets a code | +| PATCH | `/{id}` | ME_WRITE | Change it; an omitted URL or secret stays, an empty secret is dropped | +| DELETE | `/{id}` | ME_WRITE | Delete it | +| POST | `/{id}/test` | ME_WRITE | Send a sample notification now | +| POST | `/{id}/confirm` | ME_WRITE | Confirm an email address with its code | +| POST | `/{id}/resend-code` | ME_WRITE | Email a new code (once a minute) | + +The Apprise catalog comes from Apprise's own plugin details: URL tokens become fields, options become advanced fields, and a field is required only when every URL template of its service needs it. A token is a secret when Apprise marks it so or its name is a credential's (`token`, `key`, `webhook`…). A channel stores its service and fields, sealed, and each delivery builds the URL from the template those fields fill. Not offered: schemas that act on the host (`syslog`, `dbus`, `windows`…), FCM (it opens its key file itself), the options Apprise reads from a local file (`template`, `keyfile`, `subfile`, `pgp*`) and the ones RomM sets. Apprise follows no redirects and doesn't retry, its timeouts are capped at 10 s to connect and 15 s to read, a list takes at most 20 items, and `@everyone`, `@here` and `<@…>` ping nobody. A failure's error carries Apprise's warning and the start of the service's reply. Each service links its setup guide on Apprise's wiki. A pasted URL is read back into fields by matching the URL Apprise writes for it against the service's templates. The API returns the fields that aren't secret and names the secrets; on edit, a secret left out stays and an empty one goes, but a kept secret never follows the channel to another destination, as Apprise's `url_identifier` tells them apart. A test gets 60 s, like a queued delivery. + +Only an admin's webhooks may reach private addresses; everyone else's go through the SSRF guard. A kept webhook secret doesn't follow the channel to another origin. A webhook delivery gets 15 s in all, and only the start of a refusal's body is read. Text for RomM's own kinds is English until outbound messages are translated. Links are absolute only when `ROMM_BASE_URL` is shareable. ```json { @@ -1125,7 +1136,7 @@ A webhook's `format` is `json` (RomM's payload below), `discord` (an embed that } ``` -With a secret, the JSON format adds `X-RomM-Signature: sha256=`. Email needs `SMTP_HOST` and `SMTP_FROM` (see `env.template`); the heartbeat's `NOTIFICATIONS.EMAIL_ENABLED` says whether it's set up. Channel configs are sealed with a key derived from `ROMM_AUTH_SECRET_KEY`, so rotating it means entering their URLs again. +With a secret, a webhook adds `X-RomM-Signature: sha256=`. Email needs `SMTP_HOST` and `SMTP_FROM` (see `env.template`); the heartbeat's `NOTIFICATIONS.EMAIL_ENABLED` says whether it's set up. Channel configs are sealed with a key derived from `ROMM_AUTH_SECRET_KEY`, so rotating it means entering their URLs and secrets again. ### 6.17 Audit Events (`/api/audit-events`) @@ -1228,10 +1239,10 @@ tasks.run : Task execution ### Session Management -- Redis keys: `session:{session_id}`, `user_sessions:{username}`, `session_sockets:{session_id}` +- Redis keys: `session:{session_id}`, `user_sessions:{username}`, `session_sockets:{channel}:{session_id}` - Cookie: `romm_session` (httponly, samesite=lax/strict) - `clear_user_sessions(user_id)` on password change clears all sessions -- Removing a session (logout, revoke) disconnects the sockets it opened, which would otherwise keep their `user:{id}` and `admin` rooms +- Removing a session (logout, revoke) disconnects the sockets it opened on both `/ws` and `/netplay`, which would otherwise keep their `user:{id}` and `admin` rooms or their netplay access --- @@ -1515,6 +1526,18 @@ Sent to the user's own `user:{id}` room: ### Netplay (`/netplay`) +Rooms are authorized per ROM. A socket is identified once, at `connect`, from its +session cookie, and is closed when that login session is revoked. The identity is +reloaded on every gated event so a disabled account loses access without waiting +for a reconnect. `open-room` requires a logged-in user with `roms.read` who can +see the ROM being played. `join-room` into a room with a password requires that +password (sent as `password` beside `extra`), which is the guest invite path; a +room without one requires the same access as `open-room`. `GET /api/netplay/list` +requires `roms.read` and 404s for a ROM the caller cannot see, through the same +guard the other ROM endpoints use. WebRTC +signals relay only between peers of the same room, and leaving the room ends that +relay. + **Events:** | Event | Direction | Description | @@ -1542,6 +1565,7 @@ Redis-backed for horizontal scaling across multiple server instances. | `default_queue` | Standard background work | | `low_prio_queue` | Cleanups, conversions, metadata refreshes | | `scan_queue` | Library scans, consumed by a worker of its own | +| `streaming_queue` | Session reaper and exit save pulls, own worker | ### Scheduled Tasks @@ -1566,6 +1590,7 @@ Toggled via environment variables: | `sync_retroachievements_progress` | `ENABLE_SCHEDULED_RETROACHIEVEMENTS_PROGRESS_SYNC` | `0 4 * * *` | Sync RA user progress | | `cleanup_orphaned_resources` | `ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES` | `0 5 * * *` | Remove unused artwork | | `cleanup_netplay` | Always enabled | Periodic | Clean stale rooms | +| `reap_streaming_sessions` | `streaming.enabled` in config, read at startup | `* * * * *` | Stop abandoned streams | | `cleanup_audit_log` | `AUDIT_LOG_RETENTION_DAYS` above 0 (default 90) | `30 4 * * *` | Prune old audit events | ### Manual Tasks @@ -1675,7 +1700,7 @@ Falls back to `FakeRedis` in test mode. | --------------------------------- | --------------- | ----------------------------------- | | `session:{id}` | 14 days | Session JSON | | `user_sessions:{username}` | 14 days | Set of session IDs | -| `session_sockets:{id}` | 14 days | Socket IDs a session opened | +| `session_sockets:{channel}:{id}` | 14 days | Socket IDs a session opened | | `notification-channel:{id}:code` | 30 min | Hash of an email confirmation code | | `notification-channel-cooldown:*` | 1 min | A user's and an address's last code | | `reset-email:{user_id}` | 1 min | A user's last emailed reset link | diff --git a/entrypoint.sh b/entrypoint.sh index 728c5d286..1219bae47 100644 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -116,6 +116,10 @@ start_rq_worker rq_worker high default low echo "Starting RQ scan worker..." start_rq_worker rq_scan_worker scans +# Streaming teardowns get a worker of their own, see STREAMING_QUEUE_NAME. +echo "Starting RQ streaming worker..." +start_rq_worker rq_streaming_worker streaming + echo "Starting watcher..." watchfiles \ --target-type command \ diff --git a/env.template b/env.template index bece5157d..dda2a9535 100644 --- a/env.template +++ b/env.template @@ -36,7 +36,7 @@ DISABLE_CSRF_PROTECTION=false # Disable CSRF protection (not recommended) DISABLE_USERPASS_LOGIN=false # Disable username/password login when using OIDC DISABLE_SETUP_WIZARD=false # Skip the first-boot setup wizard DISABLE_LOGS_VIEWER=false # Disable the backend logs viewer -ROMM_CORS_ALLOWED_ORIGINS= # Comma-separated list of allowed CORS origins (empty allows all) +ROMM_CORS_ALLOWED_ORIGINS= # Comma-separated list of allowed CORS origins (empty allows none; a wildcard allows any origin but never credentials) ROMM_SESSION_SECURE_COOKIE=false # Mark session and CSRF cookies Secure (enable when served over HTTPS) # Email, for notification channels and password reset links (off unless SMTP_HOST and SMTP_FROM are set) @@ -174,6 +174,7 @@ SENTRY_DSN= # DSN for Sentry error tracking DEV_MODE=false # Enable development mode (debugging, hot-reloading) DEV_HOST=127.0.0.1 # Host for the development server DEV_PORT=5000 # Port for the development server +DEV_PROXY_TARGET= # Optional RomM origin (e.g. https://romm.example.com) for vite proxy DEV_HTTPS=false # Enable HTTPS in the development server DEV_SQL_ECHO=false # Log all SQL queries in development mode POSTGRES_DB=authentik # Postgres database name for the Authentik dev stack diff --git a/frontend/.storybook/preview.ts b/frontend/.storybook/preview.ts index cdf1d95dd..fd0dc1543 100644 --- a/frontend/.storybook/preview.ts +++ b/frontend/.storybook/preview.ts @@ -15,6 +15,12 @@ import { ChromeLabelsKey } from "../src/v2/lib/a11y/chromeLabels"; import "../src/v2/styles/global.css"; import { createChromeLabels } from "../src/v2/utils/chromeLabels"; import { ROMM_STORYBOOK_VIEWPORTS } from "./rommViewports"; +import { + INPUT_DEFAULT, + INPUT_GLOBAL, + INPUT_TOOLBAR, + withInputModality, +} from "./withInputModality"; // Mirror AppLayout/AuthLayout so html[data-bp] CSS matches useBreakpoint() in the iframe. installBreakpointAttribute(); @@ -62,8 +68,12 @@ setup((app) => { }); const preview: Preview = { + globalTypes: { + [INPUT_GLOBAL]: INPUT_TOOLBAR, + }, initialGlobals: { viewport: { value: "rommDesktopMd" }, + [INPUT_GLOBAL]: INPUT_DEFAULT, }, parameters: { layout: "centered", @@ -102,6 +112,7 @@ const preview: Preview = { }, }, decorators: [ + withInputModality, withThemeByClassName({ themes: { dark: "r-v2 r-v2-dark v-theme--dark", diff --git a/frontend/.storybook/withInputModality.ts b/frontend/.storybook/withInputModality.ts new file mode 100644 index 000000000..7434a420a --- /dev/null +++ b/frontend/.storybook/withInputModality.ts @@ -0,0 +1,69 @@ +import type { Decorator, Preview } from "@storybook/vue3-vite"; +import { computed, defineAsyncComponent, defineComponent, watch } from "vue"; +import { + useInputModality, + type InputModality, +} from "../src/v2/composables/useInputModality"; + +export const INPUT_GLOBAL = "input"; + +// "live" tracks real devices like the app shell; every other value pins data-input. +type StoryInputMode = InputModality | "live"; + +export const INPUT_DEFAULT: StoryInputMode = "mouse"; + +export const INPUT_TOOLBAR = { + description: "Input modality (data-input on )", + toolbar: { + title: "Input", + icon: "pointerhand", + dynamicTitle: true, + items: [ + { value: "mouse", title: "Mouse" }, + { value: "touch", title: "Touch" }, + { value: "key", title: "Keyboard" }, + { value: "pad", title: "Gamepad" }, + { value: "live", title: "Live (real devices)" }, + ], + }, +} satisfies NonNullable[string]; + +const { install, pin } = useInputModality(); + +function applyMode(mode: StoryInputMode) { + if (mode !== "live") { + pin(mode); + return; + } + pin(null); + install(); +} + +// Unmounting stops useGamepad's poll loop, so the pad only drives stories that asked for it. +// Lazy so vitest.setup.ts doesn't cache useGamepad ahead of its tests' vue-router mock. +const GamepadLayer = defineAsyncComponent(async () => { + const { useGamepad } = await import("../src/v2/composables/useGamepad"); + return defineComponent({ + setup() { + useGamepad().install(); + return () => null; + }, + }); +}); + +export const withInputModality: Decorator = (story, context) => ({ + components: { story, GamepadLayer }, + setup() { + // The Vue renderer keeps the story mounted on a toolbar change and + // updates the reactive globals in place. + const mode = computed( + () => (context.globals[INPUT_GLOBAL] ?? INPUT_DEFAULT) as StoryInputMode, + ); + watch(mode, applyMode, { immediate: true }); + const padActive = computed( + () => mode.value === "live" || mode.value === "pad", + ); + return { padActive }; + }, + template: '', +}); diff --git a/frontend/CLAUDE.md b/frontend/CLAUDE.md new file mode 100644 index 000000000..b54ef1549 --- /dev/null +++ b/frontend/CLAUDE.md @@ -0,0 +1,25 @@ +# RomM frontend + +## The frontend has two UIs - know which you're in + +- **v1 is frozen.** Everything under `frontend/src/views/`, `src/components/`, `src/console/`, `src/layouts/` is legacy and will be deleted wholesale in a final wave. **Do not refactor v1.** Only touch it for a critical bug, and when a v2 fork exists, mark the v1 export `@deprecated`. +- **v2 is the active rewrite** under `frontend/src/v2/`, gated by `user.ui_settings.uiVersion`. It has its own design system (tokens), primitive library (`R*` components in `src/v2/lib/`), universal input (mouse/touch/keyboard/gamepad), and responsive system. New frontend work goes in v2. + +v2 has a detailed constitution, split across the `frontend-v2-*` skills in `.claude/skills/`. **Read the relevant skill before editing v2 code.** + +## Commands (`cd frontend`) + +```bash +npm install # install (Node 24) +npm run dev # dev server :3000 +npm run typecheck # vue-tsc +npm run typecheck:scripts # tsc on the Node/Vite tooling in scripts/ +npm run test # vitest (+ Storybook play() tests) +npm run test:e2e # playwright (needs a running app + seeded e2e users) +npm run build # production build +npm run generate # regenerate types from backend OpenAPI (backend must be running) +npm run build:tokens # regenerate v2 tokens.css (auto on predev/prebuild) +npm run storybook # component library on :6006 +python3 src/locales/check_i18n_locales.py # i18n parity check +python3 src/locales/check_i18n_sorted.py # locale keys sorted (--fix to sort) +``` diff --git a/frontend/scripts/platformIconManifest.ts b/frontend/scripts/platformIconManifest.ts new file mode 100644 index 000000000..c2324e471 --- /dev/null +++ b/frontend/scripts/platformIconManifest.ts @@ -0,0 +1,54 @@ +// Exposes the icons under assets/platforms as `virtual:platform-icons`, so +// the app can skip requests for icons that were never shipped. +import { readdirSync } from "node:fs"; +import { dirname, extname } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { Plugin } from "vite"; + +const VIRTUAL_ID = "virtual:platform-icons"; +const RESOLVED_ID = `\0${VIRTUAL_ID}`; +const ICON_FILE = /\.(svg|ico)$/i; + +/** Lowercase slug to shipped filename; `.svg` wins over `.ico` when both ship. */ +export function listPlatformIcons(dir: string): Map { + const icons = new Map(); + const files = readdirSync(dir, { withFileTypes: true }) + .filter((entry) => entry.isFile() && ICON_FILE.test(entry.name)) + .map((entry) => entry.name) + .sort(); + for (const file of files) { + const ext = extname(file); + const slug = file.slice(0, -ext.length).toLowerCase(); + if (ext.toLowerCase() === ".svg" || !icons.has(slug)) icons.set(slug, file); + } + return icons; +} + +export function platformIconManifest(): Plugin { + const iconDir = fileURLToPath( + new URL("../assets/platforms", import.meta.url), + ); + return { + name: "romm:platform-icon-manifest", + resolveId(id) { + return id === VIRTUAL_ID ? RESOLVED_ID : undefined; + }, + load(id) { + if (id !== RESOLVED_ID) return undefined; + const entries = [...listPlatformIcons(iconDir)]; + return `export default new Map(${JSON.stringify(entries)});`; + }, + // An icon added or removed while the dev server runs would otherwise + // stay invisible until a restart. + configureServer(server) { + const refresh = (file: string) => { + if (dirname(file) !== iconDir || !ICON_FILE.test(file)) return; + const mod = server.moduleGraph.getModuleById(RESOLVED_ID); + if (mod) server.moduleGraph.invalidateModule(mod); + server.ws.send({ type: "full-reload" }); + }; + server.watcher.on("add", refresh); + server.watcher.on("unlink", refresh); + }, + }; +} diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 032da6e64..f1bb3aab5 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -10,6 +10,11 @@ export type { AdminContainerSchema } from './models/AdminContainerSchema'; export type { AdminContainersResponse } from './models/AdminContainersResponse'; export type { AdminSessionSchema } from './models/AdminSessionSchema'; export type { AdminSessionsResponse } from './models/AdminSessionsResponse'; +export type { AppriseChannelCreatePayload } from './models/AppriseChannelCreatePayload'; +export type { AppriseFieldSchema } from './models/AppriseFieldSchema'; +export type { AppriseServiceSchema } from './models/AppriseServiceSchema'; +export type { AppriseUrlFieldsSchema } from './models/AppriseUrlFieldsSchema'; +export type { AppriseUrlPayload } from './models/AppriseUrlPayload'; export type { AuditAction } from './models/AuditAction'; export type { AuditActorKind } from './models/AuditActorKind'; export type { AuditCategory } from './models/AuditCategory'; @@ -72,6 +77,7 @@ export type { ClientTokenSchema } from './models/ClientTokenSchema'; export type { CollectionRomsPayload } from './models/CollectionRomsPayload'; export type { CollectionSchema } from './models/CollectionSchema'; export type { ConfigResponse } from './models/ConfigResponse'; +export type { ContainerBusyDetail } from './models/ContainerBusyDetail'; export type { ContainerSessionSchema } from './models/ContainerSessionSchema'; export type { ConversionStats } from './models/ConversionStats'; export type { ConversionTaskMeta } from './models/ConversionTaskMeta'; @@ -125,13 +131,17 @@ export type { IGDBAgeRating } from './models/IGDBAgeRating'; export type { IGDBMetadataMultiplayerMode } from './models/IGDBMetadataMultiplayerMode'; export type { IGDBMetadataPlatform } from './models/IGDBMetadataPlatform'; export type { IGDBRelatedGame } from './models/IGDBRelatedGame'; +export type { ImportRefusalSchema } from './models/ImportRefusalSchema'; export type { InviteLinkSchema } from './models/InviteLinkSchema'; export type { JobStatus } from './models/JobStatus'; export type { JoinableSessionSchema } from './models/JoinableSessionSchema'; export type { JoinableSessionsResponse } from './models/JoinableSessionsResponse'; export type { JoinedSessionSchema } from './models/JoinedSessionSchema'; export type { LaunchboxImage } from './models/LaunchboxImage'; +export type { LaunchFailedPayload } from './models/LaunchFailedPayload'; export type { LaunchingSessionSchema } from './models/LaunchingSessionSchema'; +export type { LaunchPhasePayload } from './models/LaunchPhasePayload'; +export type { LaunchReadyPayload } from './models/LaunchReadyPayload'; export type { LoadStateRequest } from './models/LoadStateRequest'; export type { LoadStateResponse } from './models/LoadStateResponse'; export type { LogEntrySchema } from './models/LogEntrySchema'; @@ -300,7 +310,6 @@ export type { VolumeResponse } from './models/VolumeResponse'; export type { WatcherTaskMeta } from './models/WatcherTaskMeta'; export type { WatcherTaskStatusResponse } from './models/WatcherTaskStatusResponse'; export type { WebhookChannelCreatePayload } from './models/WebhookChannelCreatePayload'; -export type { WebhookFormat } from './models/WebhookFormat'; export type { WebrcadeFeedCategorySchema } from './models/WebrcadeFeedCategorySchema'; export type { WebrcadeFeedItemPropsSchema } from './models/WebrcadeFeedItemPropsSchema'; export type { WebrcadeFeedItemSchema } from './models/WebrcadeFeedItemSchema'; diff --git a/frontend/src/__generated__/models/AdminContainerSchema.ts b/frontend/src/__generated__/models/AdminContainerSchema.ts index 9d9f072ab..a461f546b 100644 --- a/frontend/src/__generated__/models/AdminContainerSchema.ts +++ b/frontend/src/__generated__/models/AdminContainerSchema.ts @@ -10,6 +10,7 @@ export type AdminContainerSchema = { platforms: Array; supports_desktop: boolean; configured: boolean; + draining?: boolean; session?: (ContainerSessionSchema | null); }; diff --git a/frontend/src/__generated__/models/AppriseChannelCreatePayload.ts b/frontend/src/__generated__/models/AppriseChannelCreatePayload.ts new file mode 100644 index 000000000..753a4b7df --- /dev/null +++ b/frontend/src/__generated__/models/AppriseChannelCreatePayload.ts @@ -0,0 +1,15 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +import type { NotificationChannelMinLevel } from './NotificationChannelMinLevel'; +import type { NotificationTopic } from './NotificationTopic'; +export type AppriseChannelCreatePayload = { + min_level?: NotificationChannelMinLevel; + topics?: (Array | null); + type: string; + name: string; + service: string; + fields: Record)>; +}; + diff --git a/frontend/src/__generated__/models/AppriseFieldSchema.ts b/frontend/src/__generated__/models/AppriseFieldSchema.ts new file mode 100644 index 000000000..6954a3642 --- /dev/null +++ b/frontend/src/__generated__/models/AppriseFieldSchema.ts @@ -0,0 +1,17 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type AppriseFieldSchema = { + key: string; + label: string; + type: 'string' | 'int' | 'float' | 'bool' | 'choice' | 'list'; + required: boolean; + private: boolean; + advanced: boolean; + default: (boolean | number | string | Array | null); + values: (Array | null); + min: (number | null); + max: (number | null); +}; + diff --git a/frontend/src/__generated__/models/AppriseServiceSchema.ts b/frontend/src/__generated__/models/AppriseServiceSchema.ts new file mode 100644 index 000000000..bc19d6a46 --- /dev/null +++ b/frontend/src/__generated__/models/AppriseServiceSchema.ts @@ -0,0 +1,13 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +import type { AppriseFieldSchema } from './AppriseFieldSchema'; +export type AppriseServiceSchema = { + id: string; + name: string; + setup_url: (string | null); + url_fields: Array; + fields: Array; +}; + diff --git a/frontend/src/__generated__/models/AppriseUrlFieldsSchema.ts b/frontend/src/__generated__/models/AppriseUrlFieldsSchema.ts new file mode 100644 index 000000000..f8ef99dc1 --- /dev/null +++ b/frontend/src/__generated__/models/AppriseUrlFieldsSchema.ts @@ -0,0 +1,12 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +/** + * The service a pasted URL is for, and the fields it fills in. + */ +export type AppriseUrlFieldsSchema = { + service: string; + fields: Record)>; +}; + diff --git a/frontend/src/__generated__/models/WebhookFormat.ts b/frontend/src/__generated__/models/AppriseUrlPayload.ts similarity index 70% rename from frontend/src/__generated__/models/WebhookFormat.ts rename to frontend/src/__generated__/models/AppriseUrlPayload.ts index 0786f840d..ec1b736d8 100644 --- a/frontend/src/__generated__/models/WebhookFormat.ts +++ b/frontend/src/__generated__/models/AppriseUrlPayload.ts @@ -2,4 +2,7 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ -export type WebhookFormat = 'json' | 'discord' | 'ntfy'; +export type AppriseUrlPayload = { + url: string; +}; + diff --git a/frontend/src/__generated__/models/ContainerBusyDetail.ts b/frontend/src/__generated__/models/ContainerBusyDetail.ts new file mode 100644 index 000000000..c6406c415 --- /dev/null +++ b/frontend/src/__generated__/models/ContainerBusyDetail.ts @@ -0,0 +1,14 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +/** + * The 409 body when a claim finds its container held. + */ +export type ContainerBusyDetail = { + message: string; + draining: boolean; + rom_name: (string | null); + claimed_at: (string | null); +}; + diff --git a/frontend/src/__generated__/models/ImportRefusalSchema.ts b/frontend/src/__generated__/models/ImportRefusalSchema.ts new file mode 100644 index 000000000..93b7b3942 --- /dev/null +++ b/frontend/src/__generated__/models/ImportRefusalSchema.ts @@ -0,0 +1,16 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +/** + * One `.import/` member the broker's activate declined to place. + */ +export type ImportRefusalSchema = { + reason: string; + member?: (string | null); + expected?: (string | null); + detail?: (string | null); + suggest_emulator?: (string | null); + docs?: (string | null); +}; + diff --git a/frontend/src/__generated__/models/LaunchFailedPayload.ts b/frontend/src/__generated__/models/LaunchFailedPayload.ts new file mode 100644 index 000000000..3eb9d692f --- /dev/null +++ b/frontend/src/__generated__/models/LaunchFailedPayload.ts @@ -0,0 +1,17 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +import type { ImportRefusalSchema } from './ImportRefusalSchema'; +/** + * `streaming:launch-failed`. The claim is already released. + */ +export type LaunchFailedPayload = { + platform: string; + container: string; + claimed_at: string; + detail: string; + refusals?: (Array | null); + refusals_truncated?: number; +}; + diff --git a/frontend/src/__generated__/models/LaunchPhasePayload.ts b/frontend/src/__generated__/models/LaunchPhasePayload.ts new file mode 100644 index 000000000..0419da55e --- /dev/null +++ b/frontend/src/__generated__/models/LaunchPhasePayload.ts @@ -0,0 +1,14 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +/** + * `streaming:launch-phase`, while a broker unpacks a large title. + */ +export type LaunchPhasePayload = { + platform: string; + container: string; + claimed_at: string; + phase?: (string | null); +}; + diff --git a/frontend/src/__generated__/models/LaunchReadyPayload.ts b/frontend/src/__generated__/models/LaunchReadyPayload.ts new file mode 100644 index 000000000..22fda9923 --- /dev/null +++ b/frontend/src/__generated__/models/LaunchReadyPayload.ts @@ -0,0 +1,15 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +/** + * `streaming:launch-ready`, pushed once the game is up. + */ +export type LaunchReadyPayload = { + platform: string; + container: string; + claimed_at: string; + host: string; + resume?: (boolean | null); +}; + diff --git a/frontend/src/__generated__/models/NotificationChannelSchema.ts b/frontend/src/__generated__/models/NotificationChannelSchema.ts index 980419e92..6facdfe68 100644 --- a/frontend/src/__generated__/models/NotificationChannelSchema.ts +++ b/frontend/src/__generated__/models/NotificationChannelSchema.ts @@ -5,7 +5,6 @@ import type { NotificationChannelMinLevel } from './NotificationChannelMinLevel'; import type { NotificationChannelType } from './NotificationChannelType'; import type { NotificationTopic } from './NotificationTopic'; -import type { WebhookFormat } from './WebhookFormat'; export type NotificationChannelSchema = { id: number; type: NotificationChannelType; @@ -14,7 +13,10 @@ export type NotificationChannelSchema = { min_level: NotificationChannelMinLevel; topics: (Array | null); target: string; - format: (WebhookFormat | null); + service: (string | null); + service_name: (string | null); + fields: (Record)> | null); + stored_secrets: (Array | null); has_secret: boolean; confirmed: boolean; last_delivered_at: (string | null); diff --git a/frontend/src/__generated__/models/NotificationChannelType.ts b/frontend/src/__generated__/models/NotificationChannelType.ts index 1a4577f3e..0f7728ac8 100644 --- a/frontend/src/__generated__/models/NotificationChannelType.ts +++ b/frontend/src/__generated__/models/NotificationChannelType.ts @@ -2,4 +2,4 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ -export type NotificationChannelType = 'webhook' | 'email'; +export type NotificationChannelType = 'apprise' | 'webhook' | 'email'; diff --git a/frontend/src/__generated__/models/NotificationChannelUpdatePayload.ts b/frontend/src/__generated__/models/NotificationChannelUpdatePayload.ts index d57169b9f..176138b6b 100644 --- a/frontend/src/__generated__/models/NotificationChannelUpdatePayload.ts +++ b/frontend/src/__generated__/models/NotificationChannelUpdatePayload.ts @@ -4,7 +4,6 @@ /* eslint-disable */ import type { NotificationChannelMinLevel } from './NotificationChannelMinLevel'; import type { NotificationTopic } from './NotificationTopic'; -import type { WebhookFormat } from './WebhookFormat'; /** * The fields to change; a null `topics` forwards every topic, an empty `secret` drops it. */ @@ -14,8 +13,8 @@ export type NotificationChannelUpdatePayload = { min_level?: (NotificationChannelMinLevel | null); topics?: (Array | null); url?: (string | null); - format?: (WebhookFormat | null); secret?: (string | null); address?: (string | null); + fields?: (Record)> | null); }; diff --git a/frontend/src/__generated__/models/PlaySessionSchema.ts b/frontend/src/__generated__/models/PlaySessionSchema.ts index c21143fd2..54d56da7e 100644 --- a/frontend/src/__generated__/models/PlaySessionSchema.ts +++ b/frontend/src/__generated__/models/PlaySessionSchema.ts @@ -7,7 +7,6 @@ export type PlaySessionSchema = { user_id: number; device_id: (string | null); rom_id: (number | null); - sync_session_id: (number | null); save_slot: (string | null); start_time: string; end_time: string; diff --git a/frontend/src/__generated__/models/SaveAndExitResponse.ts b/frontend/src/__generated__/models/SaveAndExitResponse.ts index 30be0b567..e94de32ff 100644 --- a/frontend/src/__generated__/models/SaveAndExitResponse.ts +++ b/frontend/src/__generated__/models/SaveAndExitResponse.ts @@ -3,7 +3,7 @@ /* tslint:disable */ /* eslint-disable */ export type SaveAndExitResponse = { - status: string; + status: 'ok' | 'not_found'; saved: boolean; platform: string; released: boolean; diff --git a/frontend/src/__generated__/models/SessionStatusSchema.ts b/frontend/src/__generated__/models/SessionStatusSchema.ts index 89dbda469..5c78470d7 100644 --- a/frontend/src/__generated__/models/SessionStatusSchema.ts +++ b/frontend/src/__generated__/models/SessionStatusSchema.ts @@ -7,6 +7,7 @@ export type SessionStatusSchema = { status: 'active' | 'ended'; platform: string; extraction_phase?: (string | null); + host?: (string | null); termination?: (SessionTerminationSchema | null); }; diff --git a/frontend/src/__generated__/models/SessionTerminationSchema.ts b/frontend/src/__generated__/models/SessionTerminationSchema.ts index b66bc3b59..8d592dc44 100644 --- a/frontend/src/__generated__/models/SessionTerminationSchema.ts +++ b/frontend/src/__generated__/models/SessionTerminationSchema.ts @@ -15,5 +15,8 @@ export type SessionTerminationSchema = { platform?: (string | null); rom_id?: (number | null); rom_name?: (string | null); + container?: (string | null); + claimed_at?: (string | null); + desktop?: boolean; }; diff --git a/frontend/src/__generated__/models/StreamingConfigSchema.ts b/frontend/src/__generated__/models/StreamingConfigSchema.ts index 30daad1bc..eb9b6bb09 100644 --- a/frontend/src/__generated__/models/StreamingConfigSchema.ts +++ b/frontend/src/__generated__/models/StreamingConfigSchema.ts @@ -6,5 +6,6 @@ import type { StreamingContainerSchema } from './StreamingContainerSchema'; export type StreamingConfigSchema = { enabled: boolean; containers: Array; + emulator_labels: Record; }; diff --git a/frontend/src/__generated__/models/StreamingContainerSchema.ts b/frontend/src/__generated__/models/StreamingContainerSchema.ts index 5d46882d5..b5715953d 100644 --- a/frontend/src/__generated__/models/StreamingContainerSchema.ts +++ b/frontend/src/__generated__/models/StreamingContainerSchema.ts @@ -14,5 +14,7 @@ export type StreamingContainerSchema = { emulator: string; supports_memory_cards: boolean; supports_save_picker: boolean; + supports_live_states: boolean; + import_kinds: Array<'save' | 'state'>; }; diff --git a/frontend/src/__generated__/models/SyncNegotiateResponse.ts b/frontend/src/__generated__/models/SyncNegotiateResponse.ts index 46527894f..659deecd6 100644 --- a/frontend/src/__generated__/models/SyncNegotiateResponse.ts +++ b/frontend/src/__generated__/models/SyncNegotiateResponse.ts @@ -10,5 +10,6 @@ export type SyncNegotiateResponse = { total_download: number; total_conflict: number; total_no_op: number; + total_delete: number; }; diff --git a/frontend/src/__generated__/models/SyncOperationSchema.ts b/frontend/src/__generated__/models/SyncOperationSchema.ts index 867264076..89d9e5122 100644 --- a/frontend/src/__generated__/models/SyncOperationSchema.ts +++ b/frontend/src/__generated__/models/SyncOperationSchema.ts @@ -4,15 +4,15 @@ /* eslint-disable */ export type SyncOperationSchema = { /** - * Operation the client should perform. 'upload' when the client has a save the server lacks (including any null-slot save, which is never paired with server saves), 'download' when the server has a newer or unknown save, 'conflict' when both sides changed independently, and 'no_op' when no action is needed. + * Operation the client should perform. 'upload' when the client has a save the server lacks (including any null-slot save, which is never paired with server saves), 'download' when the server has a newer or unknown save, 'conflict' when both sides changed independently, 'delete' when the slot the client still holds was emptied here, and 'no_op' when no action is needed. */ - action: 'upload' | 'download' | 'conflict' | 'no_op'; + action: 'upload' | 'download' | 'conflict' | 'no_op' | 'delete'; /** * ID of the ROM this operation applies to. */ rom_id: number; /** - * ID of the server save, if one exists (null for uploads). + * ID of the server save, if one exists (null for uploads and deletes). */ save_id?: (number | null); /** @@ -20,7 +20,7 @@ export type SyncOperationSchema = { */ file_name: string; /** - * Slot the operation applies to. Echoes the client slot for uploads; for downloads and conflicts it is the server save's slot. + * Slot the operation applies to. Echoes the client slot for uploads and deletes; for downloads and conflicts it is the server save's slot. */ slot?: (string | null); /** diff --git a/frontend/src/__generated__/models/WebhookChannelCreatePayload.ts b/frontend/src/__generated__/models/WebhookChannelCreatePayload.ts index e94eb8103..d36827a84 100644 --- a/frontend/src/__generated__/models/WebhookChannelCreatePayload.ts +++ b/frontend/src/__generated__/models/WebhookChannelCreatePayload.ts @@ -4,14 +4,12 @@ /* eslint-disable */ import type { NotificationChannelMinLevel } from './NotificationChannelMinLevel'; import type { NotificationTopic } from './NotificationTopic'; -import type { WebhookFormat } from './WebhookFormat'; export type WebhookChannelCreatePayload = { min_level?: NotificationChannelMinLevel; topics?: (Array | null); type: string; name: string; url: string; - format?: WebhookFormat; secret?: (string | null); }; diff --git a/frontend/src/console/views/Play.vue b/frontend/src/console/views/Play.vue index 9e2ab670a..f4ae38417 100644 --- a/frontend/src/console/views/Play.vue +++ b/frontend/src/console/views/Play.vue @@ -32,6 +32,7 @@ import { areThreadsRequiredForEJSCore, getDownloadPath, } from "@/utils"; +import { firmwareExternalFiles } from "@/v2/utils/playerFirmware"; import { buildStateFormData, resolveScreenshot, @@ -471,8 +472,10 @@ async function boot() { window.EJS_biosUrl = bios ? `/api/firmware/${bios.id}/content/${bios.file_name}` : ""; + window.EJS_externalFiles = firmwareExternalFiles(core, firmware); } catch { window.EJS_biosUrl = ""; + window.EJS_externalFiles = {}; } window.EJS_player = "#game"; diff --git a/frontend/src/locales/bg_BG/common.json b/frontend/src/locales/bg_BG/common.json index ff54e483e..7f12d1fbe 100644 --- a/frontend/src/locales/bg_BG/common.json +++ b/frontend/src/locales/bg_BG/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Автогенерирани колекции", "visibility": "Видимост", "warning": "ВНИМАНИЕ:", + "websocket-unreachable-retrying": "Връзката с WebSocket е недостъпна, опит за повторение…", "whats-new": "Виж какво е новото", "zoom-in": "Увеличи", "zoom-out": "Намали" diff --git a/frontend/src/locales/bg_BG/notifications.json b/frontend/src/locales/bg_BG/notifications.json index 90a543cca..92ef8a4ef 100644 --- a/frontend/src/locales/bg_BG/notifications.json +++ b/frontend/src/locales/bg_BG/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Добави канал", "channel-address": "Имейл адрес", "channel-address-hint": "Ще изпратим код, за да потвърдим, че е ваш", + "channel-advanced": "Разширени настройки", "channel-awaiting-code": "Въведете кода от имейла, за да започнете да получавате известия тук", "channel-code": "Код", "channel-code-sent": "Изпратихме код на {address}", @@ -15,10 +16,16 @@ "channel-edit": "Редактирай канала", "channel-email-unavailable": "Имейлът не е настроен на този сървър", "channel-enabled": "Изпращай известия тук", - "channel-format": "Формат", - "channel-format-discord": "Discord", - "channel-format-json": "JSON на RomM", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Име на бота", + "channel-field-host": "Хост", + "channel-field-list-hint": "Натиснете Enter след всеки", + "channel-field-number": "Трябва да е число от {min} до {max}", + "channel-field-path": "Път", + "channel-field-port": "Порт", + "channel-field-schema": "Протокол", + "channel-field-targets": "Получатели", + "channel-field-token": "Токен", + "channel-field-verify": "Проверка на SSL сертификата", "channel-last-error": "Последна грешка: {error}", "channel-last-sent": "Последно изпратено: {when}", "channel-level-error": "Само грешки", @@ -27,14 +34,23 @@ "channel-min-level": "Изпращай", "channel-name": "Име", "channel-new": "Нов канал", + "channel-paste-failed": "Този URL адрес не можа да се прочете", + "channel-paste-filled": "Прочетено от URL адреса: {fields}", + "channel-paste-other-service": "Този URL адрес е за {service}", + "channel-paste-url": "Поставете URL адрес", + "channel-paste-url-hint": "URL адрес на Apprise попълва полетата", "channel-resend": "Изпрати нов код", "channel-resend-failed": "Не можа да се изпрати нов код", "channel-save-failed": "Каналът не можа да бъде запазен", "channel-saved": "Каналът е запазен", - "channel-secret-json": "Таен ключ за подпис (по избор)", + "channel-search-services": "Търсене на услуги", + "channel-secret": "Таен ключ за подпис (по избор)", "channel-secret-keep": "Оставете празно, за да запазите текущия", - "channel-secret-ntfy": "Токен за достъп (по избор)", "channel-secret-remove": "Премахни го", + "channel-service-url": "URL адрес на {service}", + "channel-service-url-hint": "URL адресът, който ви дава {service}, или URL адрес на Apprise", + "channel-services-failed": "Услугите на Apprise не можаха да се заредят", + "channel-setup-guide": "Как да настроите {service}", "channel-test": "Изпрати тест", "channel-test-failed": "Тестът е неуспешен: {error}", "channel-test-ok": "Тестът е изпратен", @@ -42,14 +58,14 @@ "channel-topics-all": "Всички теми", "channel-type": "Тип", "channel-type-email": "Имейл", - "channel-type-webhook": "Уебхук", + "channel-type-webhook": "Уебхук на RomM (JSON)", "channel-update-failed": "Каналът не можа да бъде обновен", "channel-url": "URL", "channel-url-invalid": "Трябва да започва с http:// или https://", "channel-url-keep": "Оставете празно, за да запазите текущия URL", "channels": "Канали", "channels-empty": "Все още няма канали", - "channels-empty-hint": "Препращайте известията си към Discord, ntfy, имейл или всеки уебхук.", + "channels-empty-hint": "Препращайте известията си извън RomM: към уебхук, имейл адрес и други.", "channels-load-failed": "Каналите ви не можаха да бъдат заредени", "dismiss-all": "Затвори всички", "dismiss-all-body": "Всички известия ще бъдат премахнати.", diff --git a/frontend/src/locales/bg_BG/play.json b/frontend/src/locales/bg_BG/play.json index 62391c37c..9b0c68862 100644 --- a/frontend/src/locales/bg_BG/play.json +++ b/frontend/src/locales/bg_BG/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} работи на този контейнер. Първо прекратете тази сесия.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Цял екран", "hide-older-versions": "Скрий по-старите версии", "https-required": "Трябва да се стартира през HTTPS. Свържи се със собственика на сайта.", + "import-refusals-truncated": "Още {count} проблем не е показан | Още {count} проблема не са показани", "join-closed": "Тази сесия вече не е отворена за други играчи.", "join-ended": "Тази сесия приключи.", "jsdos-browser-save-warning": "Запазените данни на js-dos се съхраняват само в този браузър и не се синхронизират с RomM.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "Възникна неочаквана грешка.", + "stream-error-import-refused": "Избраният запис или състояние не можа да бъде използван.", "stream-error-load-rom": "Данните за ROM не можаха да се заредят.", "stream-error-not-configured": "Няма конфигуриран стрийминг контейнер за {platform}.", "stream-error-rom-not-found": "Този ROM не може да бъде намерен. Възможно е да е бил премахнат.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Заглушаване", "stream-occupied-body": "{rom} се играе от {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Предишната сесия все още се затваря. Опитайте отново след малко.", "stream-occupied-fallback": "В момента играе някой друг. Опитайте отново по-късно.", "stream-occupied-title": "Сесията е заета", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/bg_BG/scan.json b/frontend/src/locales/bg_BG/scan.json index ea83ce1cc..52375e599 100644 --- a/frontend/src/locales/bg_BG/scan.json +++ b/frontend/src/locales/bg_BG/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Пълна документация", "info-hashes-desc": "Преизчислява хешовете на всички файлове в избраните платформи.", "info-new-platforms-desc": "Търси само платформи които все още не са в RomM.", - "info-quick-scan-desc": "Сканира игри, които все още не са в библиотеката, и открива файлове, добавени в папките на вече налични игри, на всяко ниво.", + "info-quick-scan-desc": "Сканира игри, които все още не са в библиотеката, открива файлове, добавени в папките на вече налични игри, на всяко ниво, и прочита отново идентификаторите на заглавията на вече наличните игри.", "info-unmatched-games-desc": "Опитва се да разпознае игри които не са разпознати от избраните източници на метаданни.\n\nНапример, ако изберете IGDB и ScreenScraper ще сканирате игри, които не са разпознати от IGDB или ScreenScraper.", "info-update-metadata-desc": "Обновява метаданните на игри разпознати от избраните източници, използвайки външно ID (напр. IGDB ID).\n\nНапример, ако изберете IGDB и ScreenScraper ще се обновят метаданните на разпознатите игри, използвайки igdb_id и/или ssfr_id.", "live-progress": "Прогрес на живо", diff --git a/frontend/src/locales/bg_BG/settings.json b/frontend/src/locales/bg_BG/settings.json index 7f762a8fc..91c7b2ecc 100644 --- a/frontend/src/locales/bg_BG/settings.json +++ b/frontend/src/locales/bg_BG/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Предишната сесия се затваря", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/cs_CZ/common.json b/frontend/src/locales/cs_CZ/common.json index 034abc1e3..cb26ad178 100644 --- a/frontend/src/locales/cs_CZ/common.json +++ b/frontend/src/locales/cs_CZ/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Automaticky vytvořené kolekce", "visibility": "Viditelnost", "warning": "VAROVÁNÍ:", + "websocket-unreachable-retrying": "Připojení WebSocket není k dispozici, opakuji pokus…", "whats-new": "Co je nového", "zoom-in": "Přiblížit", "zoom-out": "Oddálit" diff --git a/frontend/src/locales/cs_CZ/notifications.json b/frontend/src/locales/cs_CZ/notifications.json index 896b3d2e7..18472f6c0 100644 --- a/frontend/src/locales/cs_CZ/notifications.json +++ b/frontend/src/locales/cs_CZ/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Přidat kanál", "channel-address": "E-mailová adresa", "channel-address-hint": "Pošleme kód, abychom ověřili, že je vaše", + "channel-advanced": "Pokročilé možnosti", "channel-awaiting-code": "Zadejte kód z e-mailu a začněte sem dostávat oznámení", "channel-code": "Kód", "channel-code-sent": "Poslali jsme kód na {address}", @@ -15,10 +16,16 @@ "channel-edit": "Upravit kanál", "channel-email-unavailable": "E-mail není na tomto serveru nastaven", "channel-enabled": "Posílat oznámení sem", - "channel-format": "Formát", - "channel-format-discord": "Discord", - "channel-format-json": "JSON RomM", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Jméno bota", + "channel-field-host": "Hostitel", + "channel-field-list-hint": "Po každé položce stiskněte Enter", + "channel-field-number": "Musí být číslo od {min} do {max}", + "channel-field-path": "Cesta", + "channel-field-port": "Port", + "channel-field-schema": "Protokol", + "channel-field-targets": "Cíle", + "channel-field-token": "Token", + "channel-field-verify": "Ověřovat certifikát SSL", "channel-last-error": "Poslední chyba: {error}", "channel-last-sent": "Naposledy odesláno: {when}", "channel-level-error": "Pouze chyby", @@ -27,14 +34,23 @@ "channel-min-level": "Posílat", "channel-name": "Název", "channel-new": "Nový kanál", + "channel-paste-failed": "Tuto URL se nepodařilo přečíst", + "channel-paste-filled": "Načteno z URL: {fields}", + "channel-paste-other-service": "Tato URL patří službě {service}", + "channel-paste-url": "Vložit URL", + "channel-paste-url-hint": "URL Apprise vyplní pole", "channel-resend": "Poslat nový kód", "channel-resend-failed": "Nový kód se nepodařilo odeslat", "channel-save-failed": "Kanál se nepodařilo uložit", "channel-saved": "Kanál uložen", - "channel-secret-json": "Podpisový klíč (volitelné)", + "channel-search-services": "Hledat služby", + "channel-secret": "Podpisový klíč (volitelné)", "channel-secret-keep": "Ponechte prázdné pro zachování stávajícího", - "channel-secret-ntfy": "Přístupový token (volitelné)", "channel-secret-remove": "Odebrat", + "channel-service-url": "URL {service}", + "channel-service-url-hint": "URL, kterou vám dá {service}, nebo URL Apprise", + "channel-services-failed": "Služby Apprise se nepodařilo načíst", + "channel-setup-guide": "Jak nastavit {service}", "channel-test": "Poslat test", "channel-test-failed": "Test selhal: {error}", "channel-test-ok": "Test odeslán", @@ -42,14 +58,14 @@ "channel-topics-all": "Všechna témata", "channel-type": "Typ", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook RomM (JSON)", "channel-update-failed": "Kanál se nepodařilo aktualizovat", "channel-url": "URL", "channel-url-invalid": "Musí začínat http:// nebo https://", "channel-url-keep": "Ponechte prázdné pro zachování stávající URL", "channels": "Kanály", "channels-empty": "Zatím žádné kanály", - "channels-empty-hint": "Přeposílejte oznámení na Discord, ntfy, e-mail nebo jakýkoli webhook.", + "channels-empty-hint": "Přeposílejte oznámení mimo RomM: na webhook, e-mailovou adresu a další.", "channels-load-failed": "Vaše kanály se nepodařilo načíst", "dismiss-all": "Zavřít vše", "dismiss-all-body": "Všechna oznámení budou odstraněna.", diff --git a/frontend/src/locales/cs_CZ/play.json b/frontend/src/locales/cs_CZ/play.json index 9358454ec..030306c3e 100644 --- a/frontend/src/locales/cs_CZ/play.json +++ b/frontend/src/locales/cs_CZ/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "Na tomto kontejneru běží {rom}. Nejprve tuto relaci ukončete.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Celá obrazovka", "hide-older-versions": "Skrýt starší verze", "https-required": "Musí být spuštěno přes HTTPS. Kontaktujte vlastníka webu.", + "import-refusals-truncated": "{count} dalších problémů není zobrazeno | {count} další problém není zobrazen | {count} další problémy nejsou zobrazeny | {count} dalších problémů není zobrazeno", "join-closed": "Tato relace už není otevřená dalším hráčům.", "join-ended": "Tato relace skončila.", "jsdos-browser-save-warning": "Pozice js-dos se ukládají pouze v tomto prohlížeči a nesynchronizují se s RomM.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "Došlo k neočekávané chybě.", + "stream-error-import-refused": "Vybraný uložený soubor nebo stav se nepodařilo použít.", "stream-error-load-rom": "Podrobnosti o ROM se nepodařilo načíst.", "stream-error-not-configured": "Pro platformu {platform} není nakonfigurován žádný streamovací kontejner.", "stream-error-rom-not-found": "Tento ROM nebyl nalezen. Možná byl odstraněn.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Ztlumit", "stream-occupied-body": "{rom} se hraje od {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Předchozí relace se stále ukončuje. Zkuste to znovu za chvíli.", "stream-occupied-fallback": "Právě hraje někdo jiný. Zkuste to později.", "stream-occupied-title": "Relace se používá", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/cs_CZ/scan.json b/frontend/src/locales/cs_CZ/scan.json index 333a97002..2ba5e4d2c 100644 --- a/frontend/src/locales/cs_CZ/scan.json +++ b/frontend/src/locales/cs_CZ/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Úplná dokumentace", "info-hashes-desc": "Přepočítá hashe pro všechny soubory na vybraných platformách.", "info-new-platforms-desc": "Bude hledat pouze platformy, které ještě nejsou v RomM.", - "info-quick-scan-desc": "Skenuje hry, které ještě nejsou v knihovně, a zachytí soubory přidané do složek her, které v ní už jsou, v jakékoli úrovni zanoření.", + "info-quick-scan-desc": "Skenuje hry, které ještě nejsou v knihovně, zachytí soubory přidané do složek her, které v ní už jsou, v jakékoli úrovni zanoření, a znovu načte ID titulů her, které v ní už jsou.", "info-unmatched-games-desc": "Pokusí se spárovat hry, které nejsou spárovány s vybranými zdroji metadat.\n\nNapříklad výběr IGDB a ScreenScraper naskenuje hry, které nejsou spárovány s IGDB nebo ScreenScraper.", "info-update-metadata-desc": "Aktualizuje metadata pro hry, které byly spárovány s vybranými zdroji metadat pomocí externího ID (např. IGDB ID).\n\nNapříklad výběr IGDB a ScreenScraper aktualizuje metadata pro hry spárové s IGDB nebo ScreenScraper a použije igdb_id a/nebo ssfr_id k opakovanému získání metadat od příslušných poskytovatelů.", "live-progress": "Průběh v reálném čase", diff --git a/frontend/src/locales/cs_CZ/settings.json b/frontend/src/locales/cs_CZ/settings.json index 9807989e0..ad756ae4a 100644 --- a/frontend/src/locales/cs_CZ/settings.json +++ b/frontend/src/locales/cs_CZ/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Ukončování předchozí relace", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/de_DE/common.json b/frontend/src/locales/de_DE/common.json index 3063180a2..ab7a198ea 100644 --- a/frontend/src/locales/de_DE/common.json +++ b/frontend/src/locales/de_DE/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Autogenerierte Sammlungen", "visibility": "Sichtbarkeit", "warning": "WARNUNG:", + "websocket-unreachable-retrying": "WebSocket-Verbindung nicht verfügbar, erneuter Versuch…", "whats-new": "Neuigkeiten ansehen", "zoom-in": "Vergrößern", "zoom-out": "Verkleinern" diff --git a/frontend/src/locales/de_DE/notifications.json b/frontend/src/locales/de_DE/notifications.json index c06a066ae..95e200887 100644 --- a/frontend/src/locales/de_DE/notifications.json +++ b/frontend/src/locales/de_DE/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Kanal hinzufügen", "channel-address": "E-Mail-Adresse", "channel-address-hint": "Wir schicken einen Code, um zu bestätigen, dass sie dir gehört", + "channel-advanced": "Erweiterte Optionen", "channel-awaiting-code": "Gib den Code aus der E-Mail ein, um hier Benachrichtigungen zu erhalten", "channel-code": "Code", "channel-code-sent": "Wir haben einen Code an {address} geschickt", @@ -15,10 +16,16 @@ "channel-edit": "Kanal bearbeiten", "channel-email-unavailable": "E-Mail ist auf diesem Server nicht eingerichtet", "channel-enabled": "Benachrichtigungen hierher senden", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "RomM-JSON", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Bot-Name", + "channel-field-host": "Host", + "channel-field-list-hint": "Nach jedem Eintrag Enter drücken", + "channel-field-number": "Muss eine Zahl von {min} bis {max} sein", + "channel-field-path": "Pfad", + "channel-field-port": "Port", + "channel-field-schema": "Protokoll", + "channel-field-targets": "Ziele", + "channel-field-token": "Token", + "channel-field-verify": "SSL-Zertifikat prüfen", "channel-last-error": "Letzter Fehler: {error}", "channel-last-sent": "Zuletzt gesendet: {when}", "channel-level-error": "Nur Fehler", @@ -27,14 +34,23 @@ "channel-min-level": "Senden", "channel-name": "Name", "channel-new": "Neuer Kanal", + "channel-paste-failed": "Diese URL konnte nicht gelesen werden", + "channel-paste-filled": "Aus der URL gelesen: {fields}", + "channel-paste-other-service": "Diese URL gehört zu {service}", + "channel-paste-url": "URL einfügen", + "channel-paste-url-hint": "Eine Apprise-URL füllt die Felder aus", "channel-resend": "Neuen Code senden", "channel-resend-failed": "Es konnte kein neuer Code gesendet werden", "channel-save-failed": "Der Kanal konnte nicht gespeichert werden", "channel-saved": "Kanal gespeichert", - "channel-secret-json": "Signaturgeheimnis (optional)", + "channel-search-services": "Dienste durchsuchen", + "channel-secret": "Signaturgeheimnis (optional)", "channel-secret-keep": "Leer lassen, um das aktuelle zu behalten", - "channel-secret-ntfy": "Zugriffstoken (optional)", "channel-secret-remove": "Entfernen", + "channel-service-url": "{service}-URL", + "channel-service-url-hint": "Die URL, die dir {service} gibt, oder eine Apprise-URL", + "channel-services-failed": "Die Apprise-Dienste konnten nicht geladen werden", + "channel-setup-guide": "So richtest du {service} ein", "channel-test": "Test senden", "channel-test-failed": "Test fehlgeschlagen: {error}", "channel-test-ok": "Test gesendet", @@ -42,14 +58,14 @@ "channel-topics-all": "Alle Themen", "channel-type": "Typ", "channel-type-email": "E-Mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM-Webhook (JSON)", "channel-update-failed": "Der Kanal konnte nicht aktualisiert werden", "channel-url": "URL", "channel-url-invalid": "Muss mit http:// oder https:// beginnen", "channel-url-keep": "Leer lassen, um die aktuelle URL zu behalten", "channels": "Kanäle", "channels-empty": "Noch keine Kanäle", - "channels-empty-hint": "Leite deine Benachrichtigungen an Discord, ntfy, E-Mail oder einen beliebigen Webhook weiter.", + "channels-empty-hint": "Leite deine Benachrichtigungen aus RomM heraus weiter: an einen Webhook, eine E-Mail-Adresse und mehr.", "channels-load-failed": "Deine Kanäle konnten nicht geladen werden", "dismiss-all": "Alle verwerfen", "dismiss-all-body": "Alle Benachrichtigungen werden entfernt.", diff --git a/frontend/src/locales/de_DE/play.json b/frontend/src/locales/de_DE/play.json index e32c2e508..00583673f 100644 --- a/frontend/src/locales/de_DE/play.json +++ b/frontend/src/locales/de_DE/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "Auf diesem Container läuft {rom}. Beende zuerst diese Sitzung.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Vollbild", "hide-older-versions": "Ältere Versionen ausblenden", "https-required": "Muss über HTTPS ausgeführt werden. Kontaktiere den Website-Betreiber.", + "import-refusals-truncated": "{count} weiteres Problem nicht angezeigt | {count} weitere Probleme nicht angezeigt", "join-closed": "Diese Sitzung ist nicht mehr für andere Spieler offen.", "join-ended": "Diese Sitzung ist beendet.", "jsdos-browser-save-warning": "js-dos-Spielstände werden nur in diesem Browser gespeichert und nicht mit RomM synchronisiert.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "Ein unerwarteter Fehler ist aufgetreten.", + "stream-error-import-refused": "Der ausgewählte Spielstand oder Status konnte nicht verwendet werden.", "stream-error-load-rom": "ROM-Details konnten nicht geladen werden.", "stream-error-not-configured": "Für {platform} ist kein Streaming-Container konfiguriert.", "stream-error-rom-not-found": "Dieses ROM konnte nicht gefunden werden. Möglicherweise wurde es entfernt.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Stummschalten", "stream-occupied-body": "{rom} wird seit {time} gespielt.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Die vorherige Sitzung wird noch beendet. Versuche es gleich noch einmal.", "stream-occupied-fallback": "Jemand anderes spielt gerade. Versuchen Sie es später erneut.", "stream-occupied-title": "Sitzung in Benutzung", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/de_DE/scan.json b/frontend/src/locales/de_DE/scan.json index f31320c28..c0a93fc57 100644 --- a/frontend/src/locales/de_DE/scan.json +++ b/frontend/src/locales/de_DE/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Vollständige Dokumentation", "info-hashes-desc": "Berechnet Hashes für alle Dateien in den ausgewählten Plattformen neu.", "info-new-platforms-desc": "Sucht nur nach Plattformen, die noch nicht in RomM sind.", - "info-quick-scan-desc": "Scannt nach Spielen, die noch nicht in der Bibliothek sind, und erfasst Dateien, die in den Ordnern bereits vorhandener Spiele hinzugefügt wurden, in beliebiger Tiefe.", + "info-quick-scan-desc": "Scannt nach Spielen, die noch nicht in der Bibliothek sind, erfasst Dateien, die in den Ordnern bereits vorhandener Spiele hinzugefügt wurden, in beliebiger Tiefe, und liest die Titel-IDs der bereits vorhandenen Spiele neu ein.", "info-unmatched-games-desc": "Versucht, Spiele zuzuordnen, die nicht mit den gewählten Metadatenquellen zugeordnet sind.\n\nZum Beispiel scannt die Auswahl von IGDB und ScreenScraper Spiele, die nicht mit IGDB oder ScreenScraper zugeordnet sind.", "info-update-metadata-desc": "Aktualisiert die Metadaten für Spiele, die mit gewählten Metadatenquellen über die externe ID (z.B. IGDB ID) zugeordnet wurden.\n\nZum Beispiel aktualisiert die Auswahl von IGDB und ScreenScraper die Metadaten für Spiele, die mit IGDB oder ScreenScraper zugeordnet sind, und verwendet igdb_id und/oder ssfr_id, um die Metadaten von den jeweiligen Anbietern neu abzurufen.", "live-progress": "Live-Fortschritt", diff --git a/frontend/src/locales/de_DE/settings.json b/frontend/src/locales/de_DE/settings.json index b9bff3853..b65c049c5 100644 --- a/frontend/src/locales/de_DE/settings.json +++ b/frontend/src/locales/de_DE/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Vorherige Sitzung wird beendet", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/en_GB/common.json b/frontend/src/locales/en_GB/common.json index 37f891346..adf626558 100644 --- a/frontend/src/locales/en_GB/common.json +++ b/frontend/src/locales/en_GB/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Autogenerated collections", "visibility": "Visibility", "warning": "WARNING:", + "websocket-unreachable-retrying": "WebSocket connection unavailable, retrying…", "whats-new": "See what's new", "zoom-in": "Zoom in", "zoom-out": "Zoom out" diff --git a/frontend/src/locales/en_GB/notifications.json b/frontend/src/locales/en_GB/notifications.json index 00200a192..fc7fe6029 100644 --- a/frontend/src/locales/en_GB/notifications.json +++ b/frontend/src/locales/en_GB/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Add channel", "channel-address": "Email address", "channel-address-hint": "We'll email a code to confirm it's yours", + "channel-advanced": "Advanced options", "channel-awaiting-code": "Enter the code we emailed to start getting notifications here", "channel-code": "Code", "channel-code-sent": "We sent a code to {address}", @@ -15,10 +16,16 @@ "channel-edit": "Edit channel", "channel-email-unavailable": "Email isn't set up on this server", "channel-enabled": "Send notifications here", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Bot name", + "channel-field-host": "Host", + "channel-field-list-hint": "Press Enter after each one", + "channel-field-number": "Must be a number from {min} to {max}", + "channel-field-path": "Path", + "channel-field-port": "Port", + "channel-field-schema": "Protocol", + "channel-field-targets": "Targets", + "channel-field-token": "Token", + "channel-field-verify": "Verify the SSL certificate", "channel-last-error": "Last error: {error}", "channel-last-sent": "Last sent {when}", "channel-level-error": "Errors only", @@ -27,14 +34,23 @@ "channel-min-level": "Send", "channel-name": "Name", "channel-new": "New channel", + "channel-paste-failed": "Could not read that URL", + "channel-paste-filled": "Read from the URL: {fields}", + "channel-paste-other-service": "That URL is for {service}", + "channel-paste-url": "Paste a URL", + "channel-paste-url-hint": "An Apprise URL fills in the fields", "channel-resend": "Send a new code", "channel-resend-failed": "Could not send a new code", "channel-save-failed": "Could not save the channel", "channel-saved": "Channel saved", - "channel-secret-json": "Signing secret (optional)", + "channel-search-services": "Search services", + "channel-secret": "Signing secret (optional)", "channel-secret-keep": "Leave empty to keep the current one", - "channel-secret-ntfy": "Access token (optional)", "channel-secret-remove": "Remove it", + "channel-service-url": "{service} URL", + "channel-service-url-hint": "The URL {service} gives you, or an Apprise URL", + "channel-services-failed": "Could not load the Apprise services", + "channel-setup-guide": "How to set up {service}", "channel-test": "Send a test", "channel-test-failed": "Test failed: {error}", "channel-test-ok": "Test sent", @@ -42,14 +58,14 @@ "channel-topics-all": "All topics", "channel-type": "Type", "channel-type-email": "Email", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM webhook (JSON)", "channel-update-failed": "Could not update the channel", "channel-url": "URL", "channel-url-invalid": "Must start with http:// or https://", "channel-url-keep": "Leave empty to keep the current URL", "channels": "Channels", "channels-empty": "No channels yet", - "channels-empty-hint": "Forward your notifications to Discord, ntfy, email or any webhook.", + "channels-empty-hint": "Forward your notifications outside RomM, to a webhook, an email address and more.", "channels-load-failed": "Could not load your channels", "dismiss-all": "Dismiss all", "dismiss-all-body": "Every notification will be removed.", diff --git a/frontend/src/locales/en_GB/play.json b/frontend/src/locales/en_GB/play.json index e754dadc2..c43526bc6 100644 --- a/frontend/src/locales/en_GB/play.json +++ b/frontend/src/locales/en_GB/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} is running on this container. End that session first.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Full screen", "hide-older-versions": "Hide older versions", "https-required": "Must be run over HTTPS. Contact the site owner.", + "import-refusals-truncated": "{count} more issue not shown | {count} more issues not shown", "join-closed": "That session is no longer open to other players.", "join-ended": "That session has ended.", "jsdos-browser-save-warning": "js-dos saves are stored only in this browser and are not synced with RomM.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "An unexpected error occurred.", + "stream-error-import-refused": "The picked save or state could not be used.", "stream-error-load-rom": "Could not load ROM details.", "stream-error-not-configured": "No streaming container is configured for {platform}.", "stream-error-rom-not-found": "This ROM could not be found. It may have been removed.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Mute", "stream-occupied-body": "{rom} has been playing since {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "The previous session is still shutting down. Try again in a moment.", "stream-occupied-fallback": "Someone else is currently playing. Try again later.", "stream-occupied-title": "Session in use", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/en_GB/scan.json b/frontend/src/locales/en_GB/scan.json index 08db8ae2c..5d4443f85 100644 --- a/frontend/src/locales/en_GB/scan.json +++ b/frontend/src/locales/en_GB/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Full documentation", "info-hashes-desc": "Recalculates hashes for all files in the selected platforms.", "info-new-platforms-desc": "This will only look for platforms that are not already in RomM.", - "info-quick-scan-desc": "Scans for games that are not in the library yet, and picks up files added to the folders of games already in it, at any depth.", + "info-quick-scan-desc": "Scans for games that are not in the library yet, picks up files added to the folders of games already in it, at any depth, and re-reads the title IDs of games already in it.", "info-unmatched-games-desc": "Attempts to match games that are not matched with the selected metadata sources.\n\nFor example, selecting IGDB and ScreenScraper will scan games that are not matched with IGDB or ScreenScraper.", "info-update-metadata-desc": "Updates the metadata for games that have been matched with selected metadata sources using the external ID (e.g. IGDB ID).\n\nFor example, selecting IGDB and ScreenScraper will update the metadata for games that are matched with IGDB or ScreenScraper, and will use igdb_id and/or ssfr_id to refetch the metadata from the respective providers.", "live-progress": "Live progress", diff --git a/frontend/src/locales/en_GB/settings.json b/frontend/src/locales/en_GB/settings.json index a8ce4109f..4ab063709 100644 --- a/frontend/src/locales/en_GB/settings.json +++ b/frontend/src/locales/en_GB/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Shutting down the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/en_US/common.json b/frontend/src/locales/en_US/common.json index 37f891346..adf626558 100644 --- a/frontend/src/locales/en_US/common.json +++ b/frontend/src/locales/en_US/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Autogenerated collections", "visibility": "Visibility", "warning": "WARNING:", + "websocket-unreachable-retrying": "WebSocket connection unavailable, retrying…", "whats-new": "See what's new", "zoom-in": "Zoom in", "zoom-out": "Zoom out" diff --git a/frontend/src/locales/en_US/notifications.json b/frontend/src/locales/en_US/notifications.json index 00200a192..fc7fe6029 100644 --- a/frontend/src/locales/en_US/notifications.json +++ b/frontend/src/locales/en_US/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Add channel", "channel-address": "Email address", "channel-address-hint": "We'll email a code to confirm it's yours", + "channel-advanced": "Advanced options", "channel-awaiting-code": "Enter the code we emailed to start getting notifications here", "channel-code": "Code", "channel-code-sent": "We sent a code to {address}", @@ -15,10 +16,16 @@ "channel-edit": "Edit channel", "channel-email-unavailable": "Email isn't set up on this server", "channel-enabled": "Send notifications here", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Bot name", + "channel-field-host": "Host", + "channel-field-list-hint": "Press Enter after each one", + "channel-field-number": "Must be a number from {min} to {max}", + "channel-field-path": "Path", + "channel-field-port": "Port", + "channel-field-schema": "Protocol", + "channel-field-targets": "Targets", + "channel-field-token": "Token", + "channel-field-verify": "Verify the SSL certificate", "channel-last-error": "Last error: {error}", "channel-last-sent": "Last sent {when}", "channel-level-error": "Errors only", @@ -27,14 +34,23 @@ "channel-min-level": "Send", "channel-name": "Name", "channel-new": "New channel", + "channel-paste-failed": "Could not read that URL", + "channel-paste-filled": "Read from the URL: {fields}", + "channel-paste-other-service": "That URL is for {service}", + "channel-paste-url": "Paste a URL", + "channel-paste-url-hint": "An Apprise URL fills in the fields", "channel-resend": "Send a new code", "channel-resend-failed": "Could not send a new code", "channel-save-failed": "Could not save the channel", "channel-saved": "Channel saved", - "channel-secret-json": "Signing secret (optional)", + "channel-search-services": "Search services", + "channel-secret": "Signing secret (optional)", "channel-secret-keep": "Leave empty to keep the current one", - "channel-secret-ntfy": "Access token (optional)", "channel-secret-remove": "Remove it", + "channel-service-url": "{service} URL", + "channel-service-url-hint": "The URL {service} gives you, or an Apprise URL", + "channel-services-failed": "Could not load the Apprise services", + "channel-setup-guide": "How to set up {service}", "channel-test": "Send a test", "channel-test-failed": "Test failed: {error}", "channel-test-ok": "Test sent", @@ -42,14 +58,14 @@ "channel-topics-all": "All topics", "channel-type": "Type", "channel-type-email": "Email", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM webhook (JSON)", "channel-update-failed": "Could not update the channel", "channel-url": "URL", "channel-url-invalid": "Must start with http:// or https://", "channel-url-keep": "Leave empty to keep the current URL", "channels": "Channels", "channels-empty": "No channels yet", - "channels-empty-hint": "Forward your notifications to Discord, ntfy, email or any webhook.", + "channels-empty-hint": "Forward your notifications outside RomM, to a webhook, an email address and more.", "channels-load-failed": "Could not load your channels", "dismiss-all": "Dismiss all", "dismiss-all-body": "Every notification will be removed.", diff --git a/frontend/src/locales/en_US/play.json b/frontend/src/locales/en_US/play.json index 135c92888..8a8db64bf 100644 --- a/frontend/src/locales/en_US/play.json +++ b/frontend/src/locales/en_US/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} is running on this container. End that session first.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Full screen", "hide-older-versions": "Hide older versions", "https-required": "Must be run over HTTPS. Contact the site owner.", + "import-refusals-truncated": "{count} more issue not shown | {count} more issues not shown", "join-closed": "That session is no longer open to other players.", "join-ended": "That session has ended.", "jsdos-browser-save-warning": "js-dos saves are stored only in this browser and are not synced with RomM.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "An unexpected error occurred.", + "stream-error-import-refused": "The picked save or state could not be used.", "stream-error-load-rom": "Could not load ROM details.", "stream-error-not-configured": "No streaming container is configured for {platform}.", "stream-error-rom-not-found": "This ROM could not be found. It may have been removed.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Mute", "stream-occupied-body": "{rom} has been playing since {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "The previous session is still shutting down. Try again in a moment.", "stream-occupied-fallback": "Someone else is currently playing. Try again later.", "stream-occupied-title": "Session in use", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/en_US/scan.json b/frontend/src/locales/en_US/scan.json index 7b33cdf1d..5fd38890e 100644 --- a/frontend/src/locales/en_US/scan.json +++ b/frontend/src/locales/en_US/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Full documentation", "info-hashes-desc": "Recalculates hashes for all files in the selected platforms.", "info-new-platforms-desc": "This will only look for platforms that are not already in RomM.", - "info-quick-scan-desc": "Scans for games that are not in the library yet, and picks up files added to the folders of games already in it, at any depth.", + "info-quick-scan-desc": "Scans for games that are not in the library yet, picks up files added to the folders of games already in it, at any depth, and re-reads the title IDs of games already in it.", "info-unmatched-games-desc": "Attempts to match games that are not matched with the selected metadata sources.\n\nFor example, selecting IGDB and ScreenScraper will scan games that are not matched with IGDB or ScreenScraper.", "info-update-metadata-desc": "Updates the metadata for games that have been matched with selected metadata sources using the external ID (e.g. IGDB ID).\n\nFor example, selecting IGDB and ScreenScraper will update the metadata for games that are matched with IGDB or ScreenScraper, and will use igdb_id and/or ssfr_id to refetch the metadata from the respective providers.", "live-progress": "Live progress", diff --git a/frontend/src/locales/en_US/settings.json b/frontend/src/locales/en_US/settings.json index 68eeb8cba..f339380d3 100644 --- a/frontend/src/locales/en_US/settings.json +++ b/frontend/src/locales/en_US/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Shutting down the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/es_ES/common.json b/frontend/src/locales/es_ES/common.json index 4127deacb..c01d7b044 100644 --- a/frontend/src/locales/es_ES/common.json +++ b/frontend/src/locales/es_ES/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Colecciones autogeneradas", "visibility": "Visibilidad", "warning": "ADVERTENCIA:", + "websocket-unreachable-retrying": "Conexión WebSocket no disponible, reintentando…", "whats-new": "Ver novedades", "zoom-in": "Acercar", "zoom-out": "Alejar" diff --git a/frontend/src/locales/es_ES/notifications.json b/frontend/src/locales/es_ES/notifications.json index 0f902c094..9c9c172ac 100644 --- a/frontend/src/locales/es_ES/notifications.json +++ b/frontend/src/locales/es_ES/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Añadir canal", "channel-address": "Dirección de correo", "channel-address-hint": "Te enviaremos un código para confirmar que es tuya", + "channel-advanced": "Opciones avanzadas", "channel-awaiting-code": "Introduce el código que te hemos enviado para empezar a recibir notificaciones aquí", "channel-code": "Código", "channel-code-sent": "Hemos enviado un código a {address}", @@ -15,10 +16,16 @@ "channel-edit": "Editar canal", "channel-email-unavailable": "El correo no está configurado en este servidor", "channel-enabled": "Enviar notificaciones aquí", - "channel-format": "Formato", - "channel-format-discord": "Discord", - "channel-format-json": "JSON de RomM", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Nombre del bot", + "channel-field-host": "Host", + "channel-field-list-hint": "Pulsa Intro después de cada uno", + "channel-field-number": "Debe ser un número entre {min} y {max}", + "channel-field-path": "Ruta", + "channel-field-port": "Puerto", + "channel-field-schema": "Protocolo", + "channel-field-targets": "Destinos", + "channel-field-token": "Token", + "channel-field-verify": "Verificar el certificado SSL", "channel-last-error": "Último error: {error}", "channel-last-sent": "Último envío: {when}", "channel-level-error": "Solo errores", @@ -27,14 +34,23 @@ "channel-min-level": "Enviar", "channel-name": "Nombre", "channel-new": "Nuevo canal", + "channel-paste-failed": "No se pudo leer esa URL", + "channel-paste-filled": "Leído de la URL: {fields}", + "channel-paste-other-service": "Esa URL es de {service}", + "channel-paste-url": "Pegar una URL", + "channel-paste-url-hint": "Una URL de Apprise rellena los campos", "channel-resend": "Enviar otro código", "channel-resend-failed": "No se pudo enviar otro código", "channel-save-failed": "No se pudo guardar el canal", "channel-saved": "Canal guardado", - "channel-secret-json": "Secreto de firma (opcional)", + "channel-search-services": "Buscar servicios", + "channel-secret": "Secreto de firma (opcional)", "channel-secret-keep": "Déjalo vacío para mantener el actual", - "channel-secret-ntfy": "Token de acceso (opcional)", "channel-secret-remove": "Quitarlo", + "channel-service-url": "URL de {service}", + "channel-service-url-hint": "La URL que te da {service}, o una URL de Apprise", + "channel-services-failed": "No se pudieron cargar los servicios de Apprise", + "channel-setup-guide": "Cómo configurar {service}", "channel-test": "Enviar una prueba", "channel-test-failed": "La prueba ha fallado: {error}", "channel-test-ok": "Prueba enviada", @@ -42,14 +58,14 @@ "channel-topics-all": "Todos los temas", "channel-type": "Tipo", "channel-type-email": "Correo", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook de RomM (JSON)", "channel-update-failed": "No se pudo actualizar el canal", "channel-url": "URL", "channel-url-invalid": "Debe empezar por http:// o https://", "channel-url-keep": "Déjalo vacío para mantener la URL actual", "channels": "Canales", "channels-empty": "Aún no hay canales", - "channels-empty-hint": "Reenvía tus notificaciones a Discord, ntfy, correo o cualquier webhook.", + "channels-empty-hint": "Reenvía tus notificaciones fuera de RomM: a un webhook, a un correo y más.", "channels-load-failed": "No se pudieron cargar tus canales", "dismiss-all": "Descartar todas", "dismiss-all-body": "Se eliminarán todas las notificaciones.", diff --git a/frontend/src/locales/es_ES/play.json b/frontend/src/locales/es_ES/play.json index 86f54d809..3328e28b2 100644 --- a/frontend/src/locales/es_ES/play.json +++ b/frontend/src/locales/es_ES/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} se está ejecutando en este contenedor. Finaliza esa sesión primero.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Pantalla completa", "hide-older-versions": "Ocultar versiones anteriores", "https-required": "Debe ejecutarse mediante HTTPS. Contacta con el propietario del sitio.", + "import-refusals-truncated": "{count} problema más no mostrado | {count} problemas más no mostrados", "join-closed": "Esa sesión ya no está abierta a otros jugadores.", "join-ended": "Esa sesión ha terminado.", "jsdos-browser-save-warning": "Las partidas de js-dos se almacenan solo en este navegador y no se sincronizan con RomM.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "Se produjo un error inesperado.", + "stream-error-import-refused": "No se pudo usar el guardado o estado seleccionado.", "stream-error-load-rom": "No se pudieron cargar los detalles de la ROM.", "stream-error-not-configured": "No hay ningún contenedor de streaming configurado para {platform}.", "stream-error-rom-not-found": "No se pudo encontrar esta ROM. Es posible que haya sido eliminada.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Silenciar", "stream-occupied-body": "{rom} se está jugando desde las {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "La sesión anterior aún se está cerrando. Inténtalo de nuevo en un momento.", "stream-occupied-fallback": "Otra persona está jugando en este momento. Inténtalo de nuevo más tarde.", "stream-occupied-title": "Sesión en uso", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/es_ES/scan.json b/frontend/src/locales/es_ES/scan.json index eb4db2821..985c89ae5 100644 --- a/frontend/src/locales/es_ES/scan.json +++ b/frontend/src/locales/es_ES/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Documentación completa", "info-hashes-desc": "Recalcula los hashes para todos los archivos en las plataformas seleccionadas.", "info-new-platforms-desc": "Solo buscará plataformas que no estén ya en RomM.", - "info-quick-scan-desc": "Escanea juegos que aún no estén en la biblioteca y detecta archivos añadidos a las carpetas de juegos que ya están en ella, a cualquier nivel.", + "info-quick-scan-desc": "Escanea juegos que aún no estén en la biblioteca, detecta archivos añadidos a las carpetas de juegos que ya están en ella, a cualquier nivel, y vuelve a leer los ID de título de los juegos que ya están en ella.", "info-unmatched-games-desc": "Intenta hacer coincidir juegos que no tienen coincidencias con las fuentes de metadatos seleccionadas.\n\nPor ejemplo, seleccionar IGDB y ScreenScraper escaneará juegos que no tienen coincidencias con IGDB o ScreenScraper.", "info-update-metadata-desc": "Actualiza los metadatos para juegos que han sido emparejados con fuentes de metadatos seleccionadas usando el ID externo (ej. IGDB ID).\n\nPor ejemplo, seleccionar IGDB y ScreenScraper actualizará los metadatos para juegos emparejados con IGDB o ScreenScraper, y usará igdb_id y/o ssfr_id para recargar los metadatos de los respectivos proveedores.", "live-progress": "Progreso en vivo", diff --git a/frontend/src/locales/es_ES/settings.json b/frontend/src/locales/es_ES/settings.json index d8f333225..cfd9d2b8b 100644 --- a/frontend/src/locales/es_ES/settings.json +++ b/frontend/src/locales/es_ES/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Cerrando la sesión anterior", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/fr_FR/common.json b/frontend/src/locales/fr_FR/common.json index 9aef03e38..203dfa4b4 100644 --- a/frontend/src/locales/fr_FR/common.json +++ b/frontend/src/locales/fr_FR/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Collections autogénérées", "visibility": "Visibilité", "warning": "ATTENTION :", + "websocket-unreachable-retrying": "Connexion WebSocket indisponible, nouvelle tentative…", "whats-new": "Voir les nouveautés", "zoom-in": "Zoom avant", "zoom-out": "Zoom arrière" diff --git a/frontend/src/locales/fr_FR/notifications.json b/frontend/src/locales/fr_FR/notifications.json index 9347b7748..23a2dff73 100644 --- a/frontend/src/locales/fr_FR/notifications.json +++ b/frontend/src/locales/fr_FR/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Ajouter un canal", "channel-address": "Adresse e-mail", "channel-address-hint": "Nous enverrons un code pour confirmer qu'elle est à vous", + "channel-advanced": "Options avancées", "channel-awaiting-code": "Saisissez le code reçu par e-mail pour commencer à recevoir des notifications ici", "channel-code": "Code", "channel-code-sent": "Nous avons envoyé un code à {address}", @@ -15,10 +16,16 @@ "channel-edit": "Modifier le canal", "channel-email-unavailable": "L'e-mail n'est pas configuré sur ce serveur", "channel-enabled": "Envoyer les notifications ici", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "JSON RomM", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Nom du bot", + "channel-field-host": "Hôte", + "channel-field-list-hint": "Appuyez sur Entrée après chacun", + "channel-field-number": "Doit être un nombre entre {min} et {max}", + "channel-field-path": "Chemin", + "channel-field-port": "Port", + "channel-field-schema": "Protocole", + "channel-field-targets": "Destinataires", + "channel-field-token": "Jeton", + "channel-field-verify": "Vérifier le certificat SSL", "channel-last-error": "Dernière erreur : {error}", "channel-last-sent": "Dernier envoi : {when}", "channel-level-error": "Erreurs uniquement", @@ -27,14 +34,23 @@ "channel-min-level": "Envoyer", "channel-name": "Nom", "channel-new": "Nouveau canal", + "channel-paste-failed": "Impossible de lire cette URL", + "channel-paste-filled": "Lu depuis l'URL : {fields}", + "channel-paste-other-service": "Cette URL est pour {service}", + "channel-paste-url": "Coller une URL", + "channel-paste-url-hint": "Une URL Apprise remplit les champs", "channel-resend": "Envoyer un nouveau code", "channel-resend-failed": "Impossible d'envoyer un nouveau code", "channel-save-failed": "Impossible d'enregistrer le canal", "channel-saved": "Canal enregistré", - "channel-secret-json": "Secret de signature (facultatif)", + "channel-search-services": "Rechercher un service", + "channel-secret": "Secret de signature (facultatif)", "channel-secret-keep": "Laissez vide pour conserver l'actuel", - "channel-secret-ntfy": "Jeton d'accès (facultatif)", "channel-secret-remove": "Le supprimer", + "channel-service-url": "URL {service}", + "channel-service-url-hint": "L'URL que vous donne {service}, ou une URL Apprise", + "channel-services-failed": "Impossible de charger les services Apprise", + "channel-setup-guide": "Comment configurer {service}", "channel-test": "Envoyer un test", "channel-test-failed": "Échec du test : {error}", "channel-test-ok": "Test envoyé", @@ -42,14 +58,14 @@ "channel-topics-all": "Tous les sujets", "channel-type": "Type", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook RomM (JSON)", "channel-update-failed": "Impossible de mettre à jour le canal", "channel-url": "URL", "channel-url-invalid": "Doit commencer par http:// ou https://", "channel-url-keep": "Laissez vide pour conserver l'URL actuelle", "channels": "Canaux", "channels-empty": "Aucun canal pour l'instant", - "channels-empty-hint": "Transférez vos notifications vers Discord, ntfy, l'e-mail ou n'importe quel webhook.", + "channels-empty-hint": "Transférez vos notifications hors de RomM : vers un webhook, une adresse e-mail et plus encore.", "channels-load-failed": "Impossible de charger vos canaux", "dismiss-all": "Tout ignorer", "dismiss-all-body": "Toutes les notifications seront supprimées.", diff --git a/frontend/src/locales/fr_FR/play.json b/frontend/src/locales/fr_FR/play.json index 284be0cfc..56e705eb2 100644 --- a/frontend/src/locales/fr_FR/play.json +++ b/frontend/src/locales/fr_FR/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} est en cours d'exécution sur ce conteneur. Terminez d'abord cette session.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Plein écran", "hide-older-versions": "Masquer les versions antérieures", "https-required": "Doit être exécuté en HTTPS. Contactez l'administrateur du site.", + "import-refusals-truncated": "{count} problème supplémentaire non affiché | {count} problèmes supplémentaires non affichés", "join-closed": "Cette session n'est plus ouverte aux autres joueurs.", "join-ended": "Cette session est terminée.", "jsdos-browser-save-warning": "Les sauvegardes js-dos sont stockées uniquement dans ce navigateur et ne sont pas synchronisées avec RomM.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "Une erreur inattendue s'est produite.", + "stream-error-import-refused": "La sauvegarde ou l'état sélectionné n'a pas pu être utilisé.", "stream-error-load-rom": "Impossible de charger les détails de la ROM.", "stream-error-not-configured": "Aucun conteneur de streaming n'est configuré pour {platform}.", "stream-error-rom-not-found": "Cette ROM est introuvable. Elle a peut-être été supprimée.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Couper le son", "stream-occupied-body": "{rom} est en cours de partie depuis {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "La session précédente est encore en cours de fermeture. Réessayez dans un instant.", "stream-occupied-fallback": "Quelqu'un d'autre joue actuellement. Réessayez plus tard.", "stream-occupied-title": "Session en cours d'utilisation", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/fr_FR/scan.json b/frontend/src/locales/fr_FR/scan.json index 1b15fada7..0914561a4 100644 --- a/frontend/src/locales/fr_FR/scan.json +++ b/frontend/src/locales/fr_FR/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Documentation complète", "info-hashes-desc": "Recalcule les hachages pour tous les fichiers dans les plateformes sélectionnées.", "info-new-platforms-desc": "Ne cherchera que les plateformes qui ne sont pas déjà dans RomM.", - "info-quick-scan-desc": "Scanne les jeux qui ne sont pas encore dans la bibliothèque et récupère les fichiers ajoutés dans les dossiers des jeux qui y sont déjà, à n'importe quel niveau.", + "info-quick-scan-desc": "Scanne les jeux qui ne sont pas encore dans la bibliothèque, récupère les fichiers ajoutés dans les dossiers des jeux qui y sont déjà, à n'importe quel niveau, et relit les identifiants de titre des jeux qui y sont déjà.", "info-unmatched-games-desc": "Tente d'associer les jeux qui ne sont pas associés avec les sources de métadonnées sélectionnées.\n\nPar exemple, sélectionner IGDB et ScreenScraper scannera les jeux qui ne sont pas associés avec IGDB ou ScreenScraper.", "info-update-metadata-desc": "Met à jour les métadonnées pour les jeux qui ont été associés avec les sources de métadonnées sélectionnées en utilisant l'ID externe (ex. IGDB ID).\n\nPar exemple, sélectionner IGDB et ScreenScraper mettra à jour les métadonnées pour les jeux associés avec IGDB ou ScreenScraper, et utilisera igdb_id et/ou ssfr_id pour récupérer les métadonnées des fournisseurs respectifs.", "live-progress": "Progression en direct", diff --git a/frontend/src/locales/fr_FR/settings.json b/frontend/src/locales/fr_FR/settings.json index b221cbb26..9067c4e2e 100644 --- a/frontend/src/locales/fr_FR/settings.json +++ b/frontend/src/locales/fr_FR/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Fermeture de la session précédente", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/hu_HU/common.json b/frontend/src/locales/hu_HU/common.json index bef7a2886..f3db5d05d 100644 --- a/frontend/src/locales/hu_HU/common.json +++ b/frontend/src/locales/hu_HU/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Automatikusan generált gyűjtemények", "visibility": "Láthatóság", "warning": "FIGYELMEZTETÉS:", + "websocket-unreachable-retrying": "A WebSocket kapcsolat nem érhető el, újrapróbálkozás…", "whats-new": "Mi újság", "zoom-in": "Nagyítás", "zoom-out": "Kicsinyítés" diff --git a/frontend/src/locales/hu_HU/notifications.json b/frontend/src/locales/hu_HU/notifications.json index a70e285f2..b5d45fa7b 100644 --- a/frontend/src/locales/hu_HU/notifications.json +++ b/frontend/src/locales/hu_HU/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Csatorna hozzáadása", "channel-address": "E-mail-cím", "channel-address-hint": "Küldünk egy kódot, hogy megerősítsd, a tiéd", + "channel-advanced": "Speciális beállítások", "channel-awaiting-code": "Add meg az e-mailben kapott kódot, hogy itt is értesítéseket kapj", "channel-code": "Kód", "channel-code-sent": "Kódot küldtünk ide: {address}", @@ -15,10 +16,16 @@ "channel-edit": "Csatorna szerkesztése", "channel-email-unavailable": "Az e-mail nincs beállítva ezen a szerveren", "channel-enabled": "Értesítések küldése ide", - "channel-format": "Formátum", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Bot neve", + "channel-field-host": "Kiszolgáló", + "channel-field-list-hint": "Mindegyik után nyomj Entert", + "channel-field-number": "{min} és {max} közötti számnak kell lennie", + "channel-field-path": "Útvonal", + "channel-field-port": "Port", + "channel-field-schema": "Protokoll", + "channel-field-targets": "Címzettek", + "channel-field-token": "Token", + "channel-field-verify": "SSL-tanúsítvány ellenőrzése", "channel-last-error": "Utolsó hiba: {error}", "channel-last-sent": "Utoljára elküldve: {when}", "channel-level-error": "Csak hibák", @@ -27,14 +34,23 @@ "channel-min-level": "Küldés", "channel-name": "Név", "channel-new": "Új csatorna", + "channel-paste-failed": "Ezt az URL-t nem sikerült beolvasni", + "channel-paste-filled": "Az URL-ből beolvasva: {fields}", + "channel-paste-other-service": "Ez az URL a(z) {service} szolgáltatáshoz tartozik", + "channel-paste-url": "URL beillesztése", + "channel-paste-url-hint": "Egy Apprise-URL kitölti a mezőket", "channel-resend": "Új kód küldése", "channel-resend-failed": "Nem sikerült új kódot küldeni", "channel-save-failed": "Nem sikerült menteni a csatornát", "channel-saved": "Csatorna mentve", - "channel-secret-json": "Aláírási titok (nem kötelező)", + "channel-search-services": "Szolgáltatások keresése", + "channel-secret": "Aláírási titok (nem kötelező)", "channel-secret-keep": "Hagyd üresen a jelenlegi megtartásához", - "channel-secret-ntfy": "Hozzáférési token (nem kötelező)", "channel-secret-remove": "Eltávolítás", + "channel-service-url": "{service} URL", + "channel-service-url-hint": "A(z) {service} által adott URL vagy egy Apprise-URL", + "channel-services-failed": "Az Apprise-szolgáltatásokat nem sikerült betölteni", + "channel-setup-guide": "{service} beállítása", "channel-test": "Teszt küldése", "channel-test-failed": "A teszt sikertelen: {error}", "channel-test-ok": "Teszt elküldve", @@ -42,14 +58,14 @@ "channel-topics-all": "Minden téma", "channel-type": "Típus", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM webhook (JSON)", "channel-update-failed": "Nem sikerült frissíteni a csatornát", "channel-url": "URL", "channel-url-invalid": "http:// vagy https:// kezdetűnek kell lennie", "channel-url-keep": "Hagyd üresen a jelenlegi URL megtartásához", "channels": "Csatornák", "channels-empty": "Még nincsenek csatornák", - "channels-empty-hint": "Továbbítsd az értesítéseidet Discordra, ntfy-ra, e-mailbe vagy bármilyen webhookra.", + "channels-empty-hint": "Továbbítsd az értesítéseidet a RomM-on kívülre: webhookra, e-mail-címre és máshová.", "channels-load-failed": "Nem sikerült betölteni a csatornáidat", "dismiss-all": "Összes elvetése", "dismiss-all-body": "Az összes értesítés törlődik.", diff --git a/frontend/src/locales/hu_HU/play.json b/frontend/src/locales/hu_HU/play.json index d45aef98a..0348765d8 100644 --- a/frontend/src/locales/hu_HU/play.json +++ b/frontend/src/locales/hu_HU/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "Ezen a konténeren fut: {rom}. Előbb fejezd be azt a munkamenetet.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Teljes képernyő", "hide-older-versions": "Régebbi verziók elrejtése", "https-required": "HTTPS-en keresztül kell futtatni. Vedd fel a kapcsolatot az oldal tulajdonosával.", + "import-refusals-truncated": "{count} további probléma nincs megjelenítve | {count} további probléma nincs megjelenítve", "join-closed": "Ez a munkamenet már nem áll nyitva más játékosok előtt.", "join-ended": "Ez a munkamenet véget ért.", "jsdos-browser-save-warning": "A js-dos mentések csak ebben a böngészőben tárolódnak, és nem szinkronizálódnak a RomM-mal.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "Váratlan hiba történt.", + "stream-error-import-refused": "A kiválasztott mentés vagy állapot nem volt használható.", "stream-error-load-rom": "A ROM adatait nem sikerült betölteni.", "stream-error-not-configured": "Nincs streaming konténer konfigurálva a következőhöz: {platform}.", "stream-error-rom-not-found": "Ez a ROM nem található. Lehet, hogy eltávolították.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Némítás", "stream-occupied-body": "A(z) {rom} játékban van {time} óta.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Az előző munkamenet még leáll. Próbáld újra egy pillanat múlva.", "stream-occupied-fallback": "Jelenleg valaki más játszik. Próbálja meg később.", "stream-occupied-title": "A munkamenet használatban van", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/hu_HU/scan.json b/frontend/src/locales/hu_HU/scan.json index d536eb845..e48999c49 100644 --- a/frontend/src/locales/hu_HU/scan.json +++ b/frontend/src/locales/hu_HU/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Teljes dokumentáció", "info-hashes-desc": "Újraszámolja a kiválasztott platformok összes fájljának hash-értékét.", "info-new-platforms-desc": "Ez csak azokat a platformokat fogja keresni, amelyek még nem szerepelnek a RomM-ban.", - "info-quick-scan-desc": "A könyvtárban még nem szereplő játékok keresése, valamint a már meglévő játékok mappáiba bármilyen mélységben felvett fájlok felderítése.", + "info-quick-scan-desc": "A könyvtárban még nem szereplő játékok keresése, a már meglévő játékok mappáiba bármilyen mélységben felvett fájlok felderítése, valamint a már meglévő játékok címazonosítóinak újraolvasása.", "info-unmatched-games-desc": "Megpróbálja egyeztetni azokat a játékokat, amelyek még nincsenek párosítva a kiválasztott metadatforrásokkal.\n\nPéldául, ha az IGDB és a ScreenScraper van kiválasztva, akkor minden olyan játékot átvizsgál, amely nincs egyeztetve sem az IGDB-vel, sem a ScreenScraperrel.", "info-update-metadata-desc": "Frissíti azoknak a játékoknak a metadatáit, amelyek már egyeztetve vannak a kiválasztott metadatforrásokkal, az adott külső azonosító (pl. IGDB ID) alapján.\n\nPéldául, ha az IGDB és a ScreenScraper van kiválasztva, akkor frissíti azoknak a játékoknak a metadatáit, amelyek egyeztetve vannak az IGDB-vel vagy a ScreenScraperrel, és az igdb_id illetve/vagy ssfr_id segítségével újra lekéri az adatokat a megfelelő szolgáltatóktól.", "live-progress": "Élő haladás", diff --git a/frontend/src/locales/hu_HU/settings.json b/frontend/src/locales/hu_HU/settings.json index bd45a1154..98b981f0a 100644 --- a/frontend/src/locales/hu_HU/settings.json +++ b/frontend/src/locales/hu_HU/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Az előző munkamenet leállítása", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/it_IT/common.json b/frontend/src/locales/it_IT/common.json index d1c7270d8..b43ace609 100644 --- a/frontend/src/locales/it_IT/common.json +++ b/frontend/src/locales/it_IT/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Collezioni generate automaticamente", "visibility": "Visibilità", "warning": "AVVISO:", + "websocket-unreachable-retrying": "Connessione WebSocket non disponibile, nuovo tentativo…", "whats-new": "Scopri le novità", "zoom-in": "Aumenta zoom", "zoom-out": "Diminuisci zoom" diff --git a/frontend/src/locales/it_IT/notifications.json b/frontend/src/locales/it_IT/notifications.json index a44f21ccc..67885eb93 100644 --- a/frontend/src/locales/it_IT/notifications.json +++ b/frontend/src/locales/it_IT/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Aggiungi canale", "channel-address": "Indirizzo email", "channel-address-hint": "Ti invieremo un codice per confermare che è tuo", + "channel-advanced": "Opzioni avanzate", "channel-awaiting-code": "Inserisci il codice che ti abbiamo inviato per iniziare a ricevere notifiche qui", "channel-code": "Codice", "channel-code-sent": "Abbiamo inviato un codice a {address}", @@ -15,10 +16,16 @@ "channel-edit": "Modifica canale", "channel-email-unavailable": "L'email non è configurata su questo server", "channel-enabled": "Invia notifiche qui", - "channel-format": "Formato", - "channel-format-discord": "Discord", - "channel-format-json": "JSON di RomM", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Nome del bot", + "channel-field-host": "Host", + "channel-field-list-hint": "Premi Invio dopo ognuno", + "channel-field-number": "Deve essere un numero da {min} a {max}", + "channel-field-path": "Percorso", + "channel-field-port": "Porta", + "channel-field-schema": "Protocollo", + "channel-field-targets": "Destinatari", + "channel-field-token": "Token", + "channel-field-verify": "Verifica il certificato SSL", "channel-last-error": "Ultimo errore: {error}", "channel-last-sent": "Ultimo invio: {when}", "channel-level-error": "Solo errori", @@ -27,14 +34,23 @@ "channel-min-level": "Invia", "channel-name": "Nome", "channel-new": "Nuovo canale", + "channel-paste-failed": "Impossibile leggere questo URL", + "channel-paste-filled": "Letto dall'URL: {fields}", + "channel-paste-other-service": "Questo URL è per {service}", + "channel-paste-url": "Incolla un URL", + "channel-paste-url-hint": "Un URL Apprise compila i campi", "channel-resend": "Invia un nuovo codice", "channel-resend-failed": "Impossibile inviare un nuovo codice", "channel-save-failed": "Impossibile salvare il canale", "channel-saved": "Canale salvato", - "channel-secret-json": "Segreto di firma (facoltativo)", + "channel-search-services": "Cerca servizi", + "channel-secret": "Segreto di firma (facoltativo)", "channel-secret-keep": "Lascia vuoto per mantenere quello attuale", - "channel-secret-ntfy": "Token di accesso (facoltativo)", "channel-secret-remove": "Rimuovilo", + "channel-service-url": "URL di {service}", + "channel-service-url-hint": "L'URL che ti fornisce {service}, o un URL Apprise", + "channel-services-failed": "Impossibile caricare i servizi Apprise", + "channel-setup-guide": "Come configurare {service}", "channel-test": "Invia un test", "channel-test-failed": "Test non riuscito: {error}", "channel-test-ok": "Test inviato", @@ -42,14 +58,14 @@ "channel-topics-all": "Tutti gli argomenti", "channel-type": "Tipo", "channel-type-email": "Email", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook di RomM (JSON)", "channel-update-failed": "Impossibile aggiornare il canale", "channel-url": "URL", "channel-url-invalid": "Deve iniziare con http:// o https://", "channel-url-keep": "Lascia vuoto per mantenere l'URL attuale", "channels": "Canali", "channels-empty": "Ancora nessun canale", - "channels-empty-hint": "Inoltra le tue notifiche a Discord, ntfy, email o qualsiasi webhook.", + "channels-empty-hint": "Inoltra le tue notifiche fuori da RomM: a un webhook, a un indirizzo email e altro.", "channels-load-failed": "Impossibile caricare i tuoi canali", "dismiss-all": "Ignora tutte", "dismiss-all-body": "Tutte le notifiche verranno rimosse.", diff --git a/frontend/src/locales/it_IT/play.json b/frontend/src/locales/it_IT/play.json index 0ed68941d..a5426fb7c 100644 --- a/frontend/src/locales/it_IT/play.json +++ b/frontend/src/locales/it_IT/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} è in esecuzione su questo container. Termina prima quella sessione.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Schermo Intero", "hide-older-versions": "Nascondi le versioni precedenti", "https-required": "Deve essere eseguito su HTTPS. Contatta il proprietario del sito.", + "import-refusals-truncated": "{count} problema in più non mostrato | {count} problemi in più non mostrati", "join-closed": "Quella sessione non è più aperta ad altri giocatori.", "join-ended": "Quella sessione è terminata.", "jsdos-browser-save-warning": "I salvataggi di js-dos vengono archiviati solo in questo browser e non vengono sincronizzati con RomM.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "Si è verificato un errore imprevisto.", + "stream-error-import-refused": "Il salvataggio o lo stato selezionato non è stato utilizzabile.", "stream-error-load-rom": "Impossibile caricare i dettagli della ROM.", "stream-error-not-configured": "Nessun contenitore di streaming configurato per {platform}.", "stream-error-rom-not-found": "Impossibile trovare questa ROM. Potrebbe essere stata rimossa.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Disattiva audio", "stream-occupied-body": "{rom} è in gioco da {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "La sessione precedente è ancora in chiusura. Riprova tra un momento.", "stream-occupied-fallback": "Qualcun altro sta giocando in questo momento. Riprova più tardi.", "stream-occupied-title": "Sessione in uso", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/it_IT/scan.json b/frontend/src/locales/it_IT/scan.json index cc13eb09e..44f8623f0 100644 --- a/frontend/src/locales/it_IT/scan.json +++ b/frontend/src/locales/it_IT/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Documentazione completa", "info-hashes-desc": "Ricalcola gli hash per tutti i file nelle piattaforme selezionate.", "info-new-platforms-desc": "Cercherà solo piattaforme che non sono già in RomM.", - "info-quick-scan-desc": "Scansiona i giochi che non sono ancora nella libreria e rileva i file aggiunti nelle cartelle dei giochi già presenti, a qualsiasi livello.", + "info-quick-scan-desc": "Scansiona i giochi che non sono ancora nella libreria, rileva i file aggiunti nelle cartelle dei giochi già presenti, a qualsiasi livello, e rilegge gli ID titolo dei giochi già presenti.", "info-unmatched-games-desc": "Tenta di associare giochi che non sono associati con le fonti di metadati selezionate.\n\nAd esempio, selezionando IGDB e ScreenScraper scansionerà i giochi che non sono associati con IGDB o ScreenScraper.", "info-update-metadata-desc": "Aggiorna i metadati per i giochi che sono stati associati con le fonti di metadati selezionate usando l'ID esterno (es. IGDB ID).\n\nAd esempio, selezionando IGDB e ScreenScraper aggiornerà i metadati per i giochi associati con IGDB o ScreenScraper, e userà igdb_id e/o ssfr_id per recuperare nuovamente i metadati dai rispettivi fornitori.", "live-progress": "Progresso in tempo reale", diff --git a/frontend/src/locales/it_IT/settings.json b/frontend/src/locales/it_IT/settings.json index 8621d0c73..602ab4a98 100644 --- a/frontend/src/locales/it_IT/settings.json +++ b/frontend/src/locales/it_IT/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Chiusura della sessione precedente", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ja_JP/common.json b/frontend/src/locales/ja_JP/common.json index b5716c2a4..e601dfd17 100644 --- a/frontend/src/locales/ja_JP/common.json +++ b/frontend/src/locales/ja_JP/common.json @@ -194,6 +194,7 @@ "virtual-collections": "自動生成コレクションズ", "visibility": "公開設定", "warning": "警告:", + "websocket-unreachable-retrying": "WebSocket接続が利用できません。再試行中…", "whats-new": "新機能を見る", "zoom-in": "ズームイン", "zoom-out": "ズームアウト" diff --git a/frontend/src/locales/ja_JP/notifications.json b/frontend/src/locales/ja_JP/notifications.json index b4ec992b2..9dccffcfa 100644 --- a/frontend/src/locales/ja_JP/notifications.json +++ b/frontend/src/locales/ja_JP/notifications.json @@ -2,6 +2,7 @@ "channel-add": "チャンネルを追加", "channel-address": "メールアドレス", "channel-address-hint": "本人確認のためにコードをメールで送ります", + "channel-advanced": "詳細オプション", "channel-awaiting-code": "メールで届いたコードを入力すると、ここで通知を受け取れるようになります", "channel-code": "コード", "channel-code-sent": "{address} にコードを送信しました", @@ -15,10 +16,16 @@ "channel-edit": "チャンネルを編集", "channel-email-unavailable": "このサーバーではメールが設定されていません", "channel-enabled": "ここに通知を送る", - "channel-format": "形式", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "ボット名", + "channel-field-host": "ホスト", + "channel-field-list-hint": "1 件ごとに Enter を押してください", + "channel-field-number": "{min} から {max} までの数値を入力してください", + "channel-field-path": "パス", + "channel-field-port": "ポート", + "channel-field-schema": "プロトコル", + "channel-field-targets": "送信先", + "channel-field-token": "トークン", + "channel-field-verify": "SSL 証明書を検証する", "channel-last-error": "最後のエラー: {error}", "channel-last-sent": "最終送信: {when}", "channel-level-error": "エラーのみ", @@ -27,14 +34,23 @@ "channel-min-level": "送信対象", "channel-name": "名前", "channel-new": "新しいチャンネル", + "channel-paste-failed": "その URL を読み取れませんでした", + "channel-paste-filled": "URL から読み取りました: {fields}", + "channel-paste-other-service": "その URL は {service} のものです", + "channel-paste-url": "URL を貼り付け", + "channel-paste-url-hint": "Apprise の URL で各項目を入力できます", "channel-resend": "新しいコードを送信", "channel-resend-failed": "新しいコードを送信できませんでした", "channel-save-failed": "チャンネルを保存できませんでした", "channel-saved": "チャンネルを保存しました", - "channel-secret-json": "署名シークレット(任意)", + "channel-search-services": "サービスを検索", + "channel-secret": "署名シークレット(任意)", "channel-secret-keep": "現在の値を保持するには空欄のままにします", - "channel-secret-ntfy": "アクセストークン(任意)", "channel-secret-remove": "削除する", + "channel-service-url": "{service} の URL", + "channel-service-url-hint": "{service} が発行する URL、または Apprise の URL", + "channel-services-failed": "Apprise のサービスを読み込めませんでした", + "channel-setup-guide": "{service} の設定方法", "channel-test": "テストを送信", "channel-test-failed": "テストに失敗しました: {error}", "channel-test-ok": "テストを送信しました", @@ -42,14 +58,14 @@ "channel-topics-all": "すべてのトピック", "channel-type": "種類", "channel-type-email": "メール", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM Webhook(JSON)", "channel-update-failed": "チャンネルを更新できませんでした", "channel-url": "URL", "channel-url-invalid": "http:// または https:// で始める必要があります", "channel-url-keep": "現在の URL を保持するには空欄のままにします", "channels": "チャンネル", "channels-empty": "チャンネルはまだありません", - "channels-empty-hint": "通知を Discord、ntfy、メール、または任意の Webhook に転送できます。", + "channels-empty-hint": "通知を RomM の外へ転送できます。Webhook、メールアドレスなどに送れます。", "channels-load-failed": "チャンネルを読み込めませんでした", "dismiss-all": "すべて閉じる", "dismiss-all-body": "すべての通知が削除されます。", diff --git a/frontend/src/locales/ja_JP/play.json b/frontend/src/locales/ja_JP/play.json index 474a92f9e..993c76209 100644 --- a/frontend/src/locales/ja_JP/play.json +++ b/frontend/src/locales/ja_JP/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "このコンテナでは {rom} が実行中です。先にそのセッションを終了してください。", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "全画面", "hide-older-versions": "古いバージョンを非表示", "https-required": "HTTPS で実行する必要があります。サイト管理者に連絡してください。", + "import-refusals-truncated": "他に{count}件の問題は表示されていません | 他に{count}件の問題は表示されていません", "join-closed": "このセッションは他のプレイヤーに開放されていません。", "join-ended": "このセッションは終了しました。", "jsdos-browser-save-warning": "js-dos のセーブデータはこのブラウザーにのみ保存され、RomM とは同期されません。", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "予期しないエラーが発生しました。", + "stream-error-import-refused": "選択したセーブまたはステートを使用できませんでした。", "stream-error-load-rom": "ROMの詳細を読み込めませんでした。", "stream-error-not-configured": "{platform} 用のストリーミングコンテナが構成されていません。", "stream-error-rom-not-found": "このROMが見つかりませんでした。削除された可能性があります。", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "ミュート", "stream-occupied-body": "{rom} は {time} からプレイされています。", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "前のセッションはまだ終了処理中です。しばらくしてからもう一度お試しください。", "stream-occupied-fallback": "現在、他の人がプレイ中です。後でもう一度お試しください。", "stream-occupied-title": "セッション使用中", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/ja_JP/scan.json b/frontend/src/locales/ja_JP/scan.json index de988d5b1..f2eccc4c6 100644 --- a/frontend/src/locales/ja_JP/scan.json +++ b/frontend/src/locales/ja_JP/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "全ドキュメント", "info-hashes-desc": "選択されたプラットフォームのすべてのファイルのハッシュを再計算します。", "info-new-platforms-desc": "RomMにまだないプラットフォームのみを検索します。", - "info-quick-scan-desc": "まだライブラリにないゲームをスキャンし、すでにライブラリにあるゲームのフォルダーに追加されたファイルを、任意の深さで検出します。", + "info-quick-scan-desc": "まだライブラリにないゲームをスキャンし、すでにライブラリにあるゲームのフォルダーに追加されたファイルを任意の深さで検出し、すでにライブラリにあるゲームのタイトルIDを読み直します。", "info-unmatched-games-desc": "選択されたメタデータソースとマッチしないゲームをマッチさせようとします。\n\n例えば、IGDBとScreenScraperを選択すると、IGDBまたはScreenScraperとマッチしないゲームをスキャンします。", "info-update-metadata-desc": "外部ID(例:IGDB ID)を使用して、選択されたメタデータソースとマッチしたゲームのメタデータを更新します。\n\n例えば、IGDBとScreenScraperを選択すると、IGDBまたはScreenScraperとマッチしたゲームのメタデータを更新し、igdb_idおよび/またはssfr_idを使用してそれぞれのプロバイダーからメタデータを再取得します。", "live-progress": "ライブ進行状況", diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index 3454c575f..6dcc42d6c 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "前のセッションを終了しています", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ko_KR/common.json b/frontend/src/locales/ko_KR/common.json index a803fdfb1..abfebb9f7 100644 --- a/frontend/src/locales/ko_KR/common.json +++ b/frontend/src/locales/ko_KR/common.json @@ -194,6 +194,7 @@ "virtual-collections": "자동 생성된 모음집", "visibility": "공개 범위", "warning": "경고:", + "websocket-unreachable-retrying": "WebSocket 연결을 사용할 수 없습니다. 재시도 중…", "whats-new": "새로운 기능 보기", "zoom-in": "확대", "zoom-out": "축소" diff --git a/frontend/src/locales/ko_KR/notifications.json b/frontend/src/locales/ko_KR/notifications.json index 572d97e94..a34559840 100644 --- a/frontend/src/locales/ko_KR/notifications.json +++ b/frontend/src/locales/ko_KR/notifications.json @@ -2,6 +2,7 @@ "channel-add": "채널 추가", "channel-address": "이메일 주소", "channel-address-hint": "본인 주소인지 확인할 코드를 이메일로 보내드립니다", + "channel-advanced": "고급 옵션", "channel-awaiting-code": "이메일로 받은 코드를 입력하면 여기로 알림을 받기 시작합니다", "channel-code": "코드", "channel-code-sent": "{address}(으)로 코드를 보냈습니다", @@ -15,10 +16,16 @@ "channel-edit": "채널 편집", "channel-email-unavailable": "이 서버에는 이메일이 설정되어 있지 않습니다", "channel-enabled": "여기로 알림 보내기", - "channel-format": "형식", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "봇 이름", + "channel-field-host": "호스트", + "channel-field-list-hint": "항목마다 Enter를 누르세요", + "channel-field-number": "{min}에서 {max} 사이의 숫자여야 합니다", + "channel-field-path": "경로", + "channel-field-port": "포트", + "channel-field-schema": "프로토콜", + "channel-field-targets": "대상", + "channel-field-token": "토큰", + "channel-field-verify": "SSL 인증서 확인", "channel-last-error": "마지막 오류: {error}", "channel-last-sent": "마지막 전송: {when}", "channel-level-error": "오류만", @@ -27,14 +34,23 @@ "channel-min-level": "보낼 알림", "channel-name": "이름", "channel-new": "새 채널", + "channel-paste-failed": "URL을 읽을 수 없습니다", + "channel-paste-filled": "URL에서 읽었습니다: {fields}", + "channel-paste-other-service": "이 URL은 {service}용입니다", + "channel-paste-url": "URL 붙여넣기", + "channel-paste-url-hint": "Apprise URL로 항목을 채웁니다", "channel-resend": "새 코드 보내기", "channel-resend-failed": "새 코드를 보낼 수 없습니다", "channel-save-failed": "채널을 저장할 수 없습니다", "channel-saved": "채널이 저장되었습니다", - "channel-secret-json": "서명 비밀 키 (선택)", + "channel-search-services": "서비스 검색", + "channel-secret": "서명 비밀 키 (선택)", "channel-secret-keep": "현재 값을 유지하려면 비워 두세요", - "channel-secret-ntfy": "액세스 토큰 (선택)", "channel-secret-remove": "제거", + "channel-service-url": "{service} URL", + "channel-service-url-hint": "{service}에서 받은 URL 또는 Apprise URL", + "channel-services-failed": "Apprise 서비스를 불러오지 못했습니다", + "channel-setup-guide": "{service} 설정 방법", "channel-test": "테스트 보내기", "channel-test-failed": "테스트 실패: {error}", "channel-test-ok": "테스트를 보냈습니다", @@ -42,14 +58,14 @@ "channel-topics-all": "모든 주제", "channel-type": "유형", "channel-type-email": "이메일", - "channel-type-webhook": "웹훅", + "channel-type-webhook": "RomM 웹훅 (JSON)", "channel-update-failed": "채널을 업데이트할 수 없습니다", "channel-url": "URL", "channel-url-invalid": "http:// 또는 https://로 시작해야 합니다", "channel-url-keep": "현재 URL을 유지하려면 비워 두세요", "channels": "채널", "channels-empty": "아직 채널이 없습니다", - "channels-empty-hint": "알림을 Discord, ntfy, 이메일 또는 모든 웹훅으로 전달하세요.", + "channels-empty-hint": "알림을 RomM 밖으로 전달하세요. 웹훅, 이메일 주소 등으로 보낼 수 있습니다.", "channels-load-failed": "채널을 불러올 수 없습니다", "dismiss-all": "모두 닫기", "dismiss-all-body": "모든 알림이 삭제됩니다.", diff --git a/frontend/src/locales/ko_KR/play.json b/frontend/src/locales/ko_KR/play.json index 6a4371ae1..4072a1550 100644 --- a/frontend/src/locales/ko_KR/play.json +++ b/frontend/src/locales/ko_KR/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "이 컨테이너에서 {rom}이(가) 실행 중입니다. 먼저 해당 세션을 종료하세요.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "전체 화면", "hide-older-versions": "이전 버전 숨기기", "https-required": "HTTPS로 실행해야 합니다. 사이트 관리자에게 문의하세요.", + "import-refusals-truncated": "표시되지 않은 문제가 {count}개 더 있습니다 | 표시되지 않은 문제가 {count}개 더 있습니다", "join-closed": "이 세션은 더 이상 다른 플레이어에게 열려 있지 않습니다.", "join-ended": "이 세션은 종료되었습니다.", "jsdos-browser-save-warning": "js-dos 저장 데이터는 이 브라우저에만 저장되며 RomM과 동기화되지 않습니다.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "예기치 않은 오류가 발생했습니다.", + "stream-error-import-refused": "선택한 저장 파일 또는 상태를 사용할 수 없었습니다.", "stream-error-load-rom": "ROM 세부 정보를 불러올 수 없습니다.", "stream-error-not-configured": "{platform}에 대해 구성된 스트리밍 컨테이너가 없습니다.", "stream-error-rom-not-found": "이 ROM을 찾을 수 없습니다. 삭제되었을 수 있습니다.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "음소거", "stream-occupied-body": "{rom}을(를) {time}부터 플레이하고 있습니다.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "이전 세션이 아직 종료되는 중입니다. 잠시 후 다시 시도하세요.", "stream-occupied-fallback": "현재 다른 사람이 플레이 중입니다. 나중에 다시 시도하세요.", "stream-occupied-title": "세션 사용 중", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/ko_KR/scan.json b/frontend/src/locales/ko_KR/scan.json index 5ac1465eb..e09ebf7d0 100644 --- a/frontend/src/locales/ko_KR/scan.json +++ b/frontend/src/locales/ko_KR/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "전체 문서", "info-hashes-desc": "선택한 플랫폼의 모든 파일에 대해 해시를 재계산합니다.", "info-new-platforms-desc": "RomM에 아직 없는 플랫폼만 찾습니다.", - "info-quick-scan-desc": "아직 라이브러리에 없는 게임을 스캔하고, 이미 라이브러리에 있는 게임의 폴더에 추가된 파일을 깊이에 상관없이 찾아냅니다.", + "info-quick-scan-desc": "아직 라이브러리에 없는 게임을 스캔하고, 이미 라이브러리에 있는 게임의 폴더에 추가된 파일을 깊이에 상관없이 찾아내며, 이미 라이브러리에 있는 게임의 타이틀 ID를 다시 읽습니다.", "info-unmatched-games-desc": "선택한 메타데이터 소스와 일치하지 않는 게임을 일치시키려고 시도합니다.\n\n예를 들어, IGDB와 ScreenScraper를 선택하면 IGDB나 ScreenScraper와 일치하지 않는 게임을 스캔합니다.", "info-update-metadata-desc": "외부 ID (예: IGDB ID)를 사용하여 선택한 메타데이터 소스와 일치한 게임의 메타데이터를 업데이트합니다.\n\n예를 들어, IGDB와 ScreenScraper를 선택하면 IGDB나 ScreenScraper와 일치한 게임의 메타데이터를 업데이트하고, igdb_id 및/또는 ssfr_id를 사용하여 해당 제공자로부터 메타데이터를 다시 가져옵니다.", "live-progress": "실시간 진행 상황", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index 19b6b46bc..d8781fbce 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "이전 세션을 종료하는 중", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/pl_PL/common.json b/frontend/src/locales/pl_PL/common.json index 3ffc65167..c58e02b07 100644 --- a/frontend/src/locales/pl_PL/common.json +++ b/frontend/src/locales/pl_PL/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Automatycznie wygenerowane kolekcje", "visibility": "Widoczność", "warning": "OSTRZEŻENIE:", + "websocket-unreachable-retrying": "Połączenie WebSocket niedostępne, ponawianie…", "whats-new": "Zobacz, co nowego", "zoom-in": "Powiększ", "zoom-out": "Pomniejsz" diff --git a/frontend/src/locales/pl_PL/notifications.json b/frontend/src/locales/pl_PL/notifications.json index 3449f794d..55ff7ec67 100644 --- a/frontend/src/locales/pl_PL/notifications.json +++ b/frontend/src/locales/pl_PL/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Dodaj kanał", "channel-address": "Adres e-mail", "channel-address-hint": "Wyślemy kod, aby potwierdzić, że należy do Ciebie", + "channel-advanced": "Opcje zaawansowane", "channel-awaiting-code": "Wpisz kod z e-maila, aby zacząć otrzymywać tu powiadomienia", "channel-code": "Kod", "channel-code-sent": "Wysłaliśmy kod na adres {address}", @@ -15,10 +16,16 @@ "channel-edit": "Edytuj kanał", "channel-email-unavailable": "E-mail nie jest skonfigurowany na tym serwerze", "channel-enabled": "Wysyłaj tu powiadomienia", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "JSON RomM", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Nazwa bota", + "channel-field-host": "Host", + "channel-field-list-hint": "Po każdej pozycji naciśnij Enter", + "channel-field-number": "Musi być liczbą od {min} do {max}", + "channel-field-path": "Ścieżka", + "channel-field-port": "Port", + "channel-field-schema": "Protokół", + "channel-field-targets": "Odbiorcy", + "channel-field-token": "Token", + "channel-field-verify": "Weryfikuj certyfikat SSL", "channel-last-error": "Ostatni błąd: {error}", "channel-last-sent": "Ostatnio wysłano: {when}", "channel-level-error": "Tylko błędy", @@ -27,14 +34,23 @@ "channel-min-level": "Wysyłaj", "channel-name": "Nazwa", "channel-new": "Nowy kanał", + "channel-paste-failed": "Nie udało się odczytać tego adresu URL", + "channel-paste-filled": "Odczytano z adresu URL: {fields}", + "channel-paste-other-service": "Ten adres URL jest dla {service}", + "channel-paste-url": "Wklej URL", + "channel-paste-url-hint": "Adres URL Apprise wypełnia pola", "channel-resend": "Wyślij nowy kod", "channel-resend-failed": "Nie udało się wysłać nowego kodu", "channel-save-failed": "Nie udało się zapisać kanału", "channel-saved": "Kanał zapisany", - "channel-secret-json": "Sekret podpisu (opcjonalnie)", + "channel-search-services": "Szukaj usług", + "channel-secret": "Sekret podpisu (opcjonalnie)", "channel-secret-keep": "Zostaw puste, aby zachować obecny", - "channel-secret-ntfy": "Token dostępu (opcjonalnie)", "channel-secret-remove": "Usuń go", + "channel-service-url": "Adres URL {service}", + "channel-service-url-hint": "Adres URL, który daje {service}, lub adres URL Apprise", + "channel-services-failed": "Nie udało się wczytać usług Apprise", + "channel-setup-guide": "Jak skonfigurować {service}", "channel-test": "Wyślij test", "channel-test-failed": "Test nie powiódł się: {error}", "channel-test-ok": "Test wysłany", @@ -42,14 +58,14 @@ "channel-topics-all": "Wszystkie tematy", "channel-type": "Typ", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook RomM (JSON)", "channel-update-failed": "Nie udało się zaktualizować kanału", "channel-url": "URL", "channel-url-invalid": "Musi zaczynać się od http:// lub https://", "channel-url-keep": "Zostaw puste, aby zachować obecny URL", "channels": "Kanały", "channels-empty": "Brak kanałów", - "channels-empty-hint": "Przekazuj powiadomienia do Discorda, ntfy, na e-mail lub do dowolnego webhooka.", + "channels-empty-hint": "Przekazuj powiadomienia poza RomM: do webhooka, na adres e-mail i nie tylko.", "channels-load-failed": "Nie udało się wczytać Twoich kanałów", "dismiss-all": "Odrzuć wszystkie", "dismiss-all-body": "Wszystkie powiadomienia zostaną usunięte.", diff --git a/frontend/src/locales/pl_PL/play.json b/frontend/src/locales/pl_PL/play.json index 6c2774ab5..5799abe92 100644 --- a/frontend/src/locales/pl_PL/play.json +++ b/frontend/src/locales/pl_PL/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "Na tym kontenerze działa {rom}. Najpierw zakończ tę sesję.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Pełny ekran", "hide-older-versions": "Ukryj starsze wersje", "https-required": "Musi być uruchomione przez HTTPS. Skontaktuj się z właścicielem strony.", + "import-refusals-truncated": "Nie pokazano kolejnych problemów: {count} | {count} kolejny problem nie został pokazany | Nie pokazano kolejnych problemów: {count}", "join-closed": "Ta sesja nie jest już otwarta dla innych graczy.", "join-ended": "Ta sesja się zakończyła.", "jsdos-browser-save-warning": "Zapisy js-dos są przechowywane tylko w tej przeglądarce i nie są synchronizowane z RomM.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "Wystąpił nieoczekiwany błąd.", + "stream-error-import-refused": "Nie udało się użyć wybranego zapisu lub stanu.", "stream-error-load-rom": "Nie można załadować szczegółów ROM.", "stream-error-not-configured": "Nie skonfigurowano kontenera strumieniowego dla {platform}.", "stream-error-rom-not-found": "Nie można znaleźć tego ROM-u. Mógł zostać usunięty.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Wycisz", "stream-occupied-body": "{rom} jest w grze od {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Poprzednia sesja wciąż się zamyka. Spróbuj ponownie za chwilę.", "stream-occupied-fallback": "Ktoś inny obecnie gra. Spróbuj ponownie później.", "stream-occupied-title": "Sesja w użyciu", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/pl_PL/scan.json b/frontend/src/locales/pl_PL/scan.json index 0c7b03615..79d4f9b09 100644 --- a/frontend/src/locales/pl_PL/scan.json +++ b/frontend/src/locales/pl_PL/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Pełna dokumentacja", "info-hashes-desc": "Przelicza skróty dla wszystkich plików na wybranych platformach.", "info-new-platforms-desc": "Będzie szukać tylko platform, których jeszcze nie ma w RomM.", - "info-quick-scan-desc": "Skanuje gry, których jeszcze nie ma w bibliotece, oraz wykrywa pliki dodane do folderów gier już w niej obecnych, na dowolnym poziomie zagnieżdżenia.", + "info-quick-scan-desc": "Skanuje gry, których jeszcze nie ma w bibliotece, wykrywa pliki dodane do folderów gier już w niej obecnych, na dowolnym poziomie zagnieżdżenia, i ponownie odczytuje identyfikatory tytułów gier już w niej obecnych.", "info-unmatched-games-desc": "Próbuje dopasować gry, które nie są dopasowane do wybranych źródeł metadanych.\n\nNa przykład wybór IGDB i ScreenScraper przeskanuje gry, które nie są dopasowane do IGDB lub ScreenScraper.", "info-update-metadata-desc": "Aktualizuje metadane dla gier, które zostały dopasowane do wybranych źródeł metadanych przy użyciu zewnętrznego ID (np. IGDB ID).\n\nNa przykład wybór IGDB i ScreenScraper zaktualizuje metadane dla gier dopasowanych do IGDB lub ScreenScraper i użyje igdb_id i/lub ssfr_id do ponownego pobrania metadanych od odpowiednich dostawców.", "live-progress": "Postęp na żywo", diff --git a/frontend/src/locales/pl_PL/settings.json b/frontend/src/locales/pl_PL/settings.json index 8b360915c..69cc407fa 100644 --- a/frontend/src/locales/pl_PL/settings.json +++ b/frontend/src/locales/pl_PL/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Zamykanie poprzedniej sesji", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/pt_BR/common.json b/frontend/src/locales/pt_BR/common.json index 5e54d4907..5e154ed1d 100644 --- a/frontend/src/locales/pt_BR/common.json +++ b/frontend/src/locales/pt_BR/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Coleções autogeradas", "visibility": "Visibilidade", "warning": "AVISO:", + "websocket-unreachable-retrying": "Conexão WebSocket indisponível, tentando novamente…", "whats-new": "Ver novidades", "zoom-in": "Aumentar zoom", "zoom-out": "Diminuir zoom" diff --git a/frontend/src/locales/pt_BR/notifications.json b/frontend/src/locales/pt_BR/notifications.json index cb73d3c0a..93ecee598 100644 --- a/frontend/src/locales/pt_BR/notifications.json +++ b/frontend/src/locales/pt_BR/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Adicionar canal", "channel-address": "Endereço de e-mail", "channel-address-hint": "Enviaremos um código para confirmar que é seu", + "channel-advanced": "Opções avançadas", "channel-awaiting-code": "Digite o código que enviamos por e-mail para começar a receber notificações aqui", "channel-code": "Código", "channel-code-sent": "Enviamos um código para {address}", @@ -15,10 +16,16 @@ "channel-edit": "Editar canal", "channel-email-unavailable": "O e-mail não está configurado neste servidor", "channel-enabled": "Enviar notificações aqui", - "channel-format": "Formato", - "channel-format-discord": "Discord", - "channel-format-json": "JSON do RomM", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Nome do bot", + "channel-field-host": "Host", + "channel-field-list-hint": "Pressione Enter depois de cada um", + "channel-field-number": "Deve ser um número de {min} a {max}", + "channel-field-path": "Caminho", + "channel-field-port": "Porta", + "channel-field-schema": "Protocolo", + "channel-field-targets": "Destinos", + "channel-field-token": "Token", + "channel-field-verify": "Verificar o certificado SSL", "channel-last-error": "Último erro: {error}", "channel-last-sent": "Último envio: {when}", "channel-level-error": "Somente erros", @@ -27,14 +34,23 @@ "channel-min-level": "Enviar", "channel-name": "Nome", "channel-new": "Novo canal", + "channel-paste-failed": "Não foi possível ler essa URL", + "channel-paste-filled": "Lido da URL: {fields}", + "channel-paste-other-service": "Essa URL é do {service}", + "channel-paste-url": "Colar uma URL", + "channel-paste-url-hint": "Uma URL do Apprise preenche os campos", "channel-resend": "Enviar um novo código", "channel-resend-failed": "Não foi possível enviar um novo código", "channel-save-failed": "Não foi possível salvar o canal", "channel-saved": "Canal salvo", - "channel-secret-json": "Segredo de assinatura (opcional)", + "channel-search-services": "Buscar serviços", + "channel-secret": "Segredo de assinatura (opcional)", "channel-secret-keep": "Deixe em branco para manter o atual", - "channel-secret-ntfy": "Token de acesso (opcional)", "channel-secret-remove": "Removê-lo", + "channel-service-url": "URL do {service}", + "channel-service-url-hint": "A URL que o {service} fornece, ou uma URL do Apprise", + "channel-services-failed": "Não foi possível carregar os serviços do Apprise", + "channel-setup-guide": "Como configurar o {service}", "channel-test": "Enviar um teste", "channel-test-failed": "O teste falhou: {error}", "channel-test-ok": "Teste enviado", @@ -42,14 +58,14 @@ "channel-topics-all": "Todos os tópicos", "channel-type": "Tipo", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook do RomM (JSON)", "channel-update-failed": "Não foi possível atualizar o canal", "channel-url": "URL", "channel-url-invalid": "Deve começar com http:// ou https://", "channel-url-keep": "Deixe em branco para manter a URL atual", "channels": "Canais", "channels-empty": "Nenhum canal ainda", - "channels-empty-hint": "Encaminhe suas notificações para o Discord, ntfy, e-mail ou qualquer webhook.", + "channels-empty-hint": "Encaminhe suas notificações para fora do RomM: para um webhook, um endereço de e-mail e mais.", "channels-load-failed": "Não foi possível carregar seus canais", "dismiss-all": "Dispensar todas", "dismiss-all-body": "Todas as notificações serão removidas.", diff --git a/frontend/src/locales/pt_BR/play.json b/frontend/src/locales/pt_BR/play.json index 3fb16e79f..490fcd583 100644 --- a/frontend/src/locales/pt_BR/play.json +++ b/frontend/src/locales/pt_BR/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} está em execução neste contêiner. Encerre essa sessão primeiro.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Tela cheia", "hide-older-versions": "Ocultar versões anteriores", "https-required": "Deve ser executado via HTTPS. Entre em contato com o proprietário do site.", + "import-refusals-truncated": "{count} problema a mais não exibido | {count} problemas a mais não exibidos", "join-closed": "Essa sessão não está mais aberta a outros jogadores.", "join-ended": "Essa sessão foi encerrada.", "jsdos-browser-save-warning": "Os saves do js-dos são armazenados apenas neste navegador e não são sincronizados com o RomM.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "Ocorreu um erro inesperado.", + "stream-error-import-refused": "Não foi possível usar o save ou state selecionado.", "stream-error-load-rom": "Não foi possível carregar os detalhes da ROM.", "stream-error-not-configured": "Nenhum contêiner de streaming está configurado para {platform}.", "stream-error-rom-not-found": "Esta ROM não foi encontrada. Ela pode ter sido removida.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Silenciar", "stream-occupied-body": "{rom} está sendo jogado desde {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "A sessão anterior ainda está sendo encerrada. Tente novamente em instantes.", "stream-occupied-fallback": "Outra pessoa está jogando no momento. Tente novamente mais tarde.", "stream-occupied-title": "Sessão em uso", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/pt_BR/scan.json b/frontend/src/locales/pt_BR/scan.json index c90e76c03..7b4c15ba2 100644 --- a/frontend/src/locales/pt_BR/scan.json +++ b/frontend/src/locales/pt_BR/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Documentação completa", "info-hashes-desc": "Recalcula hashes para todos os arquivos nas plataformas selecionadas.", "info-new-platforms-desc": "Procurará apenas plataformas que ainda não estão no RomM.", - "info-quick-scan-desc": "Varre jogos que ainda não estão na biblioteca e detecta arquivos adicionados às pastas de jogos já presentes, em qualquer nível.", + "info-quick-scan-desc": "Varre jogos que ainda não estão na biblioteca, detecta arquivos adicionados às pastas de jogos já presentes, em qualquer nível, e relê os IDs de título dos jogos já presentes.", "info-unmatched-games-desc": "Tenta corresponder jogos que não estão correspondendo com as fontes de metadados selecionadas.\n\nPor exemplo, selecionar IGDB e ScreenScraper varrará jogos que não estão correspondendo com IGDB ou ScreenScraper.", "info-update-metadata-desc": "Atualiza os metadados para jogos que foram correspondidos com fontes de metadados selecionadas usando o ID externo (ex. IGDB ID).\n\nPor exemplo, selecionar IGDB e ScreenScraper atualizará os metadados para jogos correspondidos com IGDB ou ScreenScraper, e usará igdb_id e/ou ssfr_id para buscar novamente os metadados dos respectivos provedores.", "live-progress": "Progresso ao vivo", diff --git a/frontend/src/locales/pt_BR/settings.json b/frontend/src/locales/pt_BR/settings.json index fe3829f7c..e6312b6c3 100644 --- a/frontend/src/locales/pt_BR/settings.json +++ b/frontend/src/locales/pt_BR/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Encerrando a sessão anterior", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ro_RO/common.json b/frontend/src/locales/ro_RO/common.json index 0fe6de31d..63334a0fc 100644 --- a/frontend/src/locales/ro_RO/common.json +++ b/frontend/src/locales/ro_RO/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Colecții autogenerate", "visibility": "Vizibilitate", "warning": "AVERTISMENT:", + "websocket-unreachable-retrying": "Conexiunea WebSocket nu este disponibilă, se reîncearcă…", "whats-new": "Vezi noutățile", "zoom-in": "Mărește", "zoom-out": "Micșorează" diff --git a/frontend/src/locales/ro_RO/notifications.json b/frontend/src/locales/ro_RO/notifications.json index b653deea8..67a492d0a 100644 --- a/frontend/src/locales/ro_RO/notifications.json +++ b/frontend/src/locales/ro_RO/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Adaugă canal", "channel-address": "Adresă de e-mail", "channel-address-hint": "Îți vom trimite un cod ca să confirmi că este a ta", + "channel-advanced": "Opțiuni avansate", "channel-awaiting-code": "Introdu codul primit pe e-mail ca să începi să primești notificări aici", "channel-code": "Cod", "channel-code-sent": "Am trimis un cod la {address}", @@ -15,10 +16,16 @@ "channel-edit": "Editează canalul", "channel-email-unavailable": "E-mailul nu este configurat pe acest server", "channel-enabled": "Trimite notificări aici", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "JSON RomM", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Numele botului", + "channel-field-host": "Gazdă", + "channel-field-list-hint": "Apasă Enter după fiecare", + "channel-field-number": "Trebuie să fie un număr între {min} și {max}", + "channel-field-path": "Cale", + "channel-field-port": "Port", + "channel-field-schema": "Protocol", + "channel-field-targets": "Destinatari", + "channel-field-token": "Token", + "channel-field-verify": "Verifică certificatul SSL", "channel-last-error": "Ultima eroare: {error}", "channel-last-sent": "Ultima trimitere: {when}", "channel-level-error": "Doar erori", @@ -27,14 +34,23 @@ "channel-min-level": "Trimite", "channel-name": "Nume", "channel-new": "Canal nou", + "channel-paste-failed": "URL-ul nu a putut fi citit", + "channel-paste-filled": "Citit din URL: {fields}", + "channel-paste-other-service": "Acest URL este pentru {service}", + "channel-paste-url": "Lipește un URL", + "channel-paste-url-hint": "Un URL Apprise completează câmpurile", "channel-resend": "Trimite un cod nou", "channel-resend-failed": "Nu s-a putut trimite un cod nou", "channel-save-failed": "Canalul nu a putut fi salvat", "channel-saved": "Canal salvat", - "channel-secret-json": "Secret de semnare (opțional)", + "channel-search-services": "Caută servicii", + "channel-secret": "Secret de semnare (opțional)", "channel-secret-keep": "Lasă gol ca să păstrezi valoarea actuală", - "channel-secret-ntfy": "Token de acces (opțional)", "channel-secret-remove": "Elimină-l", + "channel-service-url": "URL {service}", + "channel-service-url-hint": "URL-ul pe care ți-l dă {service} sau un URL Apprise", + "channel-services-failed": "Serviciile Apprise nu au putut fi încărcate", + "channel-setup-guide": "Cum configurezi {service}", "channel-test": "Trimite un test", "channel-test-failed": "Testul a eșuat: {error}", "channel-test-ok": "Test trimis", @@ -42,14 +58,14 @@ "channel-topics-all": "Toate subiectele", "channel-type": "Tip", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook RomM (JSON)", "channel-update-failed": "Canalul nu a putut fi actualizat", "channel-url": "URL", "channel-url-invalid": "Trebuie să înceapă cu http:// sau https://", "channel-url-keep": "Lasă gol ca să păstrezi URL-ul actual", "channels": "Canale", "channels-empty": "Încă nu există canale", - "channels-empty-hint": "Redirecționează notificările către Discord, ntfy, e-mail sau orice webhook.", + "channels-empty-hint": "Redirecționează notificările în afara RomM: către un webhook, o adresă de e-mail și altele.", "channels-load-failed": "Canalele tale nu au putut fi încărcate", "dismiss-all": "Închide toate", "dismiss-all-body": "Toate notificările vor fi eliminate.", diff --git a/frontend/src/locales/ro_RO/play.json b/frontend/src/locales/ro_RO/play.json index 8834d5689..fa5c62f88 100644 --- a/frontend/src/locales/ro_RO/play.json +++ b/frontend/src/locales/ro_RO/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} rulează pe acest container. Închide mai întâi acea sesiune.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Ecran complet", "hide-older-versions": "Ascunde versiunile mai vechi", "https-required": "Trebuie rulat prin HTTPS. Contactează proprietarul site-ului.", + "import-refusals-truncated": "Încă {count} problemă nu este afișată | Încă {count} probleme nu sunt afișate", "join-closed": "Acea sesiune nu mai este deschisă altor jucători.", "join-ended": "Acea sesiune s-a încheiat.", "jsdos-browser-save-warning": "Salvările js-dos sunt stocate numai în acest browser și nu sunt sincronizate cu RomM.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "A apărut o eroare neașteptată.", + "stream-error-import-refused": "Salvarea sau starea aleasă nu a putut fi folosită.", "stream-error-load-rom": "Detaliile ROM-ului nu au putut fi încărcate.", "stream-error-not-configured": "Niciun container de streaming nu este configurat pentru {platform}.", "stream-error-rom-not-found": "Acest ROM nu a putut fi găsit. Este posibil să fi fost eliminat.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Dezactivează sunetul", "stream-occupied-body": "{rom} este jucat din {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Sesiunea anterioară încă se închide. Încearcă din nou peste câteva momente.", "stream-occupied-fallback": "Altcineva joacă în acest moment. Încercați din nou mai târziu.", "stream-occupied-title": "Sesiune în uz", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/ro_RO/scan.json b/frontend/src/locales/ro_RO/scan.json index 208def8be..6b5e7327d 100644 --- a/frontend/src/locales/ro_RO/scan.json +++ b/frontend/src/locales/ro_RO/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Documentație completă", "info-hashes-desc": "Recalculează hash-urile pentru toate fișierele din platformele selectate.", "info-new-platforms-desc": "Va căuta doar platformele care nu sunt încă în RomM.", - "info-quick-scan-desc": "Scanează jocurile care nu sunt încă în bibliotecă și detectează fișierele adăugate în folderele jocurilor deja existente, la orice nivel.", + "info-quick-scan-desc": "Scanează jocurile care nu sunt încă în bibliotecă, detectează fișierele adăugate în folderele jocurilor deja existente, la orice nivel, și recitește ID-urile de titlu ale jocurilor deja existente.", "info-unmatched-games-desc": "Încearcă să coreleze jocurile care nu sunt corelate cu sursele de metadate selectate.\n\nDe exemplu, selectarea IGDB și ScreenScraper va scana jocurile care nu sunt corelate cu IGDB sau ScreenScraper.", "info-update-metadata-desc": "Actualizează metadatele pentru jocurile care au fost corelate cu sursele de metadate selectate folosind ID-ul extern (de ex. IGDB ID).\n\nDe exemplu, selectarea IGDB și ScreenScraper va actualiza metadatele pentru jocurile corelate cu IGDB sau ScreenScraper și va folosi igdb_id și/sau ssfr_id pentru a reîncărca metadatele de la furnizorii respectivi.", "live-progress": "Progres în timp real", diff --git a/frontend/src/locales/ro_RO/settings.json b/frontend/src/locales/ro_RO/settings.json index e46ef94f4..c3887f577 100644 --- a/frontend/src/locales/ro_RO/settings.json +++ b/frontend/src/locales/ro_RO/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Se închide sesiunea anterioară", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ru_RU/common.json b/frontend/src/locales/ru_RU/common.json index ca060ef11..123f8eec2 100644 --- a/frontend/src/locales/ru_RU/common.json +++ b/frontend/src/locales/ru_RU/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Автосгенерированные коллекции", "visibility": "Видимость", "warning": "ВНИМАНИЕ:", + "websocket-unreachable-retrying": "Соединение WebSocket недоступно, повторная попытка…", "whats-new": "Что нового", "zoom-in": "Приблизить", "zoom-out": "Отдалить" diff --git a/frontend/src/locales/ru_RU/notifications.json b/frontend/src/locales/ru_RU/notifications.json index 5edf2a668..1f08c1961 100644 --- a/frontend/src/locales/ru_RU/notifications.json +++ b/frontend/src/locales/ru_RU/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Добавить канал", "channel-address": "Адрес эл. почты", "channel-address-hint": "Мы отправим код, чтобы подтвердить, что адрес ваш", + "channel-advanced": "Дополнительные параметры", "channel-awaiting-code": "Введите код из письма, чтобы начать получать сюда уведомления", "channel-code": "Код", "channel-code-sent": "Мы отправили код на {address}", @@ -15,10 +16,16 @@ "channel-edit": "Изменить канал", "channel-email-unavailable": "Эл. почта на этом сервере не настроена", "channel-enabled": "Отправлять уведомления сюда", - "channel-format": "Формат", - "channel-format-discord": "Discord", - "channel-format-json": "JSON RomM", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Имя бота", + "channel-field-host": "Хост", + "channel-field-list-hint": "Нажимайте Enter после каждого", + "channel-field-number": "Должно быть числом от {min} до {max}", + "channel-field-path": "Путь", + "channel-field-port": "Порт", + "channel-field-schema": "Протокол", + "channel-field-targets": "Получатели", + "channel-field-token": "Токен", + "channel-field-verify": "Проверять SSL-сертификат", "channel-last-error": "Последняя ошибка: {error}", "channel-last-sent": "Последняя отправка: {when}", "channel-level-error": "Только ошибки", @@ -27,14 +34,23 @@ "channel-min-level": "Отправлять", "channel-name": "Название", "channel-new": "Новый канал", + "channel-paste-failed": "Не удалось прочитать этот URL", + "channel-paste-filled": "Прочитано из URL: {fields}", + "channel-paste-other-service": "Этот URL для {service}", + "channel-paste-url": "Вставить URL", + "channel-paste-url-hint": "URL Apprise заполняет поля", "channel-resend": "Отправить новый код", "channel-resend-failed": "Не удалось отправить новый код", "channel-save-failed": "Не удалось сохранить канал", "channel-saved": "Канал сохранён", - "channel-secret-json": "Секрет подписи (необязательно)", + "channel-search-services": "Поиск сервисов", + "channel-secret": "Секрет подписи (необязательно)", "channel-secret-keep": "Оставьте пустым, чтобы сохранить текущий", - "channel-secret-ntfy": "Токен доступа (необязательно)", "channel-secret-remove": "Удалить его", + "channel-service-url": "URL {service}", + "channel-service-url-hint": "URL, который выдаёт {service}, или URL Apprise", + "channel-services-failed": "Не удалось загрузить сервисы Apprise", + "channel-setup-guide": "Как настроить {service}", "channel-test": "Отправить тест", "channel-test-failed": "Тест не прошёл: {error}", "channel-test-ok": "Тест отправлен", @@ -42,14 +58,14 @@ "channel-topics-all": "Все темы", "channel-type": "Тип", "channel-type-email": "Эл. почта", - "channel-type-webhook": "Вебхук", + "channel-type-webhook": "Вебхук RomM (JSON)", "channel-update-failed": "Не удалось обновить канал", "channel-url": "URL", "channel-url-invalid": "Должен начинаться с http:// или https://", "channel-url-keep": "Оставьте пустым, чтобы сохранить текущий URL", "channels": "Каналы", "channels-empty": "Каналов пока нет", - "channels-empty-hint": "Пересылайте уведомления в Discord, ntfy, на эл. почту или в любой вебхук.", + "channels-empty-hint": "Пересылайте уведомления за пределы RomM: в вебхук, на адрес эл. почты и не только.", "channels-load-failed": "Не удалось загрузить ваши каналы", "dismiss-all": "Закрыть все", "dismiss-all-body": "Все уведомления будут удалены.", diff --git a/frontend/src/locales/ru_RU/play.json b/frontend/src/locales/ru_RU/play.json index 6788de43d..c225ec107 100644 --- a/frontend/src/locales/ru_RU/play.json +++ b/frontend/src/locales/ru_RU/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "На этом контейнере запущено: {rom}. Сначала завершите эту сессию.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Полный экран", "hide-older-versions": "Скрыть старые версии", "https-required": "Требуется запуск через HTTPS. Свяжитесь с владельцем сайта.", + "import-refusals-truncated": "Ещё {count} проблема не показана | Ещё {count} проблем не показано", "join-closed": "Эта сессия больше не открыта для других игроков.", "join-ended": "Эта сессия завершена.", "jsdos-browser-save-warning": "Сохранения js-dos хранятся только в этом браузере и не синхронизируются с RomM.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "Произошла непредвиденная ошибка.", + "stream-error-import-refused": "Не удалось использовать выбранное сохранение или состояние.", "stream-error-load-rom": "Не удалось загрузить сведения о ROM.", "stream-error-not-configured": "Для {platform} не настроен контейнер потоковой передачи.", "stream-error-rom-not-found": "Этот ROM не найден. Возможно, он был удалён.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Отключить звук", "stream-occupied-body": "В {rom} играют с {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Предыдущая сессия ещё завершается. Попробуйте снова через несколько секунд.", "stream-occupied-fallback": "Сейчас играет кто-то другой. Повторите попытку позже.", "stream-occupied-title": "Сеанс занят", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/ru_RU/scan.json b/frontend/src/locales/ru_RU/scan.json index 4510e4455..fe3521eac 100644 --- a/frontend/src/locales/ru_RU/scan.json +++ b/frontend/src/locales/ru_RU/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Полная документация", "info-hashes-desc": "Пересчитывает хеши для всех файлов в выбранных платформах.", "info-new-platforms-desc": "Будет искать только платформы, которых ещё нет в RomM.", - "info-quick-scan-desc": "Сканирует игры, которых ещё нет в библиотеке, и находит файлы, добавленные в папки уже имеющихся игр, на любом уровне вложенности.", + "info-quick-scan-desc": "Сканирует игры, которых ещё нет в библиотеке, находит файлы, добавленные в папки уже имеющихся игр, на любом уровне вложенности, и заново считывает идентификаторы тайтлов уже имеющихся игр.", "info-unmatched-games-desc": "Пытается сопоставить игры, которые не сопоставлены с выбранными источниками метаданных.\n\nНапример, выбор IGDB и ScreenScraper будет сканировать игры, которые не сопоставлены с IGDB или ScreenScraper.", "info-update-metadata-desc": "Обновляет метаданные для игр, которые были сопоставлены с выбранными источниками метаданных, используя внешний ID (например, IGDB ID).\n\nНапример, выбор IGDB и ScreenScraper обновит метаданные для игр, сопоставленных с IGDB или ScreenScraper, и будет использовать igdb_id и/или ssfr_id для повторного получения метаданных от соответствующих провайдеров.", "live-progress": "Прогресс в реальном времени", diff --git a/frontend/src/locales/ru_RU/settings.json b/frontend/src/locales/ru_RU/settings.json index 0a0385e7f..b72aad941 100644 --- a/frontend/src/locales/ru_RU/settings.json +++ b/frontend/src/locales/ru_RU/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Завершение предыдущей сессии", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/tr_TR/common.json b/frontend/src/locales/tr_TR/common.json index f4e259639..86159aae0 100644 --- a/frontend/src/locales/tr_TR/common.json +++ b/frontend/src/locales/tr_TR/common.json @@ -194,6 +194,7 @@ "virtual-collections": "Otomatik oluşturulan koleksiyonlar", "visibility": "Görünürlük", "warning": "UYARI:", + "websocket-unreachable-retrying": "WebSocket bağlantısı kullanılamıyor, yeniden deneniyor…", "whats-new": "Yeniliklere göz at", "zoom-in": "Yakınlaştır", "zoom-out": "Uzaklaştır" diff --git a/frontend/src/locales/tr_TR/notifications.json b/frontend/src/locales/tr_TR/notifications.json index 4540cbfee..447d419a3 100644 --- a/frontend/src/locales/tr_TR/notifications.json +++ b/frontend/src/locales/tr_TR/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Kanal ekle", "channel-address": "E-posta adresi", "channel-address-hint": "Size ait olduğunu doğrulamak için bir kod göndereceğiz", + "channel-advanced": "Gelişmiş seçenekler", "channel-awaiting-code": "Buraya bildirim almaya başlamak için e-postayla gönderdiğimiz kodu girin", "channel-code": "Kod", "channel-code-sent": "{address} adresine bir kod gönderdik", @@ -15,10 +16,16 @@ "channel-edit": "Kanalı düzenle", "channel-email-unavailable": "Bu sunucuda e-posta ayarlanmamış", "channel-enabled": "Bildirimleri buraya gönder", - "channel-format": "Biçim", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "Bot adı", + "channel-field-host": "Sunucu", + "channel-field-list-hint": "Her birinden sonra Enter'a basın", + "channel-field-number": "{min} ile {max} arasında bir sayı olmalı", + "channel-field-path": "Yol", + "channel-field-port": "Port", + "channel-field-schema": "Protokol", + "channel-field-targets": "Hedefler", + "channel-field-token": "Token", + "channel-field-verify": "SSL sertifikasını doğrula", "channel-last-error": "Son hata: {error}", "channel-last-sent": "Son gönderim: {when}", "channel-level-error": "Yalnızca hatalar", @@ -27,14 +34,23 @@ "channel-min-level": "Gönder", "channel-name": "Ad", "channel-new": "Yeni kanal", + "channel-paste-failed": "Bu URL okunamadı", + "channel-paste-filled": "URL'den okundu: {fields}", + "channel-paste-other-service": "Bu URL {service} için", + "channel-paste-url": "URL yapıştır", + "channel-paste-url-hint": "Bir Apprise URL'si alanları doldurur", "channel-resend": "Yeni kod gönder", "channel-resend-failed": "Yeni kod gönderilemedi", "channel-save-failed": "Kanal kaydedilemedi", "channel-saved": "Kanal kaydedildi", - "channel-secret-json": "İmza anahtarı (isteğe bağlı)", + "channel-search-services": "Hizmet ara", + "channel-secret": "İmza anahtarı (isteğe bağlı)", "channel-secret-keep": "Mevcut olanı korumak için boş bırakın", - "channel-secret-ntfy": "Erişim belirteci (isteğe bağlı)", "channel-secret-remove": "Kaldır", + "channel-service-url": "{service} URL'si", + "channel-service-url-hint": "{service} tarafından verilen URL veya bir Apprise URL'si", + "channel-services-failed": "Apprise hizmetleri yüklenemedi", + "channel-setup-guide": "{service} nasıl kurulur", "channel-test": "Test gönder", "channel-test-failed": "Test başarısız: {error}", "channel-test-ok": "Test gönderildi", @@ -42,14 +58,14 @@ "channel-topics-all": "Tüm konular", "channel-type": "Tür", "channel-type-email": "E-posta", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM webhook'u (JSON)", "channel-update-failed": "Kanal güncellenemedi", "channel-url": "URL", "channel-url-invalid": "http:// veya https:// ile başlamalı", "channel-url-keep": "Mevcut URL'yi korumak için boş bırakın", "channels": "Kanallar", "channels-empty": "Henüz kanal yok", - "channels-empty-hint": "Bildirimlerinizi Discord, ntfy, e-posta veya herhangi bir webhook'a iletin.", + "channels-empty-hint": "Bildirimlerinizi RomM dışına iletin: bir webhook'a, bir e-posta adresine ve daha fazlasına.", "channels-load-failed": "Kanallarınız yüklenemedi", "dismiss-all": "Tümünü kapat", "dismiss-all-body": "Tüm bildirimler kaldırılacak.", diff --git a/frontend/src/locales/tr_TR/play.json b/frontend/src/locales/tr_TR/play.json index 3e25f7515..b2f75b83a 100644 --- a/frontend/src/locales/tr_TR/play.json +++ b/frontend/src/locales/tr_TR/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "Bu konteynerde {rom} çalışıyor. Önce o oturumu sonlandırın.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "Tam ekran", "hide-older-versions": "Eski sürümleri gizle", "https-required": "HTTPS üzerinden çalıştırılmalıdır. Site sahibiyle iletişime geçin.", + "import-refusals-truncated": "{count} sorun daha gösterilmedi | {count} sorun daha gösterilmedi", "join-closed": "Bu oturum artık diğer oyunculara açık değil.", "join-ended": "Bu oturum sona erdi.", "jsdos-browser-save-warning": "js-dos kayıtları yalnızca bu tarayıcıda saklanır ve RomM ile eşitlenmez.", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "Beklenmeyen bir hata oluştu.", + "stream-error-import-refused": "Seçilen kayıt veya durum kullanılamadı.", "stream-error-load-rom": "ROM ayrıntıları yüklenemedi.", "stream-error-not-configured": "{platform} için yapılandırılmış bir yayın konteyneri yok.", "stream-error-rom-not-found": "Bu ROM bulunamadı. Kaldırılmış olabilir.", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Sessize al", "stream-occupied-body": "{rom} {time} saatinden beri oynanıyor.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Önceki oturum hâlâ kapatılıyor. Birazdan tekrar deneyin.", "stream-occupied-fallback": "Şu anda başka biri oynuyor. Daha sonra tekrar deneyin.", "stream-occupied-title": "Oturum kullanımda", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/tr_TR/scan.json b/frontend/src/locales/tr_TR/scan.json index 5e277eb10..43c989039 100644 --- a/frontend/src/locales/tr_TR/scan.json +++ b/frontend/src/locales/tr_TR/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "Tam dokümantasyon", "info-hashes-desc": "Seçili platformlardaki tüm dosyalar için hash değerlerini yeniden hesaplar.", "info-new-platforms-desc": "Yalnızca RomM'de henüz bulunmayan platformları arar.", - "info-quick-scan-desc": "Kütüphanede henüz olmayan oyunları tarar ve kütüphanede bulunan oyunların klasörlerine eklenen dosyaları, herhangi bir derinlikte algılar.", + "info-quick-scan-desc": "Kütüphanede henüz olmayan oyunları tarar, kütüphanede bulunan oyunların klasörlerine eklenen dosyaları herhangi bir derinlikte algılar ve kütüphanede bulunan oyunların başlık kimliklerini yeniden okur.", "info-unmatched-games-desc": "Seçili meta veri kaynaklarıyla eşleştirilmemiş oyunları eşleştirmeye çalışır.\n\nÖrneğin IGDB ve ScreenScraper seçmek, bu kaynaklardan biriyle eşleştirilmemiş oyunları tarar.", "info-update-metadata-desc": "Seçili meta veri kaynaklarıyla eşleştirilmiş oyunların meta verilerini harici ID'yi (ör. IGDB ID) kullanarak günceller.\n\nÖrneğin IGDB ve ScreenScraper seçmek, bu kaynaklarla eşleştirilmiş oyunların meta verilerini günceller ve meta verileri ilgili sağlayıcılardan yeniden çekmek için igdb_id ve/veya ssfr_id kullanır.", "live-progress": "Canlı ilerleme", diff --git a/frontend/src/locales/tr_TR/settings.json b/frontend/src/locales/tr_TR/settings.json index 6d417f8d6..e3677656b 100644 --- a/frontend/src/locales/tr_TR/settings.json +++ b/frontend/src/locales/tr_TR/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Önceki oturum kapatılıyor", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/zh_CN/common.json b/frontend/src/locales/zh_CN/common.json index dc1bc13b1..29696ae5a 100644 --- a/frontend/src/locales/zh_CN/common.json +++ b/frontend/src/locales/zh_CN/common.json @@ -194,6 +194,7 @@ "virtual-collections": "自动生成的集合", "visibility": "可见性", "warning": "警告:", + "websocket-unreachable-retrying": "WebSocket 连接不可用,正在重试…", "whats-new": "查看新功能", "zoom-in": "放大", "zoom-out": "缩小" diff --git a/frontend/src/locales/zh_CN/notifications.json b/frontend/src/locales/zh_CN/notifications.json index 27ad167b1..1eb1565b3 100644 --- a/frontend/src/locales/zh_CN/notifications.json +++ b/frontend/src/locales/zh_CN/notifications.json @@ -2,6 +2,7 @@ "channel-add": "添加渠道", "channel-address": "电子邮件地址", "channel-address-hint": "我们会发送验证码以确认该地址属于你", + "channel-advanced": "高级选项", "channel-awaiting-code": "输入邮件中的验证码,即可开始在这里接收通知", "channel-code": "验证码", "channel-code-sent": "我们已向 {address} 发送验证码", @@ -15,10 +16,16 @@ "channel-edit": "编辑渠道", "channel-email-unavailable": "此服务器未配置电子邮件", "channel-enabled": "向这里发送通知", - "channel-format": "格式", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "机器人名称", + "channel-field-host": "主机", + "channel-field-list-hint": "每输入一项后按回车", + "channel-field-number": "必须是 {min} 到 {max} 之间的数字", + "channel-field-path": "路径", + "channel-field-port": "端口", + "channel-field-schema": "协议", + "channel-field-targets": "目标", + "channel-field-token": "令牌", + "channel-field-verify": "验证 SSL 证书", "channel-last-error": "最近的错误:{error}", "channel-last-sent": "最近发送:{when}", "channel-level-error": "仅错误", @@ -27,14 +34,23 @@ "channel-min-level": "发送", "channel-name": "名称", "channel-new": "新建渠道", + "channel-paste-failed": "无法读取该 URL", + "channel-paste-filled": "已从 URL 读取:{fields}", + "channel-paste-other-service": "该 URL 属于 {service}", + "channel-paste-url": "粘贴 URL", + "channel-paste-url-hint": "Apprise URL 会填写各字段", "channel-resend": "发送新验证码", "channel-resend-failed": "无法发送新验证码", "channel-save-failed": "无法保存渠道", "channel-saved": "渠道已保存", - "channel-secret-json": "签名密钥(可选)", + "channel-search-services": "搜索服务", + "channel-secret": "签名密钥(可选)", "channel-secret-keep": "留空以保留当前值", - "channel-secret-ntfy": "访问令牌(可选)", "channel-secret-remove": "移除", + "channel-service-url": "{service} URL", + "channel-service-url-hint": "{service} 提供的 URL,或 Apprise URL", + "channel-services-failed": "无法加载 Apprise 服务", + "channel-setup-guide": "如何设置 {service}", "channel-test": "发送测试", "channel-test-failed": "测试失败:{error}", "channel-test-ok": "测试已发送", @@ -42,14 +58,14 @@ "channel-topics-all": "所有主题", "channel-type": "类型", "channel-type-email": "电子邮件", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM Webhook(JSON)", "channel-update-failed": "无法更新渠道", "channel-url": "URL", "channel-url-invalid": "必须以 http:// 或 https:// 开头", "channel-url-keep": "留空以保留当前 URL", "channels": "渠道", "channels-empty": "暂无渠道", - "channels-empty-hint": "将你的通知转发到 Discord、ntfy、电子邮件或任意 Webhook。", + "channels-empty-hint": "将你的通知转发到 RomM 之外:Webhook、电子邮件地址等。", "channels-load-failed": "无法加载你的渠道", "dismiss-all": "全部忽略", "dismiss-all-body": "所有通知都将被移除。", diff --git a/frontend/src/locales/zh_CN/play.json b/frontend/src/locales/zh_CN/play.json index e1a214169..115131324 100644 --- a/frontend/src/locales/zh_CN/play.json +++ b/frontend/src/locales/zh_CN/play.json @@ -29,6 +29,7 @@ "desktop-back": "返回管理后台", "desktop-error-no-container": "未配置该串流容器。", "desktop-error-occupied": "此容器正在使用中。请先结束占用它的会话。", + "desktop-error-occupied-by": "此容器上正在运行 {rom}。请先结束该会话。", "desktop-error-release": "无法释放桌面会话。容器可能仍在使用中。", "desktop-error-server": "无法打开桌面会话。", "desktop-exit": "结束桌面会话", @@ -57,6 +58,7 @@ "full-screen": "全屏", "hide-older-versions": "隐藏旧版本", "https-required": "必须通过 HTTPS 运行。请联系网站所有者。", + "import-refusals-truncated": "还有 {count} 个问题未显示 | 还有 {count} 个问题未显示", "join-closed": "该会话不再对其他玩家开放。", "join-ended": "该会话已结束。", "jsdos-browser-save-warning": "js-dos 存档仅保存在此浏览器中,不会与 RomM 同步。", @@ -215,6 +217,7 @@ "states-view-list": "列表", "states-view-strip": "行", "stream-error-generic": "发生意外错误。", + "stream-error-import-refused": "无法使用所选的存档或即时存档。", "stream-error-load-rom": "无法加载 ROM 详细信息。", "stream-error-not-configured": "未为 {platform} 配置流式容器。", "stream-error-rom-not-found": "找不到此 ROM。它可能已被删除。", @@ -225,7 +228,7 @@ "stream-load-state-failed": "无法加载该状态。", "stream-mute": "静音", "stream-occupied-body": "{rom} 自 {time} 起一直在游玩。", - "stream-occupied-draining": "上一个会话仍在保存中。请稍后再试。", + "stream-occupied-draining": "上一个会话仍在关闭中。请稍后再试。", "stream-occupied-fallback": "当前有其他人正在游玩。请稍后再试。", "stream-occupied-title": "会话使用中", "stream-release-failed": "无法释放会话。容器可能仍在使用中。", diff --git a/frontend/src/locales/zh_CN/scan.json b/frontend/src/locales/zh_CN/scan.json index 8abe6bb98..77b78f7bc 100644 --- a/frontend/src/locales/zh_CN/scan.json +++ b/frontend/src/locales/zh_CN/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "完整文档", "info-hashes-desc": "为选定平台中的所有文件重新计算哈希值。", "info-new-platforms-desc": "仅查找尚未在 RomM 中的平台。", - "info-quick-scan-desc": "扫描尚未在游戏库中的游戏,并识别已在游戏库中的游戏文件夹内任意层级新增的文件。", + "info-quick-scan-desc": "扫描尚未在游戏库中的游戏,识别已在游戏库中的游戏文件夹内任意层级新增的文件,并重新读取游戏库中已有游戏的标题 ID。", "info-unmatched-games-desc": "尝试匹配与所选元数据源未匹配的游戏。\n\n例如,选择 IGDB 和 ScreenScraper 将扫描与 IGDB 或 ScreenScraper 未匹配的游戏。", "info-update-metadata-desc": "使用外部 ID(如 IGDB ID)为已与所选元数据源匹配的游戏更新元数据。\n\n例如,选择 IGDB 和 ScreenScraper 将为与 IGDB 或 ScreenScraper 匹配的游戏更新元数据,并使用 igdb_id 和/或 ssfr_id 从相应提供者重新获取元数据。", "live-progress": "实时进度", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index 66db3dc49..a37a71f38 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "桌面会话", "streaming-disabled": "此服务器已禁用模拟器串流。", + "streaming-draining": "正在关闭上一个会话", "streaming-idle": "空闲", "streaming-load-failed": "无法加载串流容器。", "streaming-none": "未配置任何串流容器。", diff --git a/frontend/src/locales/zh_TW/common.json b/frontend/src/locales/zh_TW/common.json index 8e42226eb..a45ca3065 100644 --- a/frontend/src/locales/zh_TW/common.json +++ b/frontend/src/locales/zh_TW/common.json @@ -194,6 +194,7 @@ "virtual-collections": "自動生成的收藏庫", "visibility": "可見性", "warning": "警告:", + "websocket-unreachable-retrying": "WebSocket 連線不可用,正在重試…", "whats-new": "查看更新內容", "zoom-in": "放大", "zoom-out": "縮小" diff --git a/frontend/src/locales/zh_TW/notifications.json b/frontend/src/locales/zh_TW/notifications.json index eccb7d7e4..5312b547b 100644 --- a/frontend/src/locales/zh_TW/notifications.json +++ b/frontend/src/locales/zh_TW/notifications.json @@ -2,6 +2,7 @@ "channel-add": "新增管道", "channel-address": "電子郵件地址", "channel-address-hint": "我們會寄送驗證碼以確認該地址屬於你", + "channel-advanced": "進階選項", "channel-awaiting-code": "輸入郵件中的驗證碼,即可開始在這裡接收通知", "channel-code": "驗證碼", "channel-code-sent": "我們已寄送驗證碼至 {address}", @@ -15,10 +16,16 @@ "channel-edit": "編輯管道", "channel-email-unavailable": "此伺服器未設定電子郵件", "channel-enabled": "將通知傳送到這裡", - "channel-format": "格式", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-botname": "機器人名稱", + "channel-field-host": "主機", + "channel-field-list-hint": "每輸入一項後按 Enter", + "channel-field-number": "必須是 {min} 到 {max} 之間的數字", + "channel-field-path": "路徑", + "channel-field-port": "連接埠", + "channel-field-schema": "通訊協定", + "channel-field-targets": "目標", + "channel-field-token": "權杖", + "channel-field-verify": "驗證 SSL 憑證", "channel-last-error": "最近的錯誤:{error}", "channel-last-sent": "最近傳送:{when}", "channel-level-error": "僅錯誤", @@ -27,14 +34,23 @@ "channel-min-level": "傳送", "channel-name": "名稱", "channel-new": "新增管道", + "channel-paste-failed": "無法讀取此 URL", + "channel-paste-filled": "已從 URL 讀取:{fields}", + "channel-paste-other-service": "此 URL 屬於 {service}", + "channel-paste-url": "貼上 URL", + "channel-paste-url-hint": "Apprise URL 會填入各欄位", "channel-resend": "寄送新驗證碼", "channel-resend-failed": "無法寄送新驗證碼", "channel-save-failed": "無法儲存管道", "channel-saved": "管道已儲存", - "channel-secret-json": "簽章密鑰(選填)", + "channel-search-services": "搜尋服務", + "channel-secret": "簽章密鑰(選填)", "channel-secret-keep": "留空以保留目前的值", - "channel-secret-ntfy": "存取權杖(選填)", "channel-secret-remove": "移除", + "channel-service-url": "{service} URL", + "channel-service-url-hint": "{service} 提供的 URL,或 Apprise URL", + "channel-services-failed": "無法載入 Apprise 服務", + "channel-setup-guide": "如何設定 {service}", "channel-test": "傳送測試", "channel-test-failed": "測試失敗:{error}", "channel-test-ok": "測試已傳送", @@ -42,14 +58,14 @@ "channel-topics-all": "所有主題", "channel-type": "類型", "channel-type-email": "電子郵件", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM Webhook(JSON)", "channel-update-failed": "無法更新管道", "channel-url": "URL", "channel-url-invalid": "必須以 http:// 或 https:// 開頭", "channel-url-keep": "留空以保留目前的 URL", "channels": "管道", "channels-empty": "尚無管道", - "channels-empty-hint": "將你的通知轉發到 Discord、ntfy、電子郵件或任何 Webhook。", + "channels-empty-hint": "將你的通知轉發到 RomM 之外:Webhook、電子郵件地址等。", "channels-load-failed": "無法載入你的管道", "dismiss-all": "全部關閉", "dismiss-all-body": "所有通知都將被移除。", diff --git a/frontend/src/locales/zh_TW/play.json b/frontend/src/locales/zh_TW/play.json index c85dfca2c..1acd89850 100644 --- a/frontend/src/locales/zh_TW/play.json +++ b/frontend/src/locales/zh_TW/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "此容器上正在執行 {rom}。請先結束該工作階段。", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -57,6 +58,7 @@ "full-screen": "全螢幕", "hide-older-versions": "隱藏舊版本", "https-required": "必須透過 HTTPS 執行。請聯絡網站擁有者。", + "import-refusals-truncated": "還有 {count} 個問題未顯示 | 還有 {count} 個問題未顯示", "join-closed": "該工作階段不再對其他玩家開放。", "join-ended": "該工作階段已結束。", "jsdos-browser-save-warning": "js-dos 存檔僅保存在此瀏覽器中,不會與 RomM 同步。", @@ -215,6 +217,7 @@ "states-view-list": "List", "states-view-strip": "Row", "stream-error-generic": "發生意外錯誤。", + "stream-error-import-refused": "無法使用所選的存檔或即時存檔。", "stream-error-load-rom": "無法載入 ROM 詳細資訊。", "stream-error-not-configured": "未為 {platform} 設定串流容器。", "stream-error-rom-not-found": "找不到此 ROM。它可能已被移除。", @@ -225,7 +228,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "靜音", "stream-occupied-body": "{rom} 自 {time} 起一直在遊玩。", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "上一個工作階段仍在關閉中。請稍後再試。", "stream-occupied-fallback": "目前有其他人正在遊玩。請稍後再試。", "stream-occupied-title": "工作階段使用中", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/zh_TW/scan.json b/frontend/src/locales/zh_TW/scan.json index ba949a16a..10f33a244 100644 --- a/frontend/src/locales/zh_TW/scan.json +++ b/frontend/src/locales/zh_TW/scan.json @@ -33,7 +33,7 @@ "info-full-docs": "完整文件", "info-hashes-desc": "為選定平台中的所有文件重新計算雜湊值。", "info-new-platforms-desc": "僅尋找尚未在 RomM 中的平台。", - "info-quick-scan-desc": "掃描尚未在遊戲庫中的遊戲,並識別已在遊戲庫中的遊戲資料夾內任意層級新增的檔案。", + "info-quick-scan-desc": "掃描尚未在遊戲庫中的遊戲,識別已在遊戲庫中的遊戲資料夾內任意層級新增的檔案,並重新讀取遊戲庫中已有遊戲的標題 ID。", "info-unmatched-games-desc": "嘗試匹配與所選元數據來源未匹配的遊戲。\n\n例如,選擇 IGDB 和 ScreenScraper 將掃描與 IGDB 或 ScreenScraper 未匹配的遊戲。", "info-update-metadata-desc": "使用外部 ID(如 IGDB ID)為已與所選元數據來源匹配的遊戲更新元數據。\n\n例如,選擇 IGDB 和 ScreenScraper 將為與 IGDB 或 ScreenScraper 匹配的遊戲更新元數據,並使用 igdb_id 和/或 ssfr_id 從相應提供者重新獲取元數據。", "live-progress": "即時進度", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index 9fa68eed6..3cdacf352 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "正在關閉上一個工作階段", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/services/api/notificationChannel.ts b/frontend/src/services/api/notificationChannel.ts index ef8f412d4..665511823 100644 --- a/frontend/src/services/api/notificationChannel.ts +++ b/frontend/src/services/api/notificationChannel.ts @@ -1,4 +1,7 @@ import type { + AppriseChannelCreatePayload, + AppriseServiceSchema, + AppriseUrlFieldsSchema, EmailChannelCreatePayload, NotificationChannelSchema, NotificationChannelTestResult, @@ -7,13 +10,29 @@ import type { } from "@/__generated__"; import api from "@/services/api"; +export type NotificationChannelCreatePayload = + | AppriseChannelCreatePayload + | WebhookChannelCreatePayload + | EmailChannelCreatePayload; + async function getChannels() { return api.get("/notification-channels"); } -async function create( - payload: WebhookChannelCreatePayload | EmailChannelCreatePayload, -) { +async function getAppriseServices() { + return api.get( + "/notification-channels/apprise-services", + ); +} + +async function parseAppriseUrl(url: string) { + return api.post( + "/notification-channels/apprise-services/parse", + { url }, + ); +} + +async function create(payload: NotificationChannelCreatePayload) { return api.post("/notification-channels", payload); } @@ -47,6 +66,8 @@ async function resendCode(id: number) { export default { getChannels, + getAppriseServices, + parseAppriseUrl, create, update, remove, diff --git a/frontend/src/services/api/streaming.test.ts b/frontend/src/services/api/streaming.test.ts new file mode 100644 index 000000000..ced0361bd --- /dev/null +++ b/frontend/src/services/api/streaming.test.ts @@ -0,0 +1,99 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import streamingApi from "@/services/api/streaming"; + +const post = vi.hoisted(() => vi.fn()); + +vi.mock("@/services/api", () => ({ + default: { post }, + keepaliveHeaders: () => ({}), +})); + +describe("releaseSessionKeepalive", () => { + const fetchMock = vi.fn().mockResolvedValue(new Response()); + + beforeEach(() => { + vi.stubGlobal("fetch", fetchMock); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + fetchMock.mockClear(); + }); + + it("names the container and the claim where URLSearchParams has no size", async () => { + // Chrome 111-112 and Safari 16.4 are in .browserslistrc and predate it. + vi.spyOn(URLSearchParams.prototype, "size", "get").mockReturnValue( + undefined as unknown as number, + ); + + await streamingApi.releaseSessionKeepalive( + "ps2", + "WEBSTATION-DEV", + "2026-09-17T12:00:00+00:00", + ); + + expect(fetchMock.mock.calls[0][0]).toBe( + "/api/streaming/sessions/ps2?container=WEBSTATION-DEV&claimed_at=2026-09-17T12%3A00%3A00%2B00%3A00", + ); + }); + + it("sends no query when there is nothing to name", async () => { + await streamingApi.releaseSessionKeepalive("ps2"); + + expect(fetchMock.mock.calls[0][0]).toBe("/api/streaming/sessions/ps2"); + }); +}); + +describe("saveAndExitKeepalive", () => { + const fetchMock = vi.fn().mockResolvedValue(new Response()); + + beforeEach(() => { + vi.stubGlobal("fetch", fetchMock); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + fetchMock.mockClear(); + }); + + it("names the container and the claim it saves", async () => { + await streamingApi.saveAndExitKeepalive( + "ps2", + 0, + "WEBSTATION-DEV", + "2026-09-17T12:00:00+00:00", + ); + + expect(fetchMock.mock.calls[0][0]).toBe( + "/api/streaming/sessions/ps2/save-and-exit?container=WEBSTATION-DEV&claimed_at=2026-09-17T12%3A00%3A00%2B00%3A00", + ); + }); +}); + +describe("saveAndExit", () => { + beforeEach(() => { + post.mockReset(); + }); + + it("names the container and the claim it saves", async () => { + await streamingApi.saveAndExit( + "ps2", + 0, + true, + "WEBSTATION-DEV", + "2026-09-17T12:00:00+00:00", + ); + + expect(post).toHaveBeenCalledWith( + "/streaming/sessions/ps2/save-and-exit", + { slot: 0, wait: true }, + { + params: { + container: "WEBSTATION-DEV", + claimed_at: "2026-09-17T12:00:00+00:00", + }, + }, + ); + }); +}); diff --git a/frontend/src/services/api/streaming.ts b/frontend/src/services/api/streaming.ts index 644cd34e4..bbed3767a 100644 --- a/frontend/src/services/api/streaming.ts +++ b/frontend/src/services/api/streaming.ts @@ -1,16 +1,31 @@ import type { AdminContainerSchema, + AdminContainersResponse, AdminSessionSchema, + AdminSessionsResponse, + ClaimStreamingSessionRequest, + ContainerBusyDetail, LaunchingSessionSchema, DesktopSessionSchema, JoinableSessionSchema, + JoinableSessionsResponse, JoinedSessionSchema, + LaunchFailedPayload, + LaunchPhasePayload, + LaunchReadyPayload, + LoadStateResponse, MemoryCardImportRequired, + MuteResponse, + ReleaseSessionResponse, + SaveAndExitResponse, + SaveStateResponse, SessionStatusSchema, SessionTerminationSchema, SlotCapabilitiesSchema, StreamingConfigSchema, StreamingContainerSchema, + SwapDiscResponse, + VolumeResponse, } from "@/__generated__"; import api, { keepaliveHeaders } from "@/services/api"; @@ -26,34 +41,12 @@ export type StreamingContainer = StreamingContainerSchema; export type StreamingConfig = StreamingConfigSchema; export type LaunchingSession = LaunchingSessionSchema; -// The launch's own result arrives on the socket, and socket payloads reach no -// route so they are not in the OpenAPI schema (constitution SS X.10, backend -// debt). The backend builds each of these from a model of the same name in -// endpoints/responses/streaming.py, so the shapes stay tied. +// Socket payloads reach no route, so the backend publishes them into the +// schema by hand (utils/openapi.py). +export type LaunchReady = LaunchReadyPayload; +export type LaunchFailed = LaunchFailedPayload; +export type LaunchPhase = LaunchPhasePayload; -/** `streaming:launch-ready`: the game is up, and `host` is the iframe URL. */ -export interface LaunchReady { - platform: string; - container: string; - host: string; - /** null when no resume was asked for; false means the state could not be - * pushed and the session started fresh. */ - resume: boolean | null; -} - -/** `streaming:launch-failed`. The claim is already released. */ -export interface LaunchFailed { - platform: string; - container: string; - detail: string; -} - -/** `streaming:launch-phase`, while a broker unpacks a large title. */ -export interface LaunchPhase { - platform: string; - container: string; - phase: string | null; -} export type AdminStreamingSession = AdminSessionSchema; export type AdminStreamingContainer = AdminContainerSchema; export type DesktopSession = DesktopSessionSchema; @@ -68,7 +61,9 @@ export type MemoryCardImportDetail = MemoryCardImportRequired; /** The answer to that prompt, replayed on the retried claim. "discard" erases * the card currently on the container. */ -export type MemoryCardImport = "adopt" | "discard"; +export type MemoryCardImport = NonNullable< + ClaimStreamingSessionRequest["card_import"] +>; export function isMemoryCardImportDetail( value: unknown, @@ -80,6 +75,20 @@ export function isMemoryCardImportDetail( ); } +/** Body of the 409 a claim returns when the container is taken. */ +export type { ContainerBusyDetail }; + +/** The query naming a claim by its container and the stamp it was taken at. */ +function claimParams( + container?: string | null, + claimedAt?: string | null, +): { container?: string; claimed_at?: string } { + return { + ...(container != null ? { container } : {}), + ...(claimedAt != null ? { claimed_at: claimedAt } : {}), + }; +} + // ── Requests ────────────────────────────────────────────────────────────────── async function fetchConfig() { @@ -112,17 +121,18 @@ async function claimSession( async function releaseSession( platform: string, reason?: string, - container?: string, + container?: string | null, save?: boolean, + claimedAt?: string | null, ) { - return api.delete(`/streaming/sessions/${platform}`, { + return api.delete(`/streaming/sessions/${platform}`, { params: { + // The holder names its container and stamp so a taken-over tab cannot end + // the claim that replaced it. An admin names its pick and no stamp. + ...claimParams(container, claimedAt), // Sent whenever the caller supplied one, empty string included: the // backend treats the param's presence as "this is an admin force-release". ...(reason !== undefined ? { reason } : {}), - // Names which container to release, needed when a pool serves the - // platform and the admin is ending a session they do not own. - ...(container !== undefined ? { container } : {}), // Only the player who deliberately stopped without saving sends this. // Everything else leaves it off so the backend still autosaves. ...(save === false ? { save: false } : {}), @@ -131,9 +141,7 @@ async function releaseSession( } async function listJoinableSessions() { - return api.get<{ sessions: JoinableSession[] }>( - "/streaming/sessions/joinable", - ); + return api.get("/streaming/sessions/joinable"); } async function joinSession(platform: string, container?: string) { @@ -144,61 +152,111 @@ async function joinSession(platform: string, container?: string) { ); } -async function saveAndExit(platform: string, slot = 0, wait = true) { - return api.post(`/streaming/sessions/${platform}/save-and-exit`, { - slot, - wait, - }); +async function saveAndExit( + platform: string, + slot = 0, + wait = true, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( + `/streaming/sessions/${platform}/save-and-exit`, + { slot, wait }, + { params: claimParams(container, claimedAt) }, + ); } -async function heartbeatSession(platform: string, container?: string) { +async function heartbeatSession( + platform: string, + container?: string | null, + claimedAt?: string | null, +) { return api.post( `/streaming/sessions/${platform}/heartbeat`, undefined, - { params: { container } }, + { params: claimParams(container, claimedAt) }, ); } -async function sessionStatus(platform: string) { - return api.get(`/streaming/sessions/${platform}/status`); -} - -async function setVolume(platform: string, level: number) { - return api.post(`/streaming/sessions/${platform}/volume`, { - level: Math.round(level), +async function sessionStatus(platform: string, claimedAt?: string | null) { + return api.get(`/streaming/sessions/${platform}/status`, { + params: { claimed_at: claimedAt }, }); } -async function setMute(platform: string, mute?: boolean) { - return api.post( +async function setVolume( + platform: string, + level: number, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( + `/streaming/sessions/${platform}/volume`, + { level: Math.round(level) }, + { params: claimParams(container, claimedAt) }, + ); +} + +async function setMute( + platform: string, + mute?: boolean, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( `/streaming/sessions/${platform}/mute`, mute !== undefined ? { mute } : {}, + { params: claimParams(container, claimedAt) }, ); } -async function saveState(platform: string, slot = 1) { - return api.post(`/streaming/sessions/${platform}/save-state`, { slot }); +async function saveState( + platform: string, + slot = 1, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( + `/streaming/sessions/${platform}/save-state`, + { slot }, + { params: claimParams(container, claimedAt) }, + ); } -async function loadState(platform: string, slot = 1) { - return api.post(`/streaming/sessions/${platform}/load-state`, { slot }); +async function loadState( + platform: string, + slot = 1, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( + `/streaming/sessions/${platform}/load-state`, + { slot }, + { params: claimParams(container, claimedAt) }, + ); } -async function swapDisc(platform: string, fileId: number) { - return api.post(`/streaming/sessions/${platform}/swap-disc`, { - file_id: fileId, - }); +async function swapDisc( + platform: string, + fileId: number, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( + `/streaming/sessions/${platform}/swap-disc`, + { file_id: fileId }, + { params: claimParams(container, claimedAt) }, + ); } async function adminListSessions() { - return api.get<{ sessions: AdminStreamingSession[] }>("/streaming/sessions"); + return api.get("/streaming/sessions"); } async function adminListContainers() { - return api.get<{ enabled: boolean; containers: AdminStreamingContainer[] }>( - "/streaming/containers", - { headers: { "Cache-Control": "no-cache" } }, - ); + return api.get("/streaming/containers", { + headers: { "Cache-Control": "no-cache" }, + }); } async function claimDesktop(container: string) { @@ -211,8 +269,28 @@ async function claimDesktop(container: string) { // sendBeacon cannot carry the CSRF header, so the cookie-sourced header is // set by hand (mirrors the axios interceptor). -function saveAndExitKeepalive(platform: string, slot = 0): Promise { - return fetch(`/api/streaming/sessions/${platform}/save-and-exit`, { +// Names which container and which claim, so an unload cannot end the claim +// that replaced it. +function claimQuery( + container?: string | null, + claimedAt?: string | null, +): string { + const search = new URLSearchParams( + Object.entries(claimParams(container, claimedAt)).filter( + ([, value]) => value, + ), + ).toString(); + return search ? `?${search}` : ""; +} + +function saveAndExitKeepalive( + platform: string, + slot = 0, + container?: string | null, + claimedAt?: string | null, +): Promise { + const query = claimQuery(container, claimedAt); + return fetch(`/api/streaming/sessions/${platform}/save-and-exit${query}`, { method: "POST", keepalive: true, credentials: "same-origin", @@ -223,10 +301,10 @@ function saveAndExitKeepalive(platform: string, slot = 0): Promise { function releaseSessionKeepalive( platform: string, - container?: string, + container?: string | null, + claimedAt?: string | null, ): Promise { - // Names which container to release, for the platforms a pool serves. - const query = container ? `?container=${encodeURIComponent(container)}` : ""; + const query = claimQuery(container, claimedAt); return fetch(`/api/streaming/sessions/${platform}${query}`, { method: "DELETE", keepalive: true, diff --git a/frontend/src/stores/soundtrackPlayer.test.ts b/frontend/src/stores/soundtrackPlayer.test.ts index 390e5fd64..d7134447f 100644 --- a/frontend/src/stores/soundtrackPlayer.test.ts +++ b/frontend/src/stores/soundtrackPlayer.test.ts @@ -85,6 +85,19 @@ describe("resolveSoundtrackGameArtwork", () => { ).toBe("small.png"); expect(resolveSoundtrackGameArtwork(makeRom())).toBeUndefined(); }); + + it("treats the backend's empty cover paths as missing", () => { + expect( + resolveSoundtrackGameArtwork( + makeRom({ path_cover_large: "", path_cover_small: "", url_cover: "" }), + ), + ).toBeUndefined(); + expect( + resolveSoundtrackGameArtwork( + makeRom({ path_cover_large: "", path_cover_small: "small.png" }), + ), + ).toBe("small.png"); + }); }); describe("loadPlaylist with preserved shuffle", () => { diff --git a/frontend/src/stores/soundtrackPlayer.ts b/frontend/src/stores/soundtrackPlayer.ts index bd90380fb..0f6c48504 100644 --- a/frontend/src/stores/soundtrackPlayer.ts +++ b/frontend/src/stores/soundtrackPlayer.ts @@ -72,8 +72,9 @@ export function resolveSoundtrackGameArtwork( const logoPath = rom.ss_metadata?.logo_path; if (logoPath) return `${FRONTEND_RESOURCES_PATH}/${logoPath}`; + // The backend sends "" rather than null for a ROM without a cover. return ( - rom.path_cover_large ?? rom.path_cover_small ?? rom.url_cover ?? undefined + rom.path_cover_large || rom.path_cover_small || rom.url_cover || undefined ); } diff --git a/frontend/src/stores/streaming.test.ts b/frontend/src/stores/streaming.test.ts index 521593193..b4b2cbaa2 100644 --- a/frontend/src/stores/streaming.test.ts +++ b/frontend/src/stores/streaming.test.ts @@ -4,7 +4,11 @@ import streamingApi, { type JoinableSession } from "@/services/api/streaming"; import { useStreamingStore } from "@/stores/streaming"; vi.mock("@/services/api/streaming", () => ({ - default: { listJoinableSessions: vi.fn() }, + default: { + listJoinableSessions: vi.fn(), + saveAndExit: vi.fn(), + saveAndExitKeepalive: vi.fn(), + }, })); describe("platformCapabilities disc flags", () => { @@ -14,6 +18,7 @@ describe("platformCapabilities disc flags", () => { const store = useStreamingStore(); store.config = { enabled: true, + emulator_labels: {}, containers: [ { platform: "dc", @@ -22,6 +27,8 @@ describe("platformCapabilities disc flags", () => { emulator: "retroarch", supports_memory_cards: false, supports_save_picker: false, + supports_live_states: true, + import_kinds: [], capabilities: { max_slots: 0, has_autosave: true, @@ -43,6 +50,41 @@ describe("platformCapabilities disc flags", () => { }); }); +describe("emulator labels", () => { + beforeEach(() => setActivePinia(createPinia())); + + it("names an emulator by the label the backend ships", () => { + const store = useStreamingStore(); + store.config = { + enabled: true, + containers: [], + emulator_labels: { play: "Play!" }, + }; + expect(store.emulatorLabel("play")).toBe("Play!"); + }); + + it("names an emulator configured in another case", () => { + const store = useStreamingStore(); + store.config = { + enabled: true, + containers: [], + emulator_labels: { play: "Play!" }, + }; + expect(store.emulatorLabel("Play")).toBe("Play!"); + }); + + it("falls back to the id for an emulator it was told nothing about", () => { + const store = useStreamingStore(); + expect(store.emulatorLabel("snes9x")).toBe("snes9x"); + }); + + it("falls back to the id for one named like an object's own members", () => { + const store = useStreamingStore(); + expect(store.emulatorLabel("constructor")).toBe("constructor"); + expect(store.emulatorLabel("__proto__")).toBe("__proto__"); + }); +}); + describe("joinable sessions", () => { const listJoinableSessions = streamingApi.listJoinableSessions as unknown as Mock; @@ -116,3 +158,53 @@ describe("joinable sessions", () => { expect(store.joinableForRom(7)?.host_username).toBe("ana"); }); }); + +describe("save-and-exit", () => { + const saveAndExit = streamingApi.saveAndExit as unknown as Mock; + const saveAndExitKeepalive = + streamingApi.saveAndExitKeepalive as unknown as Mock; + + beforeEach(() => { + setActivePinia(createPinia()); + saveAndExit.mockReset(); + saveAndExitKeepalive.mockReset(); + }); + + it("names the claim it saves", async () => { + saveAndExit.mockResolvedValue({ data: { released: true, saved: true } }); + + await useStreamingStore().saveAndExit( + "ps2", + 0, + false, + "ps2-1", + "2026-01-01T00:00:00Z", + ); + + expect(saveAndExit).toHaveBeenCalledWith( + "ps2", + 0, + false, + "ps2-1", + "2026-01-01T00:00:00Z", + ); + }); + + it("names the claim it saves on unload", () => { + saveAndExitKeepalive.mockResolvedValue(new Response()); + + useStreamingStore().saveAndExitKeepalive( + "ps2", + 0, + "ps2-1", + "2026-01-01T00:00:00Z", + ); + + expect(saveAndExitKeepalive).toHaveBeenCalledWith( + "ps2", + 0, + "ps2-1", + "2026-01-01T00:00:00Z", + ); + }); +}); diff --git a/frontend/src/stores/streaming.ts b/frontend/src/stores/streaming.ts index 4ad1cdf7f..bceafd032 100644 --- a/frontend/src/stores/streaming.ts +++ b/frontend/src/stores/streaming.ts @@ -10,6 +10,7 @@ import type { StreamingConfig, StreamingContainer, } from "@/services/api/streaming"; +import { emulatorLabelFrom } from "@/v2/utils/assets"; export type { LaunchingSession, @@ -39,6 +40,7 @@ export const useStreamingStore = defineStore("streaming", () => { const config = ref({ enabled: false, containers: [], + emulator_labels: {}, }); const launchingSession = ref(null); const loading = ref(false); @@ -79,6 +81,11 @@ export const useStreamingStore = defineStore("streaming", () => { return container.label || container.emulator || null; } + /** The backend's display name for an emulator id, else the id as it stands. */ + function emulatorLabel(emulator: string | null | undefined): string { + return emulatorLabelFrom(config.value.emulator_labels, emulator); + } + /** * Returns per-platform save-state capabilities for the streaming player UI, * sourced from the container config the backend ships in /config (the single @@ -121,6 +128,7 @@ export const useStreamingStore = defineStore("streaming", () => { config.value = { enabled: data.enabled ?? false, containers: data.containers ?? [], + emulator_labels: data.emulator_labels ?? {}, }; } catch (err) { error.value = String(err); @@ -252,10 +260,18 @@ export const useStreamingStore = defineStore("streaming", () => { async function releaseSession( platform: string, save = true, + container?: string | null, + claimedAt?: string | null, ): Promise { if (!platform) return false; try { - await streamingApi.releaseSession(platform, undefined, undefined, save); + await streamingApi.releaseSession( + platform, + undefined, + container, + save, + claimedAt, + ); launchingSession.value = null; return true; } catch (err) { @@ -278,10 +294,18 @@ export const useStreamingStore = defineStore("streaming", () => { platform: string, slot = 0, wait = true, + container?: string | null, + claimedAt?: string | null, ): Promise<{ released: boolean; saved: boolean }> { if (!platform) return { released: false, saved: false }; try { - const { data } = await streamingApi.saveAndExit(platform, slot, wait); + const { data } = await streamingApi.saveAndExit( + platform, + slot, + wait, + container, + claimedAt, + ); const released = data.released ?? true; if (released) launchingSession.value = null; return { released, saved: data.saved ?? false }; @@ -302,11 +326,16 @@ export const useStreamingStore = defineStore("streaming", () => { */ async function heartbeatSession( platform: string, - container?: string, + container?: string | null, + claimedAt?: string | null, ): Promise { if (!platform) return null; try { - const { data } = await streamingApi.heartbeatSession(platform, container); + const { data } = await streamingApi.heartbeatSession( + platform, + container, + claimedAt, + ); return data; } catch (err) { console.warn("[streaming] Could not heartbeat session:", err); @@ -321,10 +350,11 @@ export const useStreamingStore = defineStore("streaming", () => { */ async function fetchSessionStatus( platform: string, + claimedAt?: string, ): Promise { if (!platform) return null; try { - const { data } = await streamingApi.sessionStatus(platform); + const { data } = await streamingApi.sessionStatus(platform, claimedAt); return data; } catch (err) { console.warn("[streaming] Could not fetch session status:", err); @@ -338,26 +368,39 @@ export const useStreamingStore = defineStore("streaming", () => { * is gone (wait=false; the backend forces a blocking save for card-sync * containers anyway). Best-effort, never throws. */ - function saveAndExitKeepalive(platform: string, slot = 0): void { + function saveAndExitKeepalive( + platform: string, + slot = 0, + container?: string | null, + claimedAt?: string | null, + ): void { if (!platform) return; launchingSession.value = null; // The caller is unloading and cannot await, so the rejection is caught on // the promise itself; try/catch here would only see a synchronous throw. - streamingApi.saveAndExitKeepalive(platform, slot).catch((err) => { - console.warn("[streaming] Could not save-and-exit (keepalive):", err); - }); + streamingApi + .saveAndExitKeepalive(platform, slot, container, claimedAt) + .catch((err) => { + console.warn("[streaming] Could not save-and-exit (keepalive):", err); + }); } /** * releaseSession for the pagehide path. Fire-and-forget via fetch * keepalive. Best-effort, never throws. */ - function releaseSessionKeepalive(platform: string): void { + function releaseSessionKeepalive( + platform: string, + container?: string | null, + claimedAt?: string | null, + ): void { if (!platform) return; launchingSession.value = null; - streamingApi.releaseSessionKeepalive(platform).catch((err) => { - console.warn("[streaming] Could not release session (keepalive):", err); - }); + streamingApi + .releaseSessionKeepalive(platform, container, claimedAt) + .catch((err) => { + console.warn("[streaming] Could not release session (keepalive):", err); + }); } return { @@ -369,6 +412,7 @@ export const useStreamingStore = defineStore("streaming", () => { isEnabled, containerForPlatform, containerLabelForPlatform, + emulatorLabel, platformCapabilities, fetchConfig, claimSession, diff --git a/frontend/src/test-utils/serverError.ts b/frontend/src/test-utils/serverError.ts index 00bef7986..f7c09812e 100644 --- a/frontend/src/test-utils/serverError.ts +++ b/frontend/src/test-utils/serverError.ts @@ -1,7 +1,7 @@ import { AxiosError } from "axios"; /** A refused request as axios rejects it, carrying FastAPI's `detail`. */ -export function serverError(detail: string, status = 503): AxiosError { +export function serverError(detail: unknown, status = 503): AxiosError { return Object.assign(new AxiosError(`HTTP ${status}`), { response: { status, data: { detail } }, }); diff --git a/frontend/src/test-utils/streamingStore.ts b/frontend/src/test-utils/streamingStore.ts new file mode 100644 index 000000000..222bee905 --- /dev/null +++ b/frontend/src/test-utils/streamingStore.ts @@ -0,0 +1,14 @@ +import { emulatorLabelFrom } from "@/v2/utils/assets"; + +// Stands in for `@/stores/streaming` via `vi.mock(path, () => import(...))`. +const EMULATOR_LABELS: Record = { + play: "Play!", + retroarch: "RetroArch", +}; + +export function useStreamingStore() { + return { + emulatorLabel: (id: string | null | undefined) => + emulatorLabelFrom(EMULATOR_LABELS, id), + }; +} diff --git a/frontend/src/v2/components/AppShell/BackendStatusBanner.stories.ts b/frontend/src/v2/components/AppShell/BackendStatusBanner.stories.ts new file mode 100644 index 000000000..755ec5303 --- /dev/null +++ b/frontend/src/v2/components/AppShell/BackendStatusBanner.stories.ts @@ -0,0 +1,77 @@ +import type { Meta, StoryObj } from "@storybook/vue3-vite"; +import { createPinia, setActivePinia } from "pinia"; +import { provide, ref } from "vue"; +import BackendStatusBanner from "./BackendStatusBanner.vue"; +import { + backendStatusBannerStoryKey, + type BackendStatusBannerStoryState, +} from "./backendStatusBannerStoryKey"; + +function storyDecorator(state: BackendStatusBannerStoryState) { + return () => ({ + setup() { + provide(backendStatusBannerStoryKey, state); + return {}; + }, + template: "", + }); +} + +const meta: Meta = { + title: "AppShell/BackendStatusBanner", + component: BackendStatusBanner, + decorators: [ + () => { + setActivePinia(createPinia()); + return { template: "" }; + }, + ], +}; + +export default meta; +type Story = StoryObj; + +export const Healthy: Story = { + decorators: [ + storyDecorator({ + isOffline: ref(false), + isWebSocketDegraded: ref(false), + retryNow: () => {}, + retryWebSocket: () => {}, + }), + ], + render: () => ({ + components: { BackendStatusBanner }, + template: "", + }), +}; + +export const ServerOffline: Story = { + decorators: [ + storyDecorator({ + isOffline: ref(true), + isWebSocketDegraded: ref(false), + retryNow: () => {}, + retryWebSocket: () => {}, + }), + ], + render: () => ({ + components: { BackendStatusBanner }, + template: "", + }), +}; + +export const WebSocketDegraded: Story = { + decorators: [ + storyDecorator({ + isOffline: ref(false), + isWebSocketDegraded: ref(true), + retryNow: () => {}, + retryWebSocket: () => {}, + }), + ], + render: () => ({ + components: { BackendStatusBanner }, + template: "", + }), +}; diff --git a/frontend/src/v2/components/AppShell/BackendStatusBanner.test.ts b/frontend/src/v2/components/AppShell/BackendStatusBanner.test.ts index 42ee2193a..7fa9eabdc 100644 --- a/frontend/src/v2/components/AppShell/BackendStatusBanner.test.ts +++ b/frontend/src/v2/components/AppShell/BackendStatusBanner.test.ts @@ -10,8 +10,16 @@ vi.mock("vue-i18n", () => ({ })); const isOffline = ref(false); +const isWebSocketDegraded = ref(false); +const retryNow = vi.fn(); +const retryWebSocket = vi.fn(); + vi.mock("@/v2/composables/useServerConnection", () => ({ - useServerConnection: () => ({ isOffline, retryNow: vi.fn() }), + useServerConnection: () => ({ isOffline, retryNow }), +})); + +vi.mock("@/v2/composables/useSocketTransportHealth", () => ({ + useSocketTransportHealth: () => ({ isWebSocketDegraded, retryWebSocket }), })); vi.mock("@v2/lib", () => ({ @@ -39,6 +47,9 @@ describe("BackendStatusBanner", () => { setActivePinia(createPinia()); vi.useFakeTimers(); isOffline.value = false; + isWebSocketDegraded.value = false; + retryNow.mockClear(); + retryWebSocket.mockClear(); }); afterEach(() => { @@ -53,6 +64,37 @@ describe("BackendStatusBanner", () => { expect(banner().exists()).toBe(false); }); + it("shows the websocket message when HTTP is up but transport is degraded", async () => { + isWebSocketDegraded.value = true; + + await render(); + + expect(banner().exists()).toBe(true); + expect(wrapper!.text()).toContain("common.websocket-unreachable-retrying"); + }); + + it("prefers the offline message when both HTTP and websocket are down", async () => { + isOffline.value = true; + isWebSocketDegraded.value = true; + + await render(); + + expect(wrapper!.text()).toContain("common.server-offline-retrying"); + expect(wrapper!.text()).not.toContain( + "common.websocket-unreachable-retrying", + ); + }); + + it("retries the websocket when the degraded banner retry is clicked", async () => { + isWebSocketDegraded.value = true; + + await render(); + await wrapper!.find(".r-backend-banner__retry").trigger("click"); + + expect(retryWebSocket).toHaveBeenCalledOnce(); + expect(retryNow).not.toHaveBeenCalled(); + }); + it("offers the retry button outside a game", async () => { isOffline.value = true; diff --git a/frontend/src/v2/components/AppShell/BackendStatusBanner.vue b/frontend/src/v2/components/AppShell/BackendStatusBanner.vue index 9376bf3c2..4bf0778c4 100644 --- a/frontend/src/v2/components/AppShell/BackendStatusBanner.vue +++ b/frontend/src/v2/components/AppShell/BackendStatusBanner.vue @@ -11,12 +11,18 @@ // poll / passive DOM-event listeners / recovery watcher (idempotent). This // component is mounted once, under `v-if="isV2"` in RomM.vue, so it covers both // the auth and main shells. +// +// When HTTP is up but Socket.IO fell back to polling, `useSocketTransportHealth` +// drives a second message (offline still wins if both are bad). import { RBtn, RIcon, RTooltip } from "@v2/lib"; import { storeToRefs } from "pinia"; +import { computed, inject } from "vue"; import { useI18n } from "vue-i18n"; import storePlaying from "@/stores/playing"; +import { backendStatusBannerStoryKey } from "@/v2/components/AppShell/backendStatusBannerStoryKey"; import { useDelayedFlag } from "@/v2/composables/useDelayedFlag"; import { useServerConnection } from "@/v2/composables/useServerConnection"; +import { useSocketTransportHealth } from "@/v2/composables/useSocketTransportHealth"; defineOptions({ inheritAttrs: false }); @@ -24,28 +30,63 @@ defineOptions({ inheritAttrs: false }); const COLLAPSE_MS = 6000; const { t } = useI18n(); -const { isOffline, retryNow } = useServerConnection(); +const storyState = inject(backendStatusBannerStoryKey, null); +const { isOffline, retryNow, isWebSocketDegraded, retryWebSocket } = (() => { + if (storyState) return storyState; + const server = useServerConnection(); + const transport = useSocketTransportHealth(); + return { + isOffline: server.isOffline, + retryNow: server.retryNow, + isWebSocketDegraded: transport.isWebSocketDegraded, + retryWebSocket: transport.retryWebSocket, + }; +})(); const { playing } = storeToRefs(storePlaying()); +const showWebsocketNotice = computed( + () => !isOffline.value && isWebSocketDegraded.value, +); + +const visible = computed(() => isOffline.value || showWebsocketNotice.value); + +const messageKey = computed(() => + showWebsocketNotice.value + ? "common.websocket-unreachable-retrying" + : "common.server-offline-retrying", +); + +const icon = computed(() => + showWebsocketNotice.value ? "mdi-web-sync" : "mdi-lan-disconnect", +); + // A notice that cannot be dismissed has no business sitting over a running // game, so it says its piece and then shrinks to its icon. const collapsed = useDelayedFlag( - () => isOffline.value && playing.value, + () => visible.value && playing.value, COLLAPSE_MS, ); + +function onRetry() { + if (showWebsocketNotice.value) { + retryWebSocket(); + } else { + void retryNow(); + } +} - - diff --git a/frontend/src/v2/components/AppShell/backendStatusBannerStoryKey.ts b/frontend/src/v2/components/AppShell/backendStatusBannerStoryKey.ts new file mode 100644 index 000000000..e475ff4d5 --- /dev/null +++ b/frontend/src/v2/components/AppShell/backendStatusBannerStoryKey.ts @@ -0,0 +1,12 @@ +import type { ComputedRef, InjectionKey, Ref } from "vue"; + +/** Storybook-only injection to avoid live heartbeat/socket installs in stories. */ +export interface BackendStatusBannerStoryState { + isOffline: Ref | ComputedRef; + isWebSocketDegraded: Ref | ComputedRef; + retryNow: () => void | Promise; + retryWebSocket: () => void; +} + +export const backendStatusBannerStoryKey: InjectionKey = + Symbol("backendStatusBannerStory"); diff --git a/frontend/src/v2/components/Auth/SetupStepPlatforms.vue b/frontend/src/v2/components/Auth/SetupStepPlatforms.vue index 0f4f3a2fc..ced3c6a8a 100644 --- a/frontend/src/v2/components/Auth/SetupStepPlatforms.vue +++ b/frontend/src/v2/components/Auth/SetupStepPlatforms.vue @@ -21,7 +21,6 @@ import { RCollapsible, REmptyState, RIcon, - RPlatformIcon, RSliderBtnGroup, RTag, RTextField, @@ -31,6 +30,7 @@ import { computed, ref } from "vue"; import { useI18n } from "vue-i18n"; import type { SetupLibraryInfo } from "@/services/api/setup"; import type { Platform } from "@/stores/platforms"; +import PlatformIcon from "@/v2/components/shared/PlatformIcon.vue"; defineOptions({ inheritAttrs: false }); @@ -392,7 +392,7 @@ const detectedPlatformCount = computed( class="r-setup-platforms__item" data-state="detected" > - togglePlatform(platform.fs_slug, v) " /> - togglePlatform(platform.fs_slug, v) " /> - ({ + useI18n: () => ({ t: (key: string) => key }), +})); + +// happy-dom has no ResizeObserver that fires, so the test lays the grid out. +const resize = vi.hoisted(() => ({ layout: () => {} })); +vi.mock("@vueuse/core", async (importOriginal) => ({ + ...(await importOriginal()), + useResizeObserver: (_target: unknown, callback: () => void) => { + resize.layout = callback; + }, +})); + +async function open() { + const emitter = mitt(); + const wrapper = mount(AboutDialog, { + global: { + provide: { emitter }, + stubs: { + RDialog: defineComponent({ + props: { modelValue: { type: Boolean, default: false } }, + template: `
`, + }), + }, + }, + }); + emitter.emit("showAboutDialog", null); + await nextTick(); + return wrapper; +} + +function size(wrapper: Awaited>, content: number) { + const value = wrapper.find(".r-v2-about__value").element; + Object.defineProperty(value, "scrollWidth", { + value: content, + configurable: true, + }); + Object.defineProperty(value, "clientWidth", { + value: 120, + configurable: true, + }); +} + +async function layOut( + wrapper: Awaited>, + content: number, +) { + size(wrapper, content); + resize.layout(); + await nextTick(); +} + +describe("AboutDialog", () => { + beforeEach(() => setActivePinia(createPinia())); + + // Ready before any hover, as RTooltip decides on the pointer's arrival. + it("shows a value cut off by its tile in a tooltip", async () => { + const wrapper = await open(); + + await layOut(wrapper, 480); + + expect(wrapper.findComponent(RTooltip).props("disabled")).toBe(false); + }); + + it("measures a value that changes without the grid resizing", async () => { + const wrapper = await open(); + await layOut(wrapper, 60); + + size(wrapper, 480); + const heartbeat = storeHeartbeat(); + heartbeat.value = { + ...heartbeat.value, + SYSTEM: { + ...heartbeat.value.SYSTEM, + VERSION: "development", + GIT_BRANCH: "claude/a-branch-name-too-long-for-its-tile", + }, + }; + await nextTick(); + + expect(wrapper.findComponent(RTooltip).props("disabled")).toBe(false); + }); + + it("keeps quiet about a value that fits", async () => { + const wrapper = await open(); + + await layOut(wrapper, 60); + + expect(wrapper.findComponent(RTooltip).props("disabled")).toBe(true); + }); +}); diff --git a/frontend/src/v2/components/Dialogs/AboutDialog.vue b/frontend/src/v2/components/Dialogs/AboutDialog.vue index 290c802f7..87822f534 100644 --- a/frontend/src/v2/components/Dialogs/AboutDialog.vue +++ b/frontend/src/v2/components/Dialogs/AboutDialog.vue @@ -2,9 +2,10 @@ // v2 AboutDialog — emitter-driven. Replaces the v1 AboutDialog in the v2 // GlobalDialogs stack so the "About" entry in UserMenu renders the v2 glass // panel instead of the legacy card. -import { RDialog, RIcon, RImg } from "@v2/lib"; +import { RDialog, RIcon, RImg, RTooltip } from "@v2/lib"; +import { useResizeObserver } from "@vueuse/core"; import type { Emitter } from "mitt"; -import { computed, inject, onBeforeUnmount, ref } from "vue"; +import { computed, inject, onBeforeUnmount, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; import type { Events } from "@/types/emitter"; import { useVersionDisplay } from "@/v2/composables/useVersionDisplay"; @@ -60,6 +61,21 @@ const links = computed(() => [ href: "https://discord.com/invite/P5HtHnhUDH", }, ]); + +// Which tiles cut their value off, and then show it in full. Measured whenever +// the grid lays out or a value changes, as RTooltip decides on the pointer's arrival. +const grid = ref(null); +const truncated = ref([]); + +function measure() { + truncated.value = Array.from( + grid.value?.querySelectorAll(".r-v2-about__value") ?? [], + (value) => value.scrollWidth > value.clientWidth, + ); +} + +useResizeObserver(grid, measure); +watch(() => links.value.map((link) => link.value), measure, { flush: "post" }); @@ -107,7 +128,9 @@ const links = computed(() => [ diff --git a/frontend/src/v2/components/Gallery/GameListRow.vue b/frontend/src/v2/components/Gallery/GameListRow.vue index 92af5a712..3e0a3f389 100644 --- a/frontend/src/v2/components/Gallery/GameListRow.vue +++ b/frontend/src/v2/components/Gallery/GameListRow.vue @@ -17,7 +17,6 @@ import { RChip, RIcon, RMarquee, - RPlatformIcon, RSkeletonBlock, RTooltip, } from "@v2/lib"; @@ -32,6 +31,7 @@ import ProviderBadges from "@/v2/components/Gallery/ProviderBadges.vue"; import GameActionBtn from "@/v2/components/GameActions/GameActionBtn.vue"; import GameCard from "@/v2/components/GameCard/GameCard.vue"; import SiblingBadge from "@/v2/components/GameCard/SiblingBadge.vue"; +import PlatformIcon from "@/v2/components/shared/PlatformIcon.vue"; import { useBackgroundArt } from "@/v2/composables/useBackgroundArt"; import { useBreakpoint } from "@/v2/composables/useBreakpoint"; import { useGallerySelectionInput } from "@/v2/composables/useGallerySelectionInput"; @@ -395,7 +395,7 @@ function onRowPointerDown(e: PointerEvent) {