mirror of
https://github.com/rommapp/romm.git
synced 2026-12-05 05:07:31 +01:00
* Tell a device when the save it holds was deleted here Deleting a save took its row, its file and its device pairings, leaving nothing that says it ever existed. A negotiation then read a client still holding the save as a client with a save the server lacks, answered "upload", and the next launch put the deleted save back. There was no way to say "this is gone": the protocol's actions are upload, download, conflict and no_op. So a slot emptied on purpose is now remembered. `deleted_saves` keeps one row per (user, rom, slot) with what the slot held and when it was emptied, written by the delete endpoint, which is the only place a deletion is the owner's decision rather than housekeeping: autocleanup rotating a version out leaves newer rows in the slot and is never recorded. Negotiation reads it only when the slot has no row left, and answers the new "delete" action when the client's copy is the one that went: the same content hash, or a copy last written before the deletion. Anything written after it is progress the server never held, so that still answers "upload" -- emptying a slot is not a licence to delete a newer save. The generated frontend models are hand-edited to match: this environment has only CPython 3.14.0rc2, which the locked pydantic cannot import, so the backend will not start for `npm run generate`. Both edits are mechanical (the new literal in the union, the new count field), and `npm run typecheck` passes against them. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U * Decide a deletion by identity, and record it before the row goes Three real findings from the review, and the layering rule. The record was written after the save row and its file were gone, with two transactions and a filesystem removal between them. Anything failing in that window left a deletion nothing remembered, which is the resurrection this change exists to prevent. It is written first now: a record for a save that is somehow still there is never read, because a negotiation only consults it when the slot has no row left. The client's copy was matched on its own timestamp against the server's deletion time. Those clocks are not comparable, and a device running slow would have been told to delete progress it made after the deletion. The match is now identity alone: the slot remembers every version it lost, capped at the twenty most recent, and a client holding any of them is told to drop it. Anything else is offered back, which costs a deletion that does not reach that device rather than a save that is gone. Recording replaced the row with a delete and an insert, which two deletions of the same slot could race into a uniqueness error. It locks the row and merges into it, with the house savepoint-and-catch for the case where there is no row yet to lock. The comparison itself moves to handler/sync/comparison.py beside compare_save_state, where the endpoint delegates to it and the rule is tested on its own. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U * Trim the new comments to the repo's rule One or two lines each, with the rationale in the commit messages and the PR description where the rule puts it. The model's docstring is one sentence, and the comparison keeps its Args and Returns. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U * Sort comparison imports Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U * Widen the window a deletion is remembered in A slot's record keeps a bounded list of the versions it lost, and the trim drops the oldest, which are exactly the ones a long-offline device is likeliest to still hold. At twenty, a device that missed twenty delete-and-refill cycles of one slot comes back with a digest that has aged out and is answered `upload`, which puts a deleted save back. Raised to a hundred, where the device would have had to miss a hundred manual deletions of the same slot. The residual is deliberate and cannot be designed away by a longer list alone: past the bound the server does not know those bytes were deleted, and the answer degrades to `upload`, which fails by not propagating a deletion rather than by destroying a save. A test now names that case so the next reader meets it as a choice rather than as an oversight. Found by Greptile on #4674. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U * Trim the retention comments back to the rule Both were over the two-line limit, and the constant's was a six-line design essay of exactly the kind the last round of this review already removed from this PR. The reasoning belongs in the commit that made the change and in the pull request, where it is. What stays is the part the code cannot say: the trim drops the oldest, and past the bound a device is answered `upload` rather than `delete`. Found by Greptile on #4674. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015B86R6sN9CZ2uAWXCB9Y3U * Name the deletion record for assets, not only saves Unreleased, so the table can take a name that states can share later without another migration. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Apply code-review fixes to deletion records Record a deletion in short separate transactions so concurrent first deletions no longer deadlock on MariaDB, hash a save that never recorded one, keep a re-deleted version from being trimmed, scope the negotiation's read to emptied slots, and require total_delete. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Simplify deletion records Drop the unread deleted_at column, record from _delete_save so every caller of it is covered, skip a record no hash could ever match, let comparison decide delete vs upload with its reason, count actions once, and fold the near-duplicate tests. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Polish the deletion record's index comment Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
904 lines
30 KiB
Python
904 lines
30 KiB
Python
import os
|
|
import re
|
|
from collections.abc import Sequence
|
|
from datetime import datetime, timezone
|
|
from typing import Annotated
|
|
|
|
from fastapi import Body, File, HTTPException, Query, Request, UploadFile, status
|
|
from fastapi.responses import FileResponse
|
|
|
|
from config import MAX_AUTOCLEANUP_LIMIT, MAX_SAVES_PER_SLOT
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses.assets import SaveSchema, SaveSummarySchema, SlotSummarySchema
|
|
from endpoints.responses.device import DeviceSyncSchema
|
|
from endpoints.roms import refresh_affected_smart_collections
|
|
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
|
|
from handler.asset_store import release_thumbnail, remove_asset_file, rename_asset
|
|
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,
|
|
db_save_handler,
|
|
db_screenshot_handler,
|
|
db_sync_session_handler,
|
|
)
|
|
from handler.filesystem import fs_asset_handler
|
|
from handler.scan_handler import scan_save, scan_screenshot
|
|
from logger.formatter import BLUE
|
|
from logger.formatter import highlight as hl
|
|
from logger.logger import log
|
|
from models.assets import SAVE_SLOT_MAX_LENGTH, Save
|
|
from models.base import FILE_NAME_MAX_LENGTH
|
|
from models.device import Device
|
|
from models.device_save_sync import DeviceSaveSync
|
|
from utils.assets import normalize_asset_labels
|
|
from utils.datetime import to_utc
|
|
from utils.filesystem import sanitize_filename
|
|
from utils.router import APIRouter
|
|
from utils.uploads import check_asset_upload_size
|
|
from utils.validation import RomIdScope, narrow_rom_id_scope
|
|
|
|
|
|
def _build_save_schema(
|
|
save: Save,
|
|
syncs: Sequence[tuple[DeviceSaveSync, str | None]] = (),
|
|
device: Device | None = None,
|
|
) -> SaveSchema:
|
|
"""Attach one ``DeviceSyncSchema`` per device that has synced this save.
|
|
|
|
``syncs`` is the full list of sync rows (paired with device name) for this
|
|
save across every device, so clients can attribute the save to its creator.
|
|
``device`` is the caller's device, when supplied: its entry is emitted first
|
|
for stable ordering and old-client compatibility, and a placeholder entry is
|
|
synthesized when the caller has not yet synced this save.
|
|
"""
|
|
save_schema = SaveSchema.model_validate(save)
|
|
|
|
save_updated = to_utc(save.updated_at)
|
|
caller_present = False
|
|
entries: list[DeviceSyncSchema] = []
|
|
for sync, device_name in syncs:
|
|
if device and sync.device_id == device.id:
|
|
caller_present = True
|
|
entries.append(
|
|
DeviceSyncSchema(
|
|
device_id=sync.device_id,
|
|
device_name=device_name,
|
|
last_synced_at=sync.last_synced_at,
|
|
is_untracked=sync.is_untracked,
|
|
is_current=to_utc(sync.last_synced_at) >= save_updated,
|
|
)
|
|
)
|
|
|
|
if device and not caller_present:
|
|
entries.append(
|
|
DeviceSyncSchema(
|
|
device_id=device.id,
|
|
device_name=device.name,
|
|
last_synced_at=save.updated_at,
|
|
is_untracked=False,
|
|
is_current=False,
|
|
)
|
|
)
|
|
|
|
if device:
|
|
entries.sort(key=lambda entry: entry.device_id != device.id)
|
|
|
|
save_schema.device_syncs = entries
|
|
return save_schema
|
|
|
|
|
|
def _syncs_for_save(
|
|
save_id: int, device: Device | None
|
|
) -> list[tuple[DeviceSaveSync, str | None]]:
|
|
"""Fetch every device sync for a single save when a device is in context.
|
|
|
|
Device attribution is only meaningful to a device-scoped caller, so callers
|
|
without a device get an empty list and no query is issued.
|
|
"""
|
|
if not device:
|
|
return []
|
|
return db_device_save_sync_handler.get_syncs_for_saves([save_id]).get(save_id, [])
|
|
|
|
|
|
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)
|
|
|
|
|
|
async def _prune_slot(user_id: int, rom_id: int, slot: str, keep: int) -> None:
|
|
"""Drop every version of ``slot`` past the ``keep`` newest, files included."""
|
|
for file_path, file_name, file_name_no_ext in db_save_handler.prune_slot(
|
|
user_id=user_id, rom_id=rom_id, slot=slot, keep=keep
|
|
):
|
|
await remove_asset_file(f"{file_path}/{file_name}", "Save file")
|
|
await release_thumbnail(
|
|
db_screenshot_handler.get_screenshot(
|
|
rom_id=rom_id,
|
|
user_id=user_id,
|
|
file_name=file_name,
|
|
file_name_no_ext=file_name_no_ext,
|
|
)
|
|
)
|
|
|
|
|
|
def _slot_retention(autocleanup: bool, autocleanup_limit: int) -> int | None:
|
|
"""Versions to keep in a slot: the tighter of the client's ask and the server cap."""
|
|
limits = [MAX_SAVES_PER_SLOT] if MAX_SAVES_PER_SLOT else []
|
|
if autocleanup:
|
|
limits.append(autocleanup_limit)
|
|
return min(limits, default=None)
|
|
|
|
|
|
def _apply_datetime_tag(filename: str) -> str:
|
|
name, ext = os.path.splitext(filename)
|
|
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d_%H-%M-%S")
|
|
|
|
if DATETIME_TAG_PATTERN.search(name):
|
|
name = DATETIME_TAG_PATTERN.sub("", name)
|
|
|
|
return f"{name} [{timestamp}]{ext}"
|
|
|
|
|
|
def _resolve_device(
|
|
device_id: str | None,
|
|
user_id: int,
|
|
scopes: set[str] | None = None,
|
|
required_scope: Scope | None = None,
|
|
) -> Device | None:
|
|
if not device_id:
|
|
return None
|
|
|
|
if required_scope and scopes and required_scope not in scopes:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
|
|
|
|
device = db_device_handler.get_device(device_id=device_id, user_id=user_id)
|
|
if not device:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Device with ID {device_id} not found",
|
|
)
|
|
return device
|
|
|
|
|
|
def _increment_session_counter(session_id: int, user_id: int) -> None:
|
|
try:
|
|
db_sync_session_handler.increment_operations_completed(
|
|
session_id=session_id,
|
|
user_id=user_id,
|
|
)
|
|
except Exception:
|
|
log.warning(f"Failed to update sync session {session_id}", exc_info=True)
|
|
|
|
|
|
def _owned_save_or_404(id: int, user_id: int) -> Save:
|
|
save = db_save_handler.get_save_by_id(id)
|
|
if not save or save.user_id != user_id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Save with ID {id} not found",
|
|
)
|
|
return save
|
|
|
|
|
|
router = APIRouter(
|
|
prefix="/saves",
|
|
tags=["saves"],
|
|
)
|
|
|
|
SAVE_FILE_UPLOAD = File(..., description="Save file to upload.")
|
|
SAVE_SCREENSHOT_UPLOAD = File(
|
|
default=None,
|
|
description="Screenshot file associated with this save.",
|
|
)
|
|
SAVE_FILE_UPDATE = File(default=None, description="Updated save file content.")
|
|
SAVE_SCREENSHOT_UPDATE = File(default=None, description="Updated screenshot file.")
|
|
|
|
|
|
@protected_route(router.post, "", [Scope.ASSETS_WRITE])
|
|
async def add_save(
|
|
request: Request,
|
|
rom_id: int,
|
|
emulator: str | None = None,
|
|
slot: Annotated[str | None, Query(max_length=SAVE_SLOT_MAX_LENGTH)] = None,
|
|
device_id: str | None = None,
|
|
session_id: int | None = None,
|
|
overwrite: bool = False,
|
|
autocleanup: bool = False,
|
|
autocleanup_limit: int = 10,
|
|
saveFile: UploadFile = SAVE_FILE_UPLOAD,
|
|
screenshotFile: UploadFile | None = SAVE_SCREENSHOT_UPLOAD,
|
|
) -> SaveSchema:
|
|
"""Upload a save file for a ROM."""
|
|
check_asset_upload_size(saveFile, "Save file")
|
|
check_asset_upload_size(screenshotFile, "Screenshot file")
|
|
|
|
# Keep at least the save just uploaded, and cap what a client can retain
|
|
autocleanup_limit = max(1, min(autocleanup_limit, MAX_AUTOCLEANUP_LIMIT))
|
|
keep = _slot_retention(autocleanup, autocleanup_limit)
|
|
|
|
device = _resolve_device(
|
|
device_id, request.user.id, request.auth.scopes, Scope.DEVICES_WRITE
|
|
)
|
|
|
|
rom = db_rom_handler.get_rom(rom_id)
|
|
if not rom:
|
|
raise RomNotFoundInDatabaseException(rom_id)
|
|
|
|
if not saveFile.filename:
|
|
log.error("Save file has no filename")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST, detail="Save file has no filename"
|
|
)
|
|
|
|
try:
|
|
sanitized_save_filename = sanitize_filename(saveFile.filename)
|
|
except ValueError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Invalid save filename: {str(exc)}",
|
|
) from exc
|
|
|
|
actual_filename = sanitized_save_filename
|
|
if slot:
|
|
actual_filename = _apply_datetime_tag(sanitized_save_filename)
|
|
|
|
saves_path = fs_asset_handler.build_saves_file_path(
|
|
user=request.user,
|
|
platform_fs_slug=rom.platform.fs_slug,
|
|
rom_id=rom.id,
|
|
emulator=emulator,
|
|
)
|
|
|
|
db_save = db_save_handler.get_save_by_filename(
|
|
user_id=request.user.id, rom_id=rom.id, file_name=actual_filename, slot=slot
|
|
)
|
|
|
|
if device and slot and not overwrite:
|
|
slot_saves = db_save_handler.get_saves(
|
|
user_id=request.user.id,
|
|
rom_ids=[rom.id],
|
|
slot=slot,
|
|
order_by="updated_at",
|
|
)
|
|
if slot_saves:
|
|
latest_in_slot = slot_saves[0]
|
|
sync = db_device_save_sync_handler.get_sync(
|
|
device_id=device.id, save_id=latest_in_slot.id
|
|
)
|
|
if not sync or to_utc(sync.last_synced_at) < to_utc(
|
|
latest_in_slot.updated_at
|
|
):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
detail="Slot has a newer save since your last sync",
|
|
)
|
|
elif device and db_save and not overwrite:
|
|
sync = db_device_save_sync_handler.get_sync(
|
|
device_id=device.id, save_id=db_save.id
|
|
)
|
|
if sync and to_utc(sync.last_synced_at) < to_utc(db_save.updated_at):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
detail="Save has been updated since your last sync",
|
|
)
|
|
|
|
log.info(
|
|
f"Uploading save {hl(actual_filename)} for {hl(str(rom.name), color=BLUE)}"
|
|
)
|
|
|
|
await fs_asset_handler.write_file(
|
|
file=saveFile, path=saves_path, filename=actual_filename
|
|
)
|
|
|
|
scanned_save = await scan_save(
|
|
file_name=actual_filename,
|
|
user=request.user,
|
|
platform_fs_slug=rom.platform.fs_slug,
|
|
rom_id=rom_id,
|
|
emulator=emulator,
|
|
)
|
|
|
|
if slot and scanned_save.content_hash and not overwrite:
|
|
existing_by_hash = db_save_handler.get_save_by_content_hash(
|
|
user_id=request.user.id,
|
|
rom_id=rom.id,
|
|
content_hash=scanned_save.content_hash,
|
|
slot=slot,
|
|
)
|
|
if existing_by_hash:
|
|
try:
|
|
await fs_asset_handler.remove_file(f"{saves_path}/{actual_filename}")
|
|
except FileNotFoundError:
|
|
pass
|
|
# A retry still counts as an upload to the slot, so the cap applies.
|
|
if keep is not None:
|
|
await _prune_slot(request.user.id, rom.id, slot, keep)
|
|
return _build_save_schema(
|
|
existing_by_hash, _syncs_for_save(existing_by_hash.id, device), device
|
|
)
|
|
|
|
if db_save is None:
|
|
# Refresh hash if the file already exists to avoid mismatched metadata.
|
|
colliding_save = db_save_handler.get_save_by_path(
|
|
user_id=request.user.id,
|
|
rom_id=rom.id,
|
|
file_path=scanned_save.file_path,
|
|
file_name=actual_filename,
|
|
)
|
|
if colliding_save and colliding_save.content_hash != scanned_save.content_hash:
|
|
db_save = colliding_save
|
|
|
|
if db_save:
|
|
# Track file path and emulator to prevent hash-content drift.
|
|
stale_full_path = db_save.full_path
|
|
update_data: dict = {
|
|
"file_size_bytes": scanned_save.file_size_bytes,
|
|
"content_hash": scanned_save.content_hash,
|
|
"file_path": scanned_save.file_path,
|
|
"emulator": emulator,
|
|
}
|
|
if slot is not None:
|
|
update_data["slot"] = slot
|
|
db_save = db_save_handler.update_save(db_save.id, update_data)
|
|
|
|
# Delete orphaned bytes only if no other row references the old path.
|
|
if stale_full_path != db_save.full_path:
|
|
still_referenced = any(
|
|
other.id != db_save.id and other.full_path == stale_full_path
|
|
for other in db_save_handler.get_saves(
|
|
user_id=request.user.id, rom_ids=[rom.id]
|
|
)
|
|
)
|
|
if not still_referenced:
|
|
try:
|
|
await fs_asset_handler.remove_file(stale_full_path)
|
|
except FileNotFoundError:
|
|
pass
|
|
else:
|
|
scanned_save.rom_id = rom.id
|
|
scanned_save.user_id = request.user.id
|
|
scanned_save.emulator = emulator
|
|
scanned_save.slot = slot
|
|
scanned_save.origin_device_id = device.id if device else None
|
|
db_save = db_save_handler.add_save(save=scanned_save)
|
|
|
|
if device:
|
|
db_device_save_sync_handler.upsert_sync(
|
|
device_id=device.id, save_id=db_save.id, synced_at=db_save.updated_at
|
|
)
|
|
db_device_handler.update_last_seen(device_id=device.id, user_id=request.user.id)
|
|
|
|
if session_id:
|
|
_increment_session_counter(session_id, request.user.id)
|
|
|
|
if slot and keep is not None:
|
|
await _prune_slot(request.user.id, rom.id, slot, keep)
|
|
|
|
if screenshotFile and screenshotFile.filename:
|
|
try:
|
|
sanitized_screenshot_filename = sanitize_filename(screenshotFile.filename)
|
|
except ValueError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Invalid screenshot filename: {str(exc)}",
|
|
) from exc
|
|
# Save.screenshot is matched by stem, so a slotted upload names the
|
|
# screenshot after the tagged save whatever the client called it.
|
|
if slot:
|
|
save_stem, _ = os.path.splitext(actual_filename)
|
|
_, screenshot_ext = os.path.splitext(sanitized_screenshot_filename)
|
|
sanitized_screenshot_filename = f"{save_stem}{screenshot_ext}"
|
|
|
|
screenshots_path = fs_asset_handler.build_screenshots_file_path(
|
|
user=request.user, platform_fs_slug=rom.platform_slug, rom_id=rom.id
|
|
)
|
|
|
|
await fs_asset_handler.write_file(
|
|
file=screenshotFile,
|
|
path=screenshots_path,
|
|
filename=sanitized_screenshot_filename,
|
|
)
|
|
|
|
scanned_screenshot = await scan_screenshot(
|
|
file_name=sanitized_screenshot_filename,
|
|
user=request.user,
|
|
platform_fs_slug=rom.platform_slug,
|
|
rom_id=rom.id,
|
|
)
|
|
db_screenshot = db_screenshot_handler.get_screenshot(
|
|
file_name=sanitized_screenshot_filename,
|
|
rom_id=rom.id,
|
|
user_id=request.user.id,
|
|
)
|
|
if db_screenshot:
|
|
db_screenshot = db_screenshot_handler.update_screenshot(
|
|
db_screenshot.id,
|
|
{"file_size_bytes": scanned_screenshot.file_size_bytes},
|
|
)
|
|
else:
|
|
scanned_screenshot.rom_id = rom.id
|
|
scanned_screenshot.user_id = request.user.id
|
|
db_screenshot_handler.add_screenshot(screenshot=scanned_screenshot)
|
|
|
|
rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=request.user.id)
|
|
if not rom_user:
|
|
rom_user = db_rom_handler.add_rom_user(rom_id=rom.id, user_id=request.user.id)
|
|
db_rom_handler.update_rom_user(
|
|
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
|
)
|
|
|
|
refresh_affected_smart_collections([rom.id], membership_only=True)
|
|
|
|
return _build_save_schema(db_save, _syncs_for_save(db_save.id, device), device)
|
|
|
|
|
|
@protected_route(router.get, "", [Scope.ASSETS_READ])
|
|
def get_saves(
|
|
request: Request,
|
|
rom_id: int | None = None,
|
|
rom_ids: Annotated[
|
|
RomIdScope,
|
|
Query(
|
|
description=(
|
|
"ROM IDs to scope the results to, for clients syncing a known "
|
|
"set of ROMs. Multiple values are allowed by repeating the "
|
|
"parameter. Combined with `rom_id` when both are given."
|
|
),
|
|
),
|
|
] = None,
|
|
platform_id: int | None = None,
|
|
device_id: str | None = None,
|
|
slot: str | None = None,
|
|
) -> list[SaveSchema]:
|
|
"""Retrieve saves for the current user."""
|
|
device = _resolve_device(
|
|
device_id, request.user.id, request.auth.scopes, Scope.DEVICES_READ
|
|
)
|
|
|
|
saves = db_save_handler.get_saves(
|
|
user_id=request.user.id,
|
|
rom_ids=narrow_rom_id_scope(rom_id, rom_ids),
|
|
platform_id=platform_id,
|
|
slot=slot,
|
|
)
|
|
|
|
if not device:
|
|
return [_build_save_schema(save) for save in saves]
|
|
|
|
syncs_by_save_id = db_device_save_sync_handler.get_syncs_for_saves(
|
|
[s.id for s in saves]
|
|
)
|
|
|
|
return [
|
|
_build_save_schema(save, syncs_by_save_id.get(save.id, []), device)
|
|
for save in saves
|
|
]
|
|
|
|
|
|
@protected_route(router.get, "/identifiers", [Scope.ASSETS_READ])
|
|
def get_save_identifiers(request: Request) -> list[int]:
|
|
"""Retrieve save identifiers."""
|
|
return db_save_handler.get_save_ids(user_id=request.user.id)
|
|
|
|
|
|
@protected_route(router.get, "/summary", [Scope.ASSETS_READ])
|
|
def get_saves_summary(request: Request, rom_id: int) -> SaveSummarySchema:
|
|
"""Retrieve saves summary grouped by slot."""
|
|
summary_data = db_save_handler.get_saves_summary(
|
|
user_id=request.user.id, rom_id=rom_id
|
|
)
|
|
|
|
slots = [
|
|
SlotSummarySchema(
|
|
slot=slot_data["slot"],
|
|
count=slot_data["count"],
|
|
latest=_build_save_schema(slot_data["latest"]),
|
|
)
|
|
for slot_data in summary_data["slots"]
|
|
]
|
|
|
|
return SaveSummarySchema(total_count=summary_data["total_count"], slots=slots)
|
|
|
|
|
|
@protected_route(router.get, "/{id}", [Scope.ASSETS_READ])
|
|
def get_save(request: Request, id: int, device_id: str | None = None) -> SaveSchema:
|
|
"""Retrieve a save by ID."""
|
|
device = _resolve_device(
|
|
device_id, request.user.id, request.auth.scopes, Scope.DEVICES_READ
|
|
)
|
|
|
|
save = db_save_handler.get_save(user_id=request.user.id, id=id)
|
|
if not save:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Save with ID {id} not found",
|
|
)
|
|
|
|
return _build_save_schema(save, _syncs_for_save(save.id, device), device)
|
|
|
|
|
|
@protected_route(router.get, "/{id}/content", [Scope.ASSETS_READ])
|
|
def download_save(
|
|
request: Request,
|
|
id: int,
|
|
device_id: str | None = None,
|
|
session_id: int | None = None,
|
|
optimistic: bool = True,
|
|
) -> FileResponse:
|
|
"""Download a save file."""
|
|
device = _resolve_device(
|
|
device_id, request.user.id, request.auth.scopes, Scope.DEVICES_READ
|
|
)
|
|
|
|
# Owner can download any of their saves; everyone else only public ones.
|
|
save = db_save_handler.get_save_by_id(id)
|
|
if not save or (save.user_id != request.user.id and not save.is_public):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Save with ID {id} not found",
|
|
)
|
|
|
|
# Sharing must not override the hidden-ROM/platform policy: a save on a ROM
|
|
# hidden from the caller stays 404-masked, just like the ROM itself.
|
|
assert_rom_visible(
|
|
request, save.rom, not_found_detail=f"Save with ID {id} not found"
|
|
)
|
|
|
|
is_owner = save.user_id == request.user.id
|
|
|
|
try:
|
|
file_path = fs_asset_handler.validate_path(save.full_path)
|
|
except ValueError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="Save 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="Save file not found on disk",
|
|
)
|
|
|
|
# Sync bookkeeping only makes sense for the owner's own saves.
|
|
if device and optimistic and is_owner:
|
|
db_device_save_sync_handler.upsert_sync(
|
|
device_id=device.id,
|
|
save_id=save.id,
|
|
synced_at=save.updated_at,
|
|
)
|
|
db_device_handler.update_last_seen(device_id=device.id, user_id=request.user.id)
|
|
|
|
if session_id:
|
|
_increment_session_counter(session_id, request.user.id)
|
|
|
|
return FileResponse(path=str(file_path), filename=save.file_name)
|
|
|
|
|
|
@protected_route(router.post, "/{id}/downloaded", [Scope.DEVICES_WRITE])
|
|
def confirm_download(
|
|
request: Request,
|
|
id: int,
|
|
device_id: str = Body(..., embed=True),
|
|
) -> SaveSchema:
|
|
"""Confirm a save was downloaded successfully."""
|
|
save = db_save_handler.get_save(user_id=request.user.id, id=id)
|
|
if not save:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Save with ID {id} not found",
|
|
)
|
|
|
|
device = _resolve_device(device_id, request.user.id)
|
|
db_device_save_sync_handler.upsert_sync(
|
|
device_id=device_id,
|
|
save_id=save.id,
|
|
synced_at=save.updated_at,
|
|
)
|
|
db_device_handler.update_last_seen(device_id=device_id, user_id=request.user.id)
|
|
|
|
return _build_save_schema(save, _syncs_for_save(save.id, device), device)
|
|
|
|
|
|
@protected_route(router.put, "/{id}", [Scope.ASSETS_WRITE])
|
|
async def update_save(
|
|
request: Request,
|
|
id: int,
|
|
device_id: str | None = None,
|
|
saveFile: UploadFile | None = SAVE_FILE_UPDATE,
|
|
screenshotFile: UploadFile | None = SAVE_SCREENSHOT_UPDATE,
|
|
) -> SaveSchema:
|
|
"""Update a save file."""
|
|
|
|
check_asset_upload_size(saveFile, "Save file")
|
|
check_asset_upload_size(screenshotFile, "Screenshot file")
|
|
|
|
device = _resolve_device(
|
|
device_id, request.user.id, request.auth.scopes, Scope.DEVICES_WRITE
|
|
)
|
|
|
|
db_save = db_save_handler.get_save(user_id=request.user.id, id=id)
|
|
if not db_save:
|
|
error = f"Save with ID {id} not found"
|
|
log.error(error)
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
|
|
|
if saveFile:
|
|
await fs_asset_handler.write_file(
|
|
file=saveFile, path=db_save.file_path, filename=db_save.file_name
|
|
)
|
|
scanned_save = await scan_save(
|
|
file_name=db_save.file_name,
|
|
user=request.user,
|
|
platform_fs_slug=db_save.rom.platform_fs_slug,
|
|
rom_id=db_save.rom_id,
|
|
emulator=db_save.emulator,
|
|
)
|
|
db_save = db_save_handler.update_save(
|
|
db_save.id,
|
|
{
|
|
"file_size_bytes": scanned_save.file_size_bytes,
|
|
"content_hash": scanned_save.content_hash,
|
|
},
|
|
)
|
|
|
|
if screenshotFile and screenshotFile.filename:
|
|
try:
|
|
sanitized_screenshot_filename = sanitize_filename(screenshotFile.filename)
|
|
except ValueError as exc:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Invalid screenshot filename: {str(exc)}",
|
|
) from exc
|
|
|
|
screenshots_path = fs_asset_handler.build_screenshots_file_path(
|
|
user=request.user,
|
|
platform_fs_slug=db_save.rom.platform_slug,
|
|
rom_id=db_save.rom.id,
|
|
)
|
|
|
|
await fs_asset_handler.write_file(
|
|
file=screenshotFile,
|
|
path=screenshots_path,
|
|
filename=sanitized_screenshot_filename,
|
|
)
|
|
|
|
# Scan or update screenshot
|
|
scanned_screenshot = await scan_screenshot(
|
|
file_name=sanitized_screenshot_filename,
|
|
user=request.user,
|
|
platform_fs_slug=db_save.rom.platform_slug,
|
|
rom_id=db_save.rom.id,
|
|
)
|
|
db_screenshot = db_screenshot_handler.get_screenshot(
|
|
file_name=sanitized_screenshot_filename,
|
|
rom_id=db_save.rom.id,
|
|
user_id=request.user.id,
|
|
)
|
|
if db_screenshot:
|
|
db_screenshot = db_screenshot_handler.update_screenshot(
|
|
db_screenshot.id,
|
|
{"file_size_bytes": scanned_screenshot.file_size_bytes},
|
|
)
|
|
else:
|
|
scanned_screenshot.rom_id = db_save.rom.id
|
|
scanned_screenshot.user_id = request.user.id
|
|
db_screenshot_handler.add_screenshot(screenshot=scanned_screenshot)
|
|
|
|
# Set the last played time for the current user
|
|
rom_user = db_rom_handler.get_rom_user(db_save.rom_id, request.user.id)
|
|
if not rom_user:
|
|
rom_user = db_rom_handler.add_rom_user(db_save.rom_id, request.user.id)
|
|
db_rom_handler.update_rom_user(
|
|
rom_user.id, {"last_played": datetime.now(timezone.utc)}
|
|
)
|
|
|
|
if device:
|
|
db_device_save_sync_handler.upsert_sync(
|
|
device_id=device.id, save_id=db_save.id, synced_at=db_save.updated_at
|
|
)
|
|
db_device_handler.update_last_seen(device_id=device.id, user_id=request.user.id)
|
|
|
|
return _build_save_schema(db_save, _syncs_for_save(db_save.id, device), device)
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{id}/visibility",
|
|
[Scope.ASSETS_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
def update_save_visibility(
|
|
request: Request,
|
|
id: int,
|
|
is_public: Annotated[bool, Body(embed=True)],
|
|
) -> SaveSchema:
|
|
"""Toggle a save's public/private visibility (owner only)."""
|
|
save = _owned_save_or_404(id, request.user.id)
|
|
|
|
updated = db_save_handler.update_save(id, {"is_public": is_public}, touch=False)
|
|
|
|
# Keep the auto-captured thumbnail's visibility in sync so a shared save
|
|
# still renders its preview for other users.
|
|
if save.screenshot:
|
|
db_screenshot_handler.update_screenshot(
|
|
save.screenshot.id, {"is_public": is_public}
|
|
)
|
|
|
|
# Sharing a save exposes it to every other user's `has_saves` filter.
|
|
refresh_affected_smart_collections([save.rom_id], membership_only=True)
|
|
|
|
return _build_save_schema(updated)
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{id}/favorite",
|
|
[Scope.ASSETS_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
def update_save_favorite(
|
|
request: Request,
|
|
id: int,
|
|
is_favorite: Annotated[bool, Body(embed=True)],
|
|
) -> SaveSchema:
|
|
"""Favorite a save, sorting it ahead of the rest (owner only)."""
|
|
_owned_save_or_404(id, request.user.id)
|
|
|
|
return _build_save_schema(
|
|
db_save_handler.update_save(id, {"is_favorite": is_favorite}, touch=False)
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{id}/labels",
|
|
[Scope.ASSETS_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
def update_save_labels(
|
|
request: Request,
|
|
id: int,
|
|
labels: Annotated[list[str], Body(embed=True)],
|
|
) -> SaveSchema:
|
|
"""Replace a save's free-text labels (owner only)."""
|
|
_owned_save_or_404(id, request.user.id)
|
|
|
|
return _build_save_schema(
|
|
db_save_handler.update_save(
|
|
id, {"labels": normalize_asset_labels(labels)}, touch=False
|
|
)
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{id}/file-name",
|
|
[Scope.ASSETS_WRITE],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {},
|
|
status.HTTP_404_NOT_FOUND: {},
|
|
status.HTTP_409_CONFLICT: {},
|
|
},
|
|
)
|
|
async def rename_save(
|
|
request: Request,
|
|
id: int,
|
|
file_name: Annotated[str, Body(embed=True, max_length=FILE_NAME_MAX_LENGTH)],
|
|
) -> SaveSchema:
|
|
"""Rename a save's file, its screenshot following along (owner only)."""
|
|
save = _owned_save_or_404(id, request.user.id)
|
|
|
|
return _build_save_schema(await rename_asset(save, file_name))
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"/delete",
|
|
[Scope.ASSETS_WRITE],
|
|
responses={
|
|
status.HTTP_400_BAD_REQUEST: {},
|
|
status.HTTP_404_NOT_FOUND: {},
|
|
},
|
|
)
|
|
async def delete_saves(
|
|
request: Request,
|
|
saves: Annotated[
|
|
list[int],
|
|
Body(
|
|
description="List of save ids to delete from database.",
|
|
embed=True,
|
|
),
|
|
],
|
|
) -> list[int]:
|
|
"""Delete saves."""
|
|
if not saves:
|
|
error = "No saves were provided"
|
|
log.error(error)
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error)
|
|
|
|
affected_rom_ids: set[int] = set()
|
|
|
|
for save_id in saves:
|
|
save = db_save_handler.get_save(user_id=request.user.id, id=save_id)
|
|
if not save:
|
|
error = f"Save with ID {save_id} not found"
|
|
log.error(error)
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=error)
|
|
|
|
affected_rom_ids.add(save.rom_id)
|
|
log.info(
|
|
f"Deleting save {hl(save.file_name)} [{save.rom.platform_slug}] from filesystem"
|
|
)
|
|
await _delete_save(save)
|
|
|
|
refresh_affected_smart_collections(list(affected_rom_ids), membership_only=True)
|
|
|
|
return saves
|
|
|
|
|
|
@protected_route(router.post, "/{id}/track", [Scope.DEVICES_WRITE])
|
|
def track_save(
|
|
request: Request,
|
|
id: int,
|
|
device_id: str = Body(..., embed=True),
|
|
) -> SaveSchema:
|
|
"""Re-enable sync tracking for a save on a device."""
|
|
save = db_save_handler.get_save(user_id=request.user.id, id=id)
|
|
if not save:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Save with ID {id} not found",
|
|
)
|
|
|
|
device = _resolve_device(device_id, request.user.id)
|
|
db_device_save_sync_handler.set_untracked(
|
|
device_id=device_id, save_id=id, untracked=False
|
|
)
|
|
|
|
return _build_save_schema(save, _syncs_for_save(save.id, device), device)
|
|
|
|
|
|
@protected_route(router.post, "/{id}/untrack", [Scope.DEVICES_WRITE])
|
|
def untrack_save(
|
|
request: Request,
|
|
id: int,
|
|
device_id: str = Body(..., embed=True),
|
|
) -> SaveSchema:
|
|
"""Disable sync tracking for a save on a device."""
|
|
save = db_save_handler.get_save(user_id=request.user.id, id=id)
|
|
if not save:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Save with ID {id} not found",
|
|
)
|
|
|
|
device = _resolve_device(device_id, request.user.id)
|
|
db_device_save_sync_handler.set_untracked(
|
|
device_id=device_id, save_id=id, untracked=True
|
|
)
|
|
|
|
return _build_save_schema(save, _syncs_for_save(save.id, device), device)
|