mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 02:24:09 +01:00
* fix(sync): cap play sessions on sync completion and require roms.user.write The completion endpoint fed an unbounded play_sessions list to the same ingest as POST /api/play-sessions, which allows 100 per batch and requires roms.user.write. Apply both rules before the session is completed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(config): reject empty platform binding and version values config.yml exits on load when a platforms or versions value is empty, so the API must not write one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(collections): require smart collection criteria to be a JSON object Any other JSON value was stored, then failed the response schema and broke the smart collection list for every user who could see the collection. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(stats): require roms.read on /api/stats Anonymous callers were served counts over the whole library, including platforms and ROMs hidden from users. The UI only calls it after login. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal /api/roms/filters aggregated facet values over the whole library, GET /api/saves/{id} and GET /api/play-sessions returned the caller's own rows on hidden ROMs, and removing ROMs from a collection could drop members hidden from its owner. The facet visibility clauses move onto RomVisibilityFilter so stats and filters share them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins The SSRF exception for a self-hosted Playmatch or Hasheous applied to every request, so a user's webhook could reach any path on that private origin. Non-admin webhooks now validate and connect with an empty allowlist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(saves): bound total decompressed size when hashing zip archives Zip content hashing capped each entry but not the archive, so many entries each under the cap could still decompress and hash far more than any real save or memory card holds. Budget the decompressed bytes across the whole archive and cap the entry count; callers keep treating an over-budget archive as an unknown hash. The chunked, budgeted entry reader is shared with the memory card archive check, and the RetroArch store path now hashes off the event loop like its siblings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(psp): clamp LZ4 literal and match copies to the ZISO block size The ZISO block decoder appended literals and copied matches for their full encoded length before checking the output size, and an LZ4 length can be extended without bound by 0xFF bytes. A small crafted block could therefore expand far past the block size before being truncated. Clamp each copy to the room left in the block, stop once it is full, end the block on a truncated match offset, and copy matches with slices instead of a per-byte loop (overlapping matches repeat their pattern). Output for valid blocks is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(auth): revoke OAuth tokens when a user's credentials change A password change, admin reset, reset-link reset or rename cleared the account's web sessions, but its OAuth access tokens kept working until they expired and its refresh tokens could still be exchanged at /api/token. Revoking a user's credentials now also records a per-username revocation time in Redis, kept for the longest token lifetime. Bearer validation and refresh consumption reject any token whose iat is at or before it. OAuth tokens now carry a sub-second iat, so a login right after the change still works; a token without iat counts as older than any revocation. The revocation is keyed by the token's sub, the same username sessions are keyed by, so a rename revokes tokens issued under the old name even if another account later takes it. Client (API) tokens are left alone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(api): reject local file URLs for user-supplied covers and manuals file:// and launchbox-file:// URLs are meant for covers and manuals that a scan records from gamelist.xml or LaunchBox metadata. The collection create/update endpoints and the ROM update endpoint passed a user-supplied url_cover (and url_manual) straight to the resource handler, which copied whatever library file it named into the entity's resources. That let any user with collections.write or roms.write pull files they cannot otherwise read, including those of hidden platforms and ROMs. These endpoints now answer 400 for a local file URL, unless it is the value already stored, which the edit forms echo back on every save. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(resources): bound cover downloads and decodes Remote covers, screenshots, manuals, badges and media files were streamed to disk with no size limit, and a gzip-encoded body was read whole and inflated in memory. Downloads now go through one helper that counts bytes against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the same cap, and aborts past it, so the partial file is removed and any earlier copy kept. Covers are also bounded once on disk: a still image whose header declares more than MAX_COVER_PIXELS is discarded before it is decoded (and an uploaded one is refused with a 400), and a DecompressionBombError while deriving the small cover now discards the download instead of failing the request and leaving the file behind. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: fix mypy errors in the new tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: address Greptile review on permission and input hardening - Date OAuth tokens to before the credential check, so a password change that lands during the check revokes the tokens it issues. - Apply ROM visibility to play sessions in SQL, before the page slice. - Reject truncated gzip bodies and inflate every gzip member. - Shorten the zip budget comment; stream real httpx2 responses in tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: apply code-review findings on permission hardening Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off the event loop, and reuse the shared httpx client factory for webhooks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: apply simplify pass on permission hardening Read the OAuth revocation stamp through the async cache, share the play-session batch-size check, raise a plain OSError for oversized downloads, and drop a dead slice in the LZ4 decoder. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: apply review-polish pass on permission hardening Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: state that ROM visibility is enforced as access control Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(assets): hide saves, states, screenshots and memory cards on hidden ROMs Visibility is access control, so per-id save/state/screenshot routes now 404 when the save's ROM is hidden from the caller (hidden ROM, hidden platform or age limit), and the save/state lists and identifier lists leave those rows out in SQL. GET /api/saves/summary 404s on a hidden ROM. Memory cards on a hidden platform 404 on every per-id route, drop out of both lists, and can't be created against a hidden platform. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(saves): answer a hidden ROM's save summary like a missing one Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(permissions): enforce ROM visibility in sync, installs and feeds Hidden ROMs/platforms and age-limited ROMs are access control, so the paths that skipped the caller's visibility now apply it: - sync negotiate: saves on hidden ROMs are neither offered, paired nor reported as conflicts; a client save on one negotiates like an unknown ROM - push-pull SSH sync: resolves the device owner's visibility and skips saves on hidden ROMs in both directions - device installs: list and claim leave out requests whose ROM became hidden (they stay pending), and outcome notifications don't name it - recommendations: a hidden seed ROM is no longer named - music playlists: track_count counts only tracks on visible ROMs - audit events: firmware targets on hidden platforms are filtered - setup library: supported platforms honour the caller's visibility - feeds: a hidden platform found by slug reads as missing Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(visibility): hide ROMs from virtual collections, stats and scan events Virtual collections apply the caller's visibility in SQL: a collection with no visible member is left out (404 by id), member ids and covers skip hidden ROMs, and the limit counts only visible collections. Stats save, state and screenshot totals skip assets of hidden ROMs. Scan events no longer broadcast to every socket. Progress and end events go to a scan room that sockets of users holding platforms.write or tasks.run join on connect. scanning_rom and scanning_platform go to the user rooms of those followers who can see that ROM or platform, resolved once per scan and grouped by visibility. get_rom_audience now builds on a shared get_user_visibilities. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: apply code-review findings on ROM visibility enforcement Match virtual collection members by ROM id, build the cover visibility clauses once, filter feed platforms by visibility in SQL, resolve every id before a batch save or state delete, filter push-pull saves in the query, and narrow the hides query to the requested users. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: apply simplify pass on ROM visibility enforcement Require an explicit visibility filter on the saves, states and memory card queries, share one roms_facets visibility join and one owned-asset helper, filter virtual collection members by hidden ids, batch the scan audience's scope lookup, and move the empty-room emit guard into socket_handler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: start the scan audience before emitting from scan_rom Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: apply humanizer pass on the visibility rule Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(streaming): don't mount a memory card on a hidden platform Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: address Greptile review on ROM visibility enforcement Refresh a running scan's audience after a permission change, fix the precedence of the scan-room join assertion, and narrow mock await_args before reading them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * revert: drop per-visibility scan event audience Scan events go back to every socket. Removes handler/scan/audience.py, the scan room join on connect, the permissions generation bump and the batched OAuth scope resolution that only the audience used. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
454 lines
16 KiB
Python
454 lines
16 KiB
Python
import asyncio
|
|
import re
|
|
from pathlib import Path
|
|
from typing import Annotated, Any
|
|
|
|
from fastapi import Body, File, HTTPException, Request, UploadFile, status
|
|
from fastapi.responses import FileResponse
|
|
from pydantic import BaseModel as PydanticBaseModel
|
|
from pydantic import Field
|
|
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses.memory_cards import (
|
|
MemoryCardSchema,
|
|
MemoryCardVersionSchema,
|
|
UserMemoryCardSchema,
|
|
)
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import get_rom_visibility_filter
|
|
from handler.database import db_memory_card_handler, db_platform_handler
|
|
from handler.filesystem import fs_asset_handler
|
|
from handler.filesystem.assets_handler import build_asset_file_response
|
|
from logger.formatter import highlight as hl
|
|
from logger.logger import log
|
|
from models.assets import (
|
|
EMULATOR_MAX_LENGTH,
|
|
MEMORY_CARD_NAME_MAX_LENGTH,
|
|
MemoryCard,
|
|
MemoryCardVersion,
|
|
)
|
|
from utils.memory_cards import (
|
|
MEMORY_CARD_MAX_BYTES,
|
|
UnsafeCardArchive,
|
|
assert_card_archive_safe,
|
|
store_memory_card_version,
|
|
)
|
|
from utils.router import APIRouter
|
|
from utils.uploads import check_asset_upload_size
|
|
|
|
router = APIRouter(
|
|
prefix="/memory-cards",
|
|
tags=["memory-cards"],
|
|
)
|
|
|
|
MEMORY_CARD_FILE_UPLOAD = File(..., description="Memory card archive to upload.")
|
|
|
|
# The emulator name is a folder under the user's memory_cards directory, so it
|
|
# is held to what a folder may be called rather than to any list of emulators.
|
|
EMULATOR_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 ._-]*$")
|
|
|
|
|
|
class MemoryCardCreatePayload(PydanticBaseModel):
|
|
name: str = Field(max_length=MEMORY_CARD_NAME_MAX_LENGTH)
|
|
emulator: str = Field(max_length=EMULATOR_MAX_LENGTH)
|
|
# Loose display hint only; never scopes lookup (see MemoryCard model).
|
|
platform_id: int | None = None
|
|
is_public: bool = False
|
|
|
|
|
|
def _card_or_404(request: Request, card_id: int) -> MemoryCard:
|
|
"""Fetch a card the caller may read: their own, or another user's public
|
|
one. Everything else is a 404 (never reveal a private card exists)."""
|
|
card = db_memory_card_handler.get_card_by_id(card_id)
|
|
if (
|
|
not card
|
|
or (card.user_id != request.user.id and not card.is_public)
|
|
or card.platform_id in get_rom_visibility_filter(request).hidden_platform_ids
|
|
):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Memory card with ID {card_id} not found",
|
|
)
|
|
return card
|
|
|
|
|
|
def _owned_card_or_404(request: Request, card_id: int) -> MemoryCard:
|
|
"""Fetch a card the caller owns, for mutations. A card owned by someone
|
|
else is a 404, matching how states scope writes to the owner."""
|
|
card = db_memory_card_handler.get_card(user_id=request.user.id, id=card_id)
|
|
if (
|
|
not card
|
|
or card.platform_id in get_rom_visibility_filter(request).hidden_platform_ids
|
|
):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Memory card with ID {card_id} not found",
|
|
)
|
|
return card
|
|
|
|
|
|
def _apply_card_update(card_id: int, data: dict[str, Any]) -> MemoryCard:
|
|
"""Write a field update, treating a card deleted underneath us as a 404."""
|
|
updated = db_memory_card_handler.update_card(card_id, data)
|
|
if updated is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND, detail="Memory card not found"
|
|
)
|
|
return updated
|
|
|
|
|
|
@protected_route(router.post, "", [Scope.ASSETS_WRITE])
|
|
def add_memory_card(
|
|
request: Request,
|
|
payload: MemoryCardCreatePayload,
|
|
) -> MemoryCardSchema:
|
|
"""Create an empty memory card. It hydrates onto a container at the next
|
|
streaming claim; its data accrues as versions on save-and-exit."""
|
|
name = payload.name.strip()
|
|
emulator = payload.emulator.strip()
|
|
if not name or not emulator:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Both name and emulator are required",
|
|
)
|
|
|
|
if not EMULATOR_NAME_RE.match(emulator):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Not a valid emulator name: {emulator}",
|
|
)
|
|
|
|
if payload.platform_id is not None:
|
|
platform = db_platform_handler.get_platform(payload.platform_id)
|
|
if (
|
|
not platform
|
|
or platform.id in get_rom_visibility_filter(request).hidden_platform_ids
|
|
):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Platform with ID {payload.platform_id} not found",
|
|
)
|
|
|
|
card = db_memory_card_handler.add_card(
|
|
MemoryCard(
|
|
user_id=request.user.id,
|
|
emulator=emulator,
|
|
platform_id=payload.platform_id,
|
|
name=name,
|
|
slot=1,
|
|
is_public=payload.is_public,
|
|
)
|
|
)
|
|
log.info(f"Created memory card {hl(name)} [{emulator}] for {request.user.username}")
|
|
return MemoryCardSchema.model_validate(card)
|
|
|
|
|
|
@protected_route(router.get, "", [Scope.ASSETS_READ])
|
|
def get_memory_cards(
|
|
request: Request, emulator: str | None = None
|
|
) -> list[MemoryCardSchema]:
|
|
"""The caller's own cards, newest-synced first, optionally one emulator."""
|
|
cards = db_memory_card_handler.get_cards(
|
|
request.user.id, emulator, visibility=get_rom_visibility_filter(request)
|
|
)
|
|
return [MemoryCardSchema.model_validate(card) for card in cards]
|
|
|
|
|
|
@protected_route(router.get, "/shared", [Scope.ASSETS_READ])
|
|
def get_shared_memory_cards(
|
|
request: Request, emulator: str
|
|
) -> list[UserMemoryCardSchema]:
|
|
"""Cards for an emulator visible to the caller: their own plus other users'
|
|
public ones. Browsing and download only: mounting a card at claim is
|
|
owner-scoped, so the picker lists the caller's own cards instead."""
|
|
cards = db_memory_card_handler.get_shared_cards(
|
|
emulator=emulator,
|
|
user_id=request.user.id,
|
|
visibility=get_rom_visibility_filter(request),
|
|
)
|
|
return [
|
|
UserMemoryCardSchema.model_validate(
|
|
{
|
|
**MemoryCardSchema.model_validate(card).model_dump(),
|
|
"username": card.user.username,
|
|
"user_avatar_path": card.user.avatar_path,
|
|
"user_updated_at": card.user.updated_at,
|
|
}
|
|
)
|
|
for card in cards
|
|
]
|
|
|
|
|
|
# The expansion check decompresses what the uploader sent, so it runs off the
|
|
# loop. The executor it lands in is the one every other blocking call in the
|
|
# process shares, hence the cap on how many uploads may occupy it at once.
|
|
_ARCHIVE_CHECKS = asyncio.Semaphore(2)
|
|
|
|
|
|
async def _assert_safe_archive(content: bytes) -> None:
|
|
"""The shared archive check, as a 400. Covers the whole gate: readable zip,
|
|
no escaping paths, no symlinks, no runaway expansion.
|
|
"""
|
|
try:
|
|
async with _ARCHIVE_CHECKS:
|
|
await asyncio.to_thread(assert_card_archive_safe, content)
|
|
except UnsafeCardArchive as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Memory card archive rejected, {exc}",
|
|
) from None
|
|
|
|
|
|
def _version_file_or_404(version: MemoryCardVersion) -> Path:
|
|
try:
|
|
file_path = fs_asset_handler.validate_path(version.full_path)
|
|
except ValueError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Memory card file not found",
|
|
) from None
|
|
|
|
if not file_path.exists() or not file_path.is_file():
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Memory card file not found on disk",
|
|
)
|
|
return file_path
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/versions/{id}/content",
|
|
[Scope.ASSETS_READ],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
def download_memory_card_version(request: Request, id: int) -> FileResponse:
|
|
"""Download a version's card archive. Readable if the caller owns the parent
|
|
card or it is public."""
|
|
version = db_memory_card_handler.get_version_by_id(id)
|
|
if not version:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Memory card version with ID {id} not found",
|
|
)
|
|
# Reuse the card visibility check on the parent.
|
|
_card_or_404(request, version.memory_card_id)
|
|
|
|
return build_asset_file_response(
|
|
_version_file_or_404(version), filename=version.file_name
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/{id}/content",
|
|
[Scope.ASSETS_READ],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
def download_memory_card(request: Request, id: int) -> FileResponse:
|
|
"""Download the card as it stands now, without going through its history.
|
|
|
|
This is the newest version, which is also what the next claim hydrates onto
|
|
a container, so what comes down here is what the emulator would boot with.
|
|
A card that has never been synced has nothing to serve and 404s."""
|
|
_card_or_404(request, id)
|
|
|
|
version = db_memory_card_handler.get_latest_version(id)
|
|
if not version:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Memory card has no stored data yet",
|
|
)
|
|
|
|
return build_asset_file_response(
|
|
_version_file_or_404(version), filename=version.file_name
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/{id}/versions",
|
|
[Scope.ASSETS_WRITE],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {},
|
|
status.HTTP_404_NOT_FOUND: {},
|
|
status.HTTP_413_CONTENT_TOO_LARGE: {},
|
|
},
|
|
)
|
|
async def upload_memory_card_version(
|
|
request: Request,
|
|
id: int,
|
|
cardFile: UploadFile = MEMORY_CARD_FILE_UPLOAD,
|
|
) -> MemoryCardVersionSchema:
|
|
"""Store a card image the user supplied as the card's newest version, which
|
|
is what the next claim hydrates onto the container (owner only).
|
|
|
|
Only the zip layout the broker exchanges is accepted. A bare card image
|
|
(`.ps2`, `.raw`) is refused rather than stored, because nothing downstream
|
|
would notice until hydrate pushed it and the emulator rejected the card.
|
|
"""
|
|
check_asset_upload_size(cardFile, "Memory card file")
|
|
card = _owned_card_or_404(request, id)
|
|
|
|
content = await cardFile.read(MEMORY_CARD_MAX_BYTES + 1)
|
|
if len(content) > MEMORY_CARD_MAX_BYTES:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_413_CONTENT_TOO_LARGE,
|
|
detail=(
|
|
f"Memory card exceeds the maximum size of "
|
|
f"{MEMORY_CARD_MAX_BYTES} bytes"
|
|
),
|
|
)
|
|
await _assert_safe_archive(content)
|
|
|
|
# The version this call wrote, not the card's latest: a teardown evacuating
|
|
# the same card alongside the upload would make the latest describe a
|
|
# snapshot the uploader never sent.
|
|
version = await store_memory_card_version(
|
|
request.user, card, content, deduplicate=False
|
|
)
|
|
if version is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="Memory card upload was not stored",
|
|
)
|
|
|
|
log.info(f"Uploaded memory card {hl(card.name)} [{card.emulator}]")
|
|
return MemoryCardVersionSchema.model_validate(version)
|
|
|
|
|
|
@protected_route(router.get, "/{id}", [Scope.ASSETS_READ])
|
|
def get_memory_card(request: Request, id: int) -> MemoryCardSchema:
|
|
"""A single card: the caller's own or another user's public one."""
|
|
card = _card_or_404(request, id)
|
|
return MemoryCardSchema.model_validate(card)
|
|
|
|
|
|
def _reconcile_missing(version: MemoryCardVersion) -> bool:
|
|
"""Whether this version's archive is gone, persisting the answer.
|
|
|
|
Nothing else writes `missing_from_fs`, and the history is the only place a
|
|
user can see that a snapshot is unrecoverable before clicking download, so
|
|
the listing is where the flag is brought back in line with the disk.
|
|
"""
|
|
try:
|
|
path = fs_asset_handler.validate_path(version.full_path)
|
|
missing = not path.is_file()
|
|
except ValueError, OSError:
|
|
missing = True
|
|
|
|
if missing != version.missing_from_fs:
|
|
db_memory_card_handler.set_version_missing(version.id, missing)
|
|
return missing
|
|
|
|
|
|
@protected_route(router.get, "/{id}/versions", [Scope.ASSETS_READ])
|
|
def get_memory_card_versions(
|
|
request: Request, id: int
|
|
) -> list[MemoryCardVersionSchema]:
|
|
"""A card's snapshot history, newest first."""
|
|
_card_or_404(request, id)
|
|
versions = db_memory_card_handler.get_versions(id)
|
|
return [
|
|
MemoryCardVersionSchema.model_validate(v).model_copy(
|
|
update={"missing_from_fs": _reconcile_missing(v)}
|
|
)
|
|
for v in versions
|
|
]
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{id}",
|
|
[Scope.ASSETS_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
def rename_memory_card(
|
|
request: Request,
|
|
id: int,
|
|
name: Annotated[str, Body(embed=True, max_length=MEMORY_CARD_NAME_MAX_LENGTH)],
|
|
) -> MemoryCardSchema:
|
|
"""Rename a card (owner only)."""
|
|
_owned_card_or_404(request, id)
|
|
cleaned = name.strip()
|
|
if not cleaned:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Name cannot be empty",
|
|
)
|
|
return MemoryCardSchema.model_validate(_apply_card_update(id, {"name": cleaned}))
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{id}/visibility",
|
|
[Scope.ASSETS_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
def update_memory_card_visibility(
|
|
request: Request,
|
|
id: int,
|
|
is_public: Annotated[bool, Body(embed=True)],
|
|
) -> MemoryCardSchema:
|
|
"""Toggle a card's public/private visibility (owner only). Sharing is
|
|
one-way: a recipient's writes go to their own card, never back to this one."""
|
|
_owned_card_or_404(request, id)
|
|
return MemoryCardSchema.model_validate(
|
|
_apply_card_update(id, {"is_public": is_public})
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/delete",
|
|
[Scope.ASSETS_WRITE],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {},
|
|
status.HTTP_404_NOT_FOUND: {},
|
|
},
|
|
)
|
|
async def delete_memory_cards(
|
|
request: Request,
|
|
cards: Annotated[
|
|
list[int],
|
|
Body(
|
|
description="List of memory card ids to delete.",
|
|
embed=True,
|
|
),
|
|
],
|
|
) -> list[int]:
|
|
"""Delete cards the caller owns, with their version files. Versions cascade
|
|
in the database; their on-disk archives are removed here."""
|
|
if not cards:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="No memory cards were provided",
|
|
)
|
|
|
|
# Resolve every card up front: deletion is irreversible and spans one
|
|
# transaction per card, so a bad id in the batch must fail before the
|
|
# first archive is removed rather than half way through.
|
|
owned = [(card_id, _owned_card_or_404(request, card_id)) for card_id in cards]
|
|
|
|
for card_id, card in owned:
|
|
# The delete reports the archives that went with it, so the removal list
|
|
# cannot miss a version written while the batch was running. A file that
|
|
# will not budge (permissions, a locked mount) must not abort the batch:
|
|
# the rest of the cards would be left untouched with nothing to tell the
|
|
# caller how far it got. An orphaned archive is recoverable, a
|
|
# half-deleted batch is not.
|
|
for path in db_memory_card_handler.delete_card(card_id):
|
|
try:
|
|
await fs_asset_handler.remove_file(file_path=path)
|
|
except FileNotFoundError:
|
|
log.warning(f"Memory card file {hl(path)} already gone from disk")
|
|
except OSError as exc:
|
|
log.error(
|
|
f"Could not remove memory card file {hl(path)}, "
|
|
f"leaving it orphaned: {exc}"
|
|
)
|
|
|
|
log.info(f"Deleted memory card {hl(card.name)} [{card.emulator}]")
|
|
|
|
return cards
|