feat(saves): add slot-based save sync with content hash deduplication

- Add device registration and save synchronization
- Implement slot-based save organization with datetime tagging
- Add conflict detection for multi-device sync scenarios
- Add content hash computation for save deduplication
- Support ZIP inner-file hashing for consistent deduplication
- Add confirm_download endpoint for sync state management
- Add overwrite parameter to bypass conflict checks
This commit is contained in:
nendo
2026-01-31 21:57:22 +09:00
parent b420af7578
commit a236123e4f
8 changed files with 1868 additions and 134 deletions

View File

@@ -74,22 +74,28 @@ def upgrade():
)
with op.batch_alter_table("saves", schema=None) as batch_op:
batch_op.add_column(sa.Column("save_name", sa.String(255), nullable=True))
batch_op.add_column(sa.Column("slot", sa.String(255), nullable=True))
batch_op.add_column(sa.Column("content_hash", sa.String(32), nullable=True))
op.create_index("ix_devices_user_id", "devices", ["user_id"])
op.create_index("ix_devices_last_seen", "devices", ["last_seen"])
op.create_index("ix_device_save_sync_save_id", "device_save_sync", ["save_id"])
op.create_index("ix_saves_save_name", "saves", ["save_name"])
op.create_index("ix_saves_slot", "saves", ["slot"])
op.create_index(
"ix_saves_rom_user_hash", "saves", ["rom_id", "user_id", "content_hash"]
)
def downgrade():
op.drop_index("ix_saves_save_name", "saves")
op.drop_index("ix_saves_rom_user_hash", "saves")
op.drop_index("ix_saves_slot", "saves")
op.drop_index("ix_device_save_sync_save_id", "device_save_sync")
op.drop_index("ix_devices_last_seen", "devices")
op.drop_index("ix_devices_user_id", "devices")
with op.batch_alter_table("saves", schema=None) as batch_op:
batch_op.drop_column("save_name")
batch_op.drop_column("content_hash")
batch_op.drop_column("slot")
op.drop_table("device_save_sync")
op.drop_table("devices")

View File

@@ -32,11 +32,23 @@ class ScreenshotSchema(BaseAsset):
class SaveSchema(BaseAsset):
emulator: str | None
save_name: str | None = None
slot: str | None = None
content_hash: str | None = None
screenshot: ScreenshotSchema | None
device_syncs: list[DeviceSyncSchema] = []
class SlotSummarySchema(BaseModel):
slot: str | None
count: int
latest: SaveSchema
class SaveSummarySchema(BaseModel):
total_count: int
slots: list[SlotSummarySchema]
class StateSchema(BaseAsset):
emulator: str | None
screenshot: ScreenshotSchema | None

View File

