fix(saves): stamp save and state file names with local time

State names were built with toISOString() in the browser, and save,
streaming save and memory card names with datetime.now(timezone.utc) on
the server, so every timestamp in an asset's file name was UTC. States
now use the browser's local time and server-named assets use the
server's local time (the container's TZ). Matching and ordering read the
stored file_name and the DB timestamps, so existing files are unaffected.

Fixes #4726

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-26 13:58:54 -04:00
parent 9c1e6b2d86
commit b6c03e79eb
7 changed files with 68 additions and 17 deletions

View File

@@ -120,7 +120,7 @@ def _slot_retention(autocleanup: bool, autocleanup_limit: int) -> int | 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")
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
if DATETIME_TAG_PATTERN.search(name):
name = DATETIME_TAG_PATTERN.sub("", name)

View File

@@ -9,7 +9,7 @@ a .zip extension so the whole card set travels as a unit.
import asyncio
import secrets
import time
from datetime import datetime, timezone
from datetime import datetime
from typing import NamedTuple
from fastapi import HTTPException
@@ -151,7 +151,7 @@ async def store_save_asset(user: User, rom: Rom, emulator: str, content: bytes)
history of save snapshots rather than overwriting. Identical content is
deduplicated by hash so idle exits do not pile up copies.
"""
ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H-%M-%S")
ts = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
filename = sanitize_filename(f"{rom.fs_name_no_ext} [{emulator} {ts}].saves.zip")
saves_path = fs_asset_handler.build_saves_file_path(

View File

@@ -1,5 +1,7 @@
import os
import re
import time
from collections.abc import Iterator
from datetime import datetime, timedelta, timezone
from io import BytesIO
from pathlib import Path
@@ -10,6 +12,7 @@ from fastapi import status
from sqlalchemy import update
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
from endpoints.saves import _apply_datetime_tag
from handler.auth import oauth_handler
from handler.auth.constants import Scope
from handler.database import (
@@ -4135,3 +4138,27 @@ class TestSaveRename:
assert response.status_code == status.HTTP_404_NOT_FOUND
assert save_file.exists()
class TestApplyDatetimeTag:
@pytest.fixture
def sao_paulo_tz(self, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
monkeypatch.setenv("TZ", "America/Sao_Paulo")
time.tzset()
yield
monkeypatch.undo()
time.tzset()
@pytest.mark.usefixtures("sao_paulo_tz")
def test_stamps_the_server_local_time(self):
captured_at = datetime(2026, 9, 22, 22, 10, 13, tzinfo=timezone.utc)
class FrozenDatetime(datetime):
@classmethod
def now(cls, tz=None):
return datetime.fromtimestamp(captured_at.timestamp(), tz)
with mock.patch("endpoints.saves.datetime", FrozenDatetime):
tagged = _apply_datetime_tag("suikoden [2020-01-01_00-00-00].srm")
assert tagged == "suikoden [2026-09-22_19-10-13].srm"

View File

@@ -177,7 +177,7 @@ async def store_memory_card_version(
)
return None
ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H-%M-%S-%f")[:-3]
ts = datetime.now().strftime("%Y-%m-%d %H-%M-%S-%f")[:-3]
cards_path = fs_asset_handler.build_memory_cards_file_path(
user=user, emulator=card.emulator, card_id=card.id
)

View File

@@ -231,14 +231,9 @@ async function uploadState(
screenshotFile: ArrayBuffer,
) {
if (!romRef.value) return;
const filename = `${romRef.value.fs_name_no_ext.trim()} [${new Date()
.toISOString()
.replace(/[:.]/g, "-")
.replace("T", " ")
.replace("Z", "")}]`;
try {
const stateApi = await import("@/services/api/state");
const filename = stateApi.sessionStateName(romRef.value, new Date());
const uploadedStates = await stateApi.default.uploadStates({
rom: romRef.value,

View File

@@ -0,0 +1,30 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { sessionStateName } from "@/services/api/state";
describe("sessionStateName", () => {
const originalTZ = process.env.TZ;
beforeEach(() => {
process.env.TZ = "America/Sao_Paulo";
});
afterEach(() => {
process.env.TZ = originalTZ;
});
it("stamps the name with the local time of the capture", () => {
const capturedAt = new Date(Date.UTC(2026, 8, 22, 22, 10, 13, 849));
expect(sessionStateName({ fs_name_no_ext: "suikoden " }, capturedAt)).toBe(
"suikoden [2026-09-22 19-10-13-849]",
);
});
it("zero-pads every component", () => {
const capturedAt = new Date(Date.UTC(2026, 0, 2, 6, 4, 5, 7));
expect(sessionStateName({ fs_name_no_ext: "game" }, capturedAt)).toBe(
"game [2026-01-02 03-04-05-007]",
);
});
});

View File

@@ -9,17 +9,16 @@ import { buildFormInput } from "@/utils/formData";
export const stateApi = api;
/** States are named after the ROM and the moment the core was serialized. */
/** States are named after the ROM and the local time the core was serialized. */
export function sessionStateName(
rom: { fs_name_no_ext: string },
capturedAt: Date,
): string {
const timestamp = capturedAt
.toISOString()
.replace(/[:.]/g, "-")
.replace("T", " ")
.replace("Z", "");
return `${rom.fs_name_no_ext.trim()} [${timestamp}]`;
const pad = (value: number, length = 2) =>
String(value).padStart(length, "0");
const date = `${capturedAt.getFullYear()}-${pad(capturedAt.getMonth() + 1)}-${pad(capturedAt.getDate())}`;
const time = `${pad(capturedAt.getHours())}-${pad(capturedAt.getMinutes())}-${pad(capturedAt.getSeconds())}-${pad(capturedAt.getMilliseconds(), 3)}`;
return `${rom.fs_name_no_ext.trim()} [${date} ${time}]`;
}
/** A state and its picture, both named after the moment of the capture. */