diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index 846d91e48..2193e840f 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -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) diff --git a/backend/handler/streaming/saves.py b/backend/handler/streaming/saves.py index 9eeaf62ec..68860c361 100644 --- a/backend/handler/streaming/saves.py +++ b/backend/handler/streaming/saves.py @@ -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( diff --git a/backend/tests/endpoints/test_saves.py b/backend/tests/endpoints/test_saves.py index c3ebb42cc..f1f126924 100644 --- a/backend/tests/endpoints/test_saves.py +++ b/backend/tests/endpoints/test_saves.py @@ -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" diff --git a/backend/utils/memory_cards.py b/backend/utils/memory_cards.py index d66b1ee03..55a0a7e2f 100644 --- a/backend/utils/memory_cards.py +++ b/backend/utils/memory_cards.py @@ -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 ) diff --git a/frontend/src/console/views/Play.vue b/frontend/src/console/views/Play.vue index f4ae38417..db77e6560 100644 --- a/frontend/src/console/views/Play.vue +++ b/frontend/src/console/views/Play.vue @@ -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, diff --git a/frontend/src/services/api/state.test.ts b/frontend/src/services/api/state.test.ts new file mode 100644 index 000000000..29d5bde92 --- /dev/null +++ b/frontend/src/services/api/state.test.ts @@ -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]", + ); + }); +}); diff --git a/frontend/src/services/api/state.ts b/frontend/src/services/api/state.ts index ef9783529..e49203e3d 100644 --- a/frontend/src/services/api/state.ts +++ b/frontend/src/services/api/state.ts @@ -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. */