@@ -1,3 +1,5 @@
import os
import re
from datetime import datetime, timezone
from typing import Annotated
@@ -5,7 +7,7 @@ from fastapi import Body, HTTPException, Request, UploadFile, status
from fastapi.responses import FileResponse
from decorators.auth import protected_route
from endpoints.responses.assets import SaveSchema
from endpoints.responses.assets import SaveSchema, SaveSummarySchema, SlotSummarySchema
from endpoints.responses.device import DeviceSyncSchema
from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException
from handler.auth.constants import Scope
@@ -41,14 +43,21 @@ def _build_save_schema(
device_syncs: list[DeviceSyncSchema] = []
if device:
last_synced = sync.last_synced_at if sync else save.updated_at
is_current = _to_utc(last_synced) >= _to_utc(save.updated_at)
if sync:
is_current = _to_utc(sync.last_synced_at) >= _to_utc(save.updated_at)
last_synced = sync.last_synced_at
is_untracked = sync.is_untracked
else:
is_current = False
last_synced = save.updated_at
is_untracked = False
device_syncs.append(
DeviceSyncSchema(
device_id=device.id,
device_name=device.name,
last_synced_at=last_synced,
is_untracked=sync.is_untracked if sync else False,
is_untracked=is_untracked,
is_current=is_current,
)
)
@@ -62,6 +71,40 @@ def _build_save_schema(
return SaveSchema.model_validate(save_data)
DATETIME_TAG_PATTERN = re.compile(r" \[\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\]")
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
router = APIRouter(
prefix="/saves",
tags=["saves"],
@@ -73,23 +116,16 @@ async def add_save(
request: Request,
rom_id: int,
emulator: str | None = None,
save_name: str | None = None,
slot: str | None = None,
device_id: str | None = None,
overwrite: bool = False,
autocleanup: bool = False,
autocleanup_limit: int = 10,
) -> SaveSchema:
if device_id and Scope.DEVICES_WRITE not in request.auth.scopes:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
device = None
if device_id:
device = db_device_handler.get_device(
device_id=device_id, user_id=request.user.id
)
if not device:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device with ID {device_id} not found",
)
"""Upload a save file for a ROM."""
device = _resolve_device(
device_id, request.user.id, request.auth.scopes, Scope.DEVICES_WRITE
)
data = await request.form()
@@ -111,28 +147,45 @@ async def add_save(
status_code=status.HTTP_400_BAD_REQUEST, detail="Save file has no filename"
)
actual_filename = saveFile.filename
if slot:
actual_filename = _apply_datetime_tag(saveFile.filename)
db_save = db_save_handler.get_save_by_filename(
user_id=request.user.id, rom_id=rom.id, file_name=saveFile.filename
user_id=request.user.id, rom_id=rom.id, file_name=actual_filename
)
if device and db_save and not overwrite:
if device and slot and not overwrite:
slot_saves = db_save_handler.get_saves(
user_id=request.user.id,
rom_id=rom.id,
slot=slot,
order_by_updated_at_desc=True,
)
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 sync.last_synced_at < db_save.updated_at:
if sync and _to_utc(sync.last_synced_at) < _to_utc(db_save.updated_at):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail={
"error": "conflict",
"message": "Save has been updated since last sync",
"save_id": db_save.id,
"current_save_time": db_save.updated_at.isoformat(),
"device_sync_time": sync.last_synced_at.isoformat(),
},
detail="Save has been updated since your last sync",
)
log.info(
f"Uploading save {hl(saveFile.filename)} for {hl(str(rom.name), color=BLUE)}"
f"Uploading save {hl(actual_filename)} for {hl(str(rom.name), color=BLUE)}"
)
saves_path = fs_asset_handler.build_saves_file_path(
@@ -142,29 +195,49 @@ async def add_save(
emulator=emulator,
)
await fs_asset_handler.write_file(file=saveFile, path=saves_path)
await fs_asset_handler.write_file(
file=saveFile, path=saves_path, filename=actual_filename
)
scanned_save = await scan_save(
file_name=saveFile.filename,
file_name=actual_filename,
user=request.user,
platform_fs_slug=rom.platform.fs_slug,
rom_id=rom_id,
emulator=emulator,
)
if db_save:
db_save = db_save_handler.update_save(
db_save.id,
{
"file_size_bytes": scanned_save.file_size_bytes,
"save_name": save_name or db_save.save_name,
},
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,
)
if existing_by_hash:
try:
await fs_asset_handler.remove_file(f"{saves_path}/{actual_filename}")
except FileNotFoundError:
pass
sync = None
if device:
sync = db_device_save_sync_handler.get_sync(
device_id=device.id, save_id=existing_by_hash.id
)
return _build_save_schema(existing_by_hash, device, sync)
if db_save:
update_data: dict = {
"file_size_bytes": scanned_save.file_size_bytes,
"content_hash": scanned_save.content_hash,
}
if slot is not None:
update_data["slot"] = slot
db_save = db_save_handler.update_save(db_save.id, update_data)
else:
scanned_save.rom_id = rom.id
scanned_save.user_id = request.user.id
scanned_save.emulator = emulator
scanned_save.save_name = save_name
scanned_save.slot = slot
db_save = db_save_handler.add_save(save=scanned_save)
if device:
@@ -173,6 +246,21 @@ async def add_save(
)
db_device_handler.update_last_seen(device_id=device.id, user_id=request.user.id)
if slot and autocleanup:
slot_saves = db_save_handler.get_saves(
user_id=request.user.id,
rom_id=rom.id,
slot=slot,
order_by_updated_at_desc=True,
)
if len(slot_saves) > autocleanup_limit:
for old_save in slot_saves[autocleanup_limit:]:
db_save_handler.delete_save(old_save.id)
try:
await fs_asset_handler.remove_file(old_save.full_path)
except FileNotFoundError:
log.warning(f"Could not delete old save file: {old_save.full_path}")
screenshotFile: UploadFile | None = data.get("screenshotFile", None) # type: ignore
if screenshotFile and screenshotFile.filename:
screenshots_path = fs_asset_handler.build_screenshots_file_path(
@@ -223,23 +311,15 @@ def get_saves(
rom_id: int | None = None,
platform_id: int | None = None,
device_id: str | None = None,
slot: str | None = None,
) -> list[SaveSchema]:
if device_id and Scope.DEVICES_READ not in request.auth.scopes:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
device = None
if device_id:
device = db_device_handler.get_device(
device_id=device_id, user_id=request.user.id
)
if not device:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device with ID {device_id} not found",
)
"""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_id=rom_id, platform_id=platform_id
user_id=request.user.id, rom_id=rom_id, platform_id=platform_id, slot=slot
)
if not device:
@@ -256,17 +336,8 @@ def get_saves(
@protected_route(router.get, "/identifiers", [Scope.ASSETS_READ])
def get_save_identifiers(
request: Request,
) -> list[int]:
"""Get save identifiers endpoint
Args:
request (Request): Fastapi Request object
Returns:
list[int]: List of save IDs
"""
def get_save_identifiers(request: Request) -> list[int]:
"""Retrieve save identifiers."""
saves = db_save_handler.get_saves(
user_id=request.user.id,
only_fields=[Save.id],
@@ -275,21 +346,31 @@ def get_save_identifiers(
return [save.id for save in saves]
@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:
if device_id and Scope.DEVICES_READ not in request.auth.scopes:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
device = None
if device_id:
device = db_device_handler.get_device(
device_id=device_id, user_id=request.user.id
)
if not device:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device with ID {device_id} not found",
)
"""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:
@@ -313,19 +394,10 @@ def download_save(
device_id: str | None = None,
optimistic: bool = True,
) -> FileResponse:
if device_id and Scope.DEVICES_READ not in request.auth.scopes:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
device = None
if device_id:
device = db_device_handler.get_device(
device_id=device_id, user_id=request.user.id
)
if not device:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device with ID {device_id} not found",
)
"""Download a save file."""
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:
@@ -365,7 +437,7 @@ def confirm_download(
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(
@@ -373,12 +445,8 @@ def confirm_download(
detail=f"Save with ID {id} not found",
)
device = db_device_handler.get_device(device_id=device_id, user_id=request.user.id)
if not device:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device with ID {device_id} not found",
)
device = _resolve_device(device_id, request.user.id)
assert device is not None
sync = db_device_save_sync_handler.upsert_sync(
device_id=device_id,
@@ -392,6 +460,7 @@ def confirm_download(
@protected_route(router.put, "/{id}", [Scope.ASSETS_WRITE])
async def update_save(request: Request, id: int) -> SaveSchema:
"""Update a save file."""
data = await request.form()
db_save = db_save_handler.get_save(user_id=request.user.id, id=id)
@@ -514,7 +583,7 @@ def track_save(
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(
@@ -522,12 +591,8 @@ def track_save(
detail=f"Save with ID {id} not found",
)
device = db_device_handler.get_device(device_id=device_id, user_id=request.user.id)
if not device:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device with ID {device_id} not found",
)
device = _resolve_device(device_id, request.user.id)
assert device is not None
sync = db_device_save_sync_handler.set_untracked(
device_id=device_id, save_id=id, untracked=False
@@ -542,7 +607,7 @@ def untrack_save(
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(
@@ -550,12 +615,8 @@ def untrack_save(
detail=f"Save with ID {id} not found",
)
device = db_device_handler.get_device(device_id=device_id, user_id=request.user.id)
if not device:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device with ID {device_id} not found",
)
device = _resolve_device(device_id, request.user.id)
assert device is not None
sync = db_device_save_sync_handler.set_untracked(
device_id=device_id, save_id=id, untracked=True

View File

@@ -1,6 +1,6 @@
from collections.abc import Sequence
from sqlalchemy import and_, delete, select, update
from sqlalchemy import and_, delete, desc, select, update
from sqlalchemy.orm import QueryableAttribute, Session, load_only
from decorators.database import begin_session
@@ -42,12 +42,28 @@ class DBSavesHandler(DBBaseHandler):
.limit(1)
).first()
@begin_session
def get_save_by_content_hash(
self,
user_id: int,
rom_id: int,
content_hash: str,
session: Session = None, # type: ignore
) -> Save | None:
return session.scalar(
select(Save)
.filter_by(rom_id=rom_id, user_id=user_id, content_hash=content_hash)
.limit(1)
)
@begin_session
def get_saves(
self,
user_id: int,
rom_id: int | None = None,
platform_id: int | None = None,
slot: str | None = None,
order_by_updated_at_desc: bool = False,
only_fields: Sequence[QueryableAttribute] | None = None,
session: Session = None, # type: ignore
) -> Sequence[Save]:
@@ -61,6 +77,12 @@ class DBSavesHandler(DBBaseHandler):
Rom.platform_id == platform_id
)
if slot is not None:
query = query.filter(Save.slot == slot)
if order_by_updated_at_desc:
query = query.order_by(desc(Save.updated_at))
if only_fields:
query = query.options(load_only(*only_fields))
@@ -125,3 +147,28 @@ class DBSavesHandler(DBBaseHandler):
)
return missing_saves
@begin_session
def get_saves_summary(
self,
user_id: int,
rom_id: int,
session: Session = None, # type: ignore
) -> dict:
saves = session.scalars(
select(Save)
.filter_by(user_id=user_id, rom_id=rom_id)
.order_by(desc(Save.updated_at))
).all()
slots_data: dict[str | None, dict] = {}
for save in saves:
slot_key = save.slot
if slot_key not in slots_data:
slots_data[slot_key] = {"slot": slot_key, "count": 0, "latest": save}
slots_data[slot_key]["count"] += 1
return {
"total_count": len(saves),
"slots": list(slots_data.values()),
}

View File

@@ -1,9 +1,12 @@
import asyncio
import enum
import hashlib
import zipfile
from typing import Any
import socketio # type: ignore
from config import ASSETS_BASE_PATH
from config.config_manager import config_manager as cm
from endpoints.responses.rom import SimpleRomSchema
from handler.database import db_platform_handler, db_rom_handler
@@ -817,11 +820,41 @@ async def scan_rom(
return Rom(**rom_attrs)
async def _scan_asset(file_name: str, asset_path: str):
def _compute_file_hash(file_path: str) -> str:
hash_obj = hashlib.md5(usedforsecurity=False)
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
hash_obj.update(chunk)
return hash_obj.hexdigest()
def _compute_zip_hash(zip_path: str) -> str:
with zipfile.ZipFile(zip_path, "r") as zf:
file_hashes = []
for name in sorted(zf.namelist()):
if not name.endswith("/"):
content = zf.read(name)
file_hash = hashlib.md5(content, usedforsecurity=False).hexdigest()
file_hashes.append(f"{name}:{file_hash}")
combined = "\n".join(file_hashes)
return hashlib.md5(combined.encode(), usedforsecurity=False).hexdigest()
def _compute_content_hash(file_path: str) -> str | None:
try:
if zipfile.is_zipfile(file_path):
return _compute_zip_hash(file_path)
return _compute_file_hash(file_path)
except Exception as e:
log.debug(f"Failed to compute content hash for {file_path}: {e}")
return None
async def _scan_asset(file_name: str, asset_path: str, compute_hash: bool = False):
file_path = f"{asset_path}/{file_name}"
file_size = await fs_asset_handler.get_file_size(file_path)
return {
result = {
"file_path": asset_path,
"file_name": file_name,
"file_name_no_tags": fs_asset_handler.get_file_name_with_no_tags(file_name),
@@ -830,6 +863,12 @@ async def _scan_asset(file_name: str, asset_path: str):
"file_size_bytes": file_size,
}
if compute_hash:
absolute_path = f"{ASSETS_BASE_PATH}/{file_path}"
result["content_hash"] = _compute_content_hash(absolute_path)
return result
async def scan_save(
file_name: str,
@@ -841,7 +880,7 @@ async def scan_save(
saves_path = fs_asset_handler.build_saves_file_path(
user=user, platform_fs_slug=platform_fs_slug, rom_id=rom_id, emulator=emulator
)
scanned_asset = await _scan_asset(file_name, saves_path)
scanned_asset = await _scan_asset(file_name, saves_path, compute_hash=True)
return Save(**scanned_asset)

View File

@@ -55,7 +55,8 @@ class Save(RomAsset):
__table_args__ = {"extend_existing": True}
emulator: Mapped[str | None] = mapped_column(String(length=50))
save_name: Mapped[str | None] = mapped_column(String(length=255))
slot: Mapped[str | None] = mapped_column(String(length=255))
content_hash: Mapped[str | None] = mapped_column(String(length=32))
rom: Mapped[Rom] = relationship(lazy="joined", back_populates="saves")
user: Mapped[User] = relationship(lazy="joined", back_populates="saves")

File diff suppressed because it is too large Load Diff

View File

@@ -166,3 +166,268 @@ class TestDBSavesHandlerPlatformFiltering:
# Verify the save is associated with the correct platform through ROM
assert retrieved_save.rom.platform_id == platform.id
class TestDBSavesHandlerSlotFiltering:
def test_get_saves_with_slot_filter(self, admin_user: User, rom: Rom):
save1 = Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="slot_test_1.sav",
file_name_no_tags="slot_test_1",
file_name_no_ext="slot_test_1",
file_extension="sav",
emulator="test_emu",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot="Slot A",
)
save2 = Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="slot_test_2.sav",
file_name_no_tags="slot_test_2",
file_name_no_ext="slot_test_2",
file_extension="sav",
emulator="test_emu",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot="Slot A",
)
save3 = Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="slot_test_3.sav",
file_name_no_tags="slot_test_3",
file_name_no_ext="slot_test_3",
file_extension="sav",
emulator="test_emu",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot="Slot B",
)
db_save_handler.add_save(save1)
db_save_handler.add_save(save2)
db_save_handler.add_save(save3)
slot_a_saves = db_save_handler.get_saves(
user_id=admin_user.id, rom_id=rom.id, slot="Slot A"
)
assert len(slot_a_saves) == 2
assert all(s.slot == "Slot A" for s in slot_a_saves)
slot_b_saves = db_save_handler.get_saves(
user_id=admin_user.id, rom_id=rom.id, slot="Slot B"
)
assert len(slot_b_saves) == 1
assert slot_b_saves[0].slot == "Slot B"
def test_get_saves_with_null_slot_filter(self, admin_user: User, rom: Rom):
save_with_slot = Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="with_slot.sav",
file_name_no_tags="with_slot",
file_name_no_ext="with_slot",
file_extension="sav",
emulator="test_emu",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot="Main",
)
save_without_slot = Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="without_slot.sav",
file_name_no_tags="without_slot",
file_name_no_ext="without_slot",
file_extension="sav",
emulator="test_emu",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot=None,
)
db_save_handler.add_save(save_with_slot)
db_save_handler.add_save(save_without_slot)
all_saves = db_save_handler.get_saves(user_id=admin_user.id, rom_id=rom.id)
assert len(all_saves) >= 2
def test_get_saves_order_by_updated_at_desc(self, admin_user: User, rom: Rom):
from datetime import datetime, timedelta, timezone
base_time = datetime.now(timezone.utc)
save1 = Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="order_test_1.sav",
file_name_no_tags="order_test_1",
file_name_no_ext="order_test_1",
file_extension="sav",
emulator="test_emu",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot="order_test",
)
save2 = Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="order_test_2.sav",
file_name_no_tags="order_test_2",
file_name_no_ext="order_test_2",
file_extension="sav",
emulator="test_emu",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot="order_test",
)
created1 = db_save_handler.add_save(save1)
created2 = db_save_handler.add_save(save2)
db_save_handler.update_save(
created1.id, {"updated_at": base_time - timedelta(hours=2)}
)
db_save_handler.update_save(
created2.id, {"updated_at": base_time - timedelta(hours=1)}
)
ordered_saves = db_save_handler.get_saves(
user_id=admin_user.id,
rom_id=rom.id,
slot="order_test",
order_by_updated_at_desc=True,
)
assert len(ordered_saves) == 2
assert ordered_saves[0].id == created2.id
assert ordered_saves[1].id == created1.id
class TestDBSavesHandlerSummary:
def test_get_saves_summary_basic(self, admin_user: User, rom: Rom):
from datetime import datetime, timedelta, timezone
base_time = datetime.now(timezone.utc)
configs = [
("summary_a_1.sav", "Slot A", -3),
("summary_a_2.sav", "Slot A", -1),
("summary_b_1.sav", "Slot B", -2),
("summary_none_1.sav", None, -4),
]
for filename, slot, hours_offset in configs:
save = Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name=filename,
file_name_no_tags=filename.replace(".sav", ""),
file_name_no_ext=filename.replace(".sav", ""),
file_extension="sav",
emulator="test_emu",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot=slot,
)
created = db_save_handler.add_save(save)
db_save_handler.update_save(
created.id, {"updated_at": base_time + timedelta(hours=hours_offset)}
)
summary = db_save_handler.get_saves_summary(
user_id=admin_user.id, rom_id=rom.id
)
assert "total_count" in summary
assert "slots" in summary
assert summary["total_count"] == 4
assert len(summary["slots"]) == 3
def test_get_saves_summary_latest_per_slot(self, admin_user: User, rom: Rom):
from datetime import datetime, timedelta, timezone
base_time = datetime.now(timezone.utc)
old_save = Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="latest_test_old.sav",
file_name_no_tags="latest_test_old",
file_name_no_ext="latest_test_old",
file_extension="sav",
emulator="test_emu",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot="latest_test",
)
new_save = Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name="latest_test_new.sav",
file_name_no_tags="latest_test_new",
file_name_no_ext="latest_test_new",
file_extension="sav",
emulator="test_emu",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot="latest_test",
)
old_created = db_save_handler.add_save(old_save)
new_created = db_save_handler.add_save(new_save)
db_save_handler.update_save(
old_created.id, {"updated_at": base_time - timedelta(hours=5)}
)
db_save_handler.update_save(
new_created.id, {"updated_at": base_time - timedelta(hours=1)}
)
summary = db_save_handler.get_saves_summary(
user_id=admin_user.id, rom_id=rom.id
)
latest_slot = next(
(s for s in summary["slots"] if s["slot"] == "latest_test"), None
)
assert latest_slot is not None
assert latest_slot["count"] == 2
assert latest_slot["latest"].file_name == "latest_test_new.sav"
def test_get_saves_summary_empty_rom(self, admin_user: User):
summary = db_save_handler.get_saves_summary(
user_id=admin_user.id, rom_id=999999
)
assert summary["total_count"] == 0
assert summary["slots"] == []
def test_get_saves_summary_count_accuracy(self, admin_user: User, rom: Rom):
for i in range(5):
save = Save(
rom_id=rom.id,
user_id=admin_user.id,
file_name=f"count_test_{i}.sav",
file_name_no_tags=f"count_test_{i}",
file_name_no_ext=f"count_test_{i}",
file_extension="sav",
emulator="test_emu",
file_path=f"{rom.platform_slug}/saves",
file_size_bytes=100,
slot="count_test",
)
db_save_handler.add_save(save)
summary = db_save_handler.get_saves_summary(
user_id=admin_user.id, rom_id=rom.id
)
count_slot = next(
(s for s in summary["slots"] if s["slot"] == "count_test"), None
)
assert count_slot is not None
assert count_slot["count"] == 5