diff --git a/backend/handler/play_session_handler.py b/backend/handler/play_session_handler.py index 5ae356e21..1bfd0b891 100644 --- a/backend/handler/play_session_handler.py +++ b/backend/handler/play_session_handler.py @@ -6,6 +6,7 @@ from pydash import compact from handler.database import db_device_handler, db_play_session_handler, db_rom_handler from logger.logger import log from models.play_session import PlaySession +from models.rom import RomUserStatus from utils.datetime import to_utc @@ -37,7 +38,7 @@ def _resolve_device(device_id: str | None, user_id: int) -> str | None: return device_id if device is not None else None -def _update_rom_user_last_played( +def _apply_play_to_rom_user( rom_user_updates: dict[int, datetime], user_id: int ) -> None: for rom_id, latest_end_time in rom_user_updates.items(): @@ -46,10 +47,18 @@ def _update_rom_user_last_played( rom_user = db_rom_handler.add_rom_user(rom_id=rom_id, user_id=user_id) current = to_utc(rom_user.last_played) if rom_user.last_played else None - if current is None or latest_end_time > current: - db_rom_handler.update_rom_user( - rom_user.id, {"last_played": latest_end_time} - ) + # Only the newest play advances state. A backfilled or device-synced + # older session must not resurrect "now playing" or rewind the status. + if current is not None and latest_end_time <= current: + continue + + updates: dict = {"last_played": latest_end_time, "now_playing": True} + # Playing again counts as active: rewind an empty or "finished" status + # to "incomplete", but leave statuses the user set on purpose + # (completed_100 / retired / never_playing) untouched. + if rom_user.status in (None, RomUserStatus.FINISHED): + updates["status"] = RomUserStatus.INCOMPLETE + db_rom_handler.update_rom_user(rom_user.id, updates) def ingest_play_sessions( @@ -138,7 +147,7 @@ def ingest_play_sessions( rom_user_updates[resolved_rom_id] = ps.end_time # Phase 4: Side effects - _update_rom_user_last_played(rom_user_updates, user_id) + _apply_play_to_rom_user(rom_user_updates, user_id) if resolved_device_id is not None: db_device_handler.update_last_seen( diff --git a/backend/tests/endpoints/test_play_sessions.py b/backend/tests/endpoints/test_play_sessions.py index cdc39b345..0a1ca83af 100644 --- a/backend/tests/endpoints/test_play_sessions.py +++ b/backend/tests/endpoints/test_play_sessions.py @@ -11,7 +11,7 @@ from handler.auth import oauth_handler from handler.database import db_device_handler, db_play_session_handler, db_rom_handler from models.device import Device from models.platform import Platform -from models.rom import Rom +from models.rom import Rom, RomUserStatus from models.user import User from utils.datetime import to_utc @@ -68,6 +68,14 @@ def _ingest(device_id=None, sessions=None): return {"device_id": device_id, "sessions": sessions or []} +def _prime_rom_user(rom_id, user_id, **fields): + """Fetch (or create) the rom_user and seed it with the given fields.""" + rom_user = db_rom_handler.get_rom_user(rom_id=rom_id, user_id=user_id) + if rom_user is None: + rom_user = db_rom_handler.add_rom_user(rom_id=rom_id, user_id=user_id) + return db_rom_handler.update_rom_user(rom_user.id, fields) + + class TestPlaySessionIngest: def test_single_session(self, client, access_token: str, device: Device, rom: Rom): payload = _ingest(device_id=device.id, sessions=[_session(rom_id=rom.id)]) @@ -472,6 +480,96 @@ class TestPlaySessionRomUserUpdates: last_played_utc = to_utc(rom_user.last_played) assert abs((last_played_utc - expected_latest).total_seconds()) < 2 + def test_now_playing_set_on_ingest( + self, client, access_token: str, admin_user: User, rom: Rom + ): + payload = _ingest(sessions=[_session(rom_id=rom.id)]) + client.post( + "/api/play-sessions", + json=payload, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user is not None + assert rom_user.now_playing is True + + def test_empty_status_rewound_to_incomplete( + self, client, access_token: str, admin_user: User, rom: Rom + ): + client.post( + "/api/play-sessions", + json=_ingest(sessions=[_session(rom_id=rom.id)]), + headers={"Authorization": f"Bearer {access_token}"}, + ) + + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user.status == RomUserStatus.INCOMPLETE + + def test_finished_status_rewound_to_incomplete( + self, client, access_token: str, admin_user: User, rom: Rom + ): + _prime_rom_user(rom.id, admin_user.id, status=RomUserStatus.FINISHED) + + client.post( + "/api/play-sessions", + json=_ingest(sessions=[_session(rom_id=rom.id)]), + headers={"Authorization": f"Bearer {access_token}"}, + ) + + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user.status == RomUserStatus.INCOMPLETE + + @pytest.mark.parametrize( + "protected_status", + [ + RomUserStatus.COMPLETED_100, + RomUserStatus.RETIRED, + RomUserStatus.NEVER_PLAYING, + ], + ) + def test_deliberate_status_preserved( + self, client, access_token, admin_user, rom, protected_status + ): + _prime_rom_user(rom.id, admin_user.id, status=protected_status) + + client.post( + "/api/play-sessions", + json=_ingest(sessions=[_session(rom_id=rom.id)]), + headers={"Authorization": f"Bearer {access_token}"}, + ) + + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + # now_playing is orthogonal, so it still flips on... + assert rom_user.now_playing is True + # ...but the deliberate enum status is left untouched. + assert rom_user.status == protected_status + + def test_older_session_does_not_resurrect_now_playing( + self, client, access_token: str, admin_user: User, rom: Rom + ): + # A recent play sets last_played and now_playing. + client.post( + "/api/play-sessions", + json=_ingest(sessions=[_session(rom_id=rom.id, start_offset_hours=-1)]), + headers={"Authorization": f"Bearer {access_token}"}, + ) + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + db_rom_handler.update_rom_user( + rom_user.id, {"now_playing": False, "status": RomUserStatus.FINISHED} + ) + + # Backfilling an older session must not advance state. + client.post( + "/api/play-sessions", + json=_ingest(sessions=[_session(rom_id=rom.id, start_offset_hours=-10)]), + headers={"Authorization": f"Bearer {access_token}"}, + ) + + rom_user = db_rom_handler.get_rom_user(rom_id=rom.id, user_id=admin_user.id) + assert rom_user.now_playing is False + assert rom_user.status == RomUserStatus.FINISHED + def test_rom_user_created_if_not_exists( self, client, access_token: str, admin_user: User, platform: Platform ): diff --git a/frontend/src/composables/useUISettings.ts b/frontend/src/composables/useUISettings.ts index 3304635a5..a0b55811d 100644 --- a/frontend/src/composables/useUISettings.ts +++ b/frontend/src/composables/useUISettings.ts @@ -15,8 +15,7 @@ export const UI_SETTINGS_KEYS = { // NOTE: uiVersion is intentionally NOT tracked here. It's owned by the // singleton in composables/useUiVersion.ts so a write propagates reactively - // to the RomM.vue gate without a reload. When v2 graduates we can move it - // into this map and pick up backend sync. + // to the RomM.vue gate without a reload. // Home section showStats: { key: "settings.showStats", default: true }, @@ -80,6 +79,12 @@ export const UI_SETTINGS_KEYS = { default: false, }, boxartStyle: { key: "settings.boxartStyle", default: "cover_path" }, + + // Gameplay + confirmProtectedLaunch: { + key: "settings.confirmProtectedLaunch", + default: true, + }, } as const; export type UISettingsKey = keyof typeof UI_SETTINGS_KEYS; diff --git a/frontend/src/locales/bg_BG/rom.json b/frontend/src/locales/bg_BG/rom.json index eba52515a..b8d8775f0 100644 --- a/frontend/src/locales/bg_BG/rom.json +++ b/frontend/src/locales/bg_BG/rom.json @@ -59,6 +59,8 @@ "completion": "Завършеност", "completionist": "Перфекционист", "confirm-delete-note": "Сигурен ли си, че искаш да изтриеш бележката \"{title}\"?", + "confirm-launch-protected-body": "Отбелязахте „{name}“ като {status}. Искате ли все пак да я играете?", + "confirm-launch-protected-title": "Стартиране на тази игра?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Копирай линк за сваляне", diff --git a/frontend/src/locales/bg_BG/settings.json b/frontend/src/locales/bg_BG/settings.json index e2f9632e1..766d1ec10 100644 --- a/frontend/src/locales/bg_BG/settings.json +++ b/frontend/src/locales/bg_BG/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Конфигурация", "confirm-delete-mapping": "Потвърди?", + "confirm-protected-launch": "Потвърждаване при стартиране на архивирани игри", + "confirm-protected-launch-desc": "Питане преди стартиране на игра, отбелязана като „Изоставена“ или „Неиграна никога“.", "continue-playing-as-grid": "Продължи игра като решетка", "continue-playing-as-grid-desc": "Показвай кориците за продължаване на игра като решетка на началната страница", "controller-debug": "Диагностика на контролера", @@ -161,6 +163,7 @@ "folder-name": "Име на папка", "folder-name-header": "Име на папка", "gallery": "Галерия", + "gameplay": "Геймплей", "games-label": "Игри", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/cs_CZ/rom.json b/frontend/src/locales/cs_CZ/rom.json index 43c3327b2..9c96f8615 100644 --- a/frontend/src/locales/cs_CZ/rom.json +++ b/frontend/src/locales/cs_CZ/rom.json @@ -59,6 +59,8 @@ "completion": "Dokončení", "completionist": "Kompletista", "confirm-delete-note": "Opravdu chcete smazat poznámku \"{title}\"?", + "confirm-launch-protected-body": "Označili jste „{name}“ jako {status}. Přesto ji chcete hrát?", + "confirm-launch-protected-title": "Spustit tuto hru?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Kopírovat odkaz ke stažení", diff --git a/frontend/src/locales/cs_CZ/settings.json b/frontend/src/locales/cs_CZ/settings.json index 8f1b61e71..01cc8abf1 100644 --- a/frontend/src/locales/cs_CZ/settings.json +++ b/frontend/src/locales/cs_CZ/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Konfigurace", "confirm-delete-mapping": "Potvrzujete?", + "confirm-protected-launch": "Potvrzovat spuštění odložených her", + "confirm-protected-launch-desc": "Zeptat se před spuštěním hry označené jako Opuštěno nebo Nikdy nebudu hrát.", "continue-playing-as-grid": "Pokračovat ve hraní jako mřížka", "continue-playing-as-grid-desc": "Zobrazit karty pokračovaného hraní na hlavní stránce jako mřížku", "controller-debug": "Ladění ovladače", @@ -161,6 +163,7 @@ "folder-name": "Název složky", "folder-name-header": "Název složky", "gallery": "Galerie", + "gameplay": "Hraní", "games-label": "Hry", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/de_DE/rom.json b/frontend/src/locales/de_DE/rom.json index b11b1017a..48c6d6efa 100644 --- a/frontend/src/locales/de_DE/rom.json +++ b/frontend/src/locales/de_DE/rom.json @@ -59,6 +59,8 @@ "completion": "Durchgespielt", "completionist": "Vollendung", "confirm-delete-note": "Sind Sie sicher, dass Sie die Notiz \"{title}\" löschen möchten?", + "confirm-launch-protected-body": "Du hast „{name}“ als {status} markiert. Möchtest du es trotzdem spielen?", + "confirm-launch-protected-title": "Dieses Spiel starten?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Download-Link kopieren", diff --git a/frontend/src/locales/de_DE/settings.json b/frontend/src/locales/de_DE/settings.json index 57669c310..ad567ec7c 100644 --- a/frontend/src/locales/de_DE/settings.json +++ b/frontend/src/locales/de_DE/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Konfiguration", "confirm-delete-mapping": "Bestätigen Sie?", + "confirm-protected-launch": "Starten zurückgestellter Spiele bestätigen", + "confirm-protected-launch-desc": "Vor dem Starten eines Spiels nachfragen, das als Aufgegeben oder Nie spielen markiert ist.", "continue-playing-as-grid": "Weiterspielen als Raster", "continue-playing-as-grid-desc": "Zeige die Weiterspielen-Karten als Raster auf der Startseite", "controller-debug": "Controller-Debug", @@ -161,6 +163,7 @@ "folder-name": "Verzeichnisname", "folder-name-header": "Ordnername", "gallery": "Galerie", + "gameplay": "Gameplay", "games-label": "Spiele", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/en_GB/rom.json b/frontend/src/locales/en_GB/rom.json index 6784a9079..947156ea9 100644 --- a/frontend/src/locales/en_GB/rom.json +++ b/frontend/src/locales/en_GB/rom.json @@ -59,6 +59,8 @@ "completion": "Completion", "completionist": "Completionist", "confirm-delete-note": "Are you sure you want to delete the note \"{title}\"?", + "confirm-launch-protected-body": "You marked \"{name}\" as {status}. Do you want to play it anyway?", + "confirm-launch-protected-title": "Launch this game?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copy download link", diff --git a/frontend/src/locales/en_GB/settings.json b/frontend/src/locales/en_GB/settings.json index 9c0908d01..16be2d88b 100644 --- a/frontend/src/locales/en_GB/settings.json +++ b/frontend/src/locales/en_GB/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Config", "confirm-delete-mapping": "Do you confirm?", + "confirm-protected-launch": "Confirm launching shelved games", + "confirm-protected-launch-desc": "Ask before launching a game you marked as Retired or Never Playing.", "continue-playing-as-grid": "Continue playing as grid", "continue-playing-as-grid-desc": "View continue playing ROM cards as a grid at the home page", "controller-debug": "Controller debug", @@ -161,6 +163,7 @@ "folder-name": "Folder name", "folder-name-header": "Folder name", "gallery": "Gallery", + "gameplay": "Gameplay", "games-label": "Games", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/en_US/rom.json b/frontend/src/locales/en_US/rom.json index c2a374838..1f86d9e45 100644 --- a/frontend/src/locales/en_US/rom.json +++ b/frontend/src/locales/en_US/rom.json @@ -59,6 +59,8 @@ "completion": "Completion", "completionist": "Completionist", "confirm-delete-note": "Are you sure you want to delete the note \"{title}\"?", + "confirm-launch-protected-body": "You marked \"{name}\" as {status}. Do you want to play it anyway?", + "confirm-launch-protected-title": "Launch this game?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copy download link", diff --git a/frontend/src/locales/en_US/settings.json b/frontend/src/locales/en_US/settings.json index 50e79b3f9..c2ed8e05b 100644 --- a/frontend/src/locales/en_US/settings.json +++ b/frontend/src/locales/en_US/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Config", "confirm-delete-mapping": "Do you confirm?", + "confirm-protected-launch": "Confirm launching shelved games", + "confirm-protected-launch-desc": "Ask before launching a game you marked as Retired or Never Playing.", "continue-playing-as-grid": "Continue playing as grid", "continue-playing-as-grid-desc": "View continue playing ROM cards as a grid at the home page", "controller-debug": "Controller debug", @@ -161,6 +163,7 @@ "folder-name": "Folder name", "folder-name-header": "Folder name", "gallery": "Gallery", + "gameplay": "Gameplay", "games-label": "Games", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/es_ES/rom.json b/frontend/src/locales/es_ES/rom.json index 5c7d70f37..720a8f04a 100644 --- a/frontend/src/locales/es_ES/rom.json +++ b/frontend/src/locales/es_ES/rom.json @@ -59,6 +59,8 @@ "completion": "Completado", "completionist": "Completista", "confirm-delete-note": "¿Estás seguro de que quieres eliminar la nota \"{title}\"?", + "confirm-launch-protected-body": "Marcaste «{name}» como {status}. ¿Quieres jugarlo de todos modos?", + "confirm-launch-protected-title": "¿Iniciar este juego?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copiar enlace de descarga", diff --git a/frontend/src/locales/es_ES/settings.json b/frontend/src/locales/es_ES/settings.json index ba63810cc..7746d9b5f 100644 --- a/frontend/src/locales/es_ES/settings.json +++ b/frontend/src/locales/es_ES/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Configuración", "confirm-delete-mapping": "¿Confirmas?", + "confirm-protected-launch": "Confirmar el inicio de juegos archivados", + "confirm-protected-launch-desc": "Preguntar antes de iniciar un juego marcado como Abandonado o Nunca jugar.", "continue-playing-as-grid": "Continuar jugando como cuadrícula", "continue-playing-as-grid-desc": "Ver tarjetas de continuar jugando como cuadrícula en la página principal", "controller-debug": "Depuración del mando", @@ -161,6 +163,7 @@ "folder-name": "Nombre de la carpeta", "folder-name-header": "Nombre de carpeta", "gallery": "Galería", + "gameplay": "Juego", "games-label": "Juegos", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/fr_FR/rom.json b/frontend/src/locales/fr_FR/rom.json index 4f7de4709..bb61b287d 100644 --- a/frontend/src/locales/fr_FR/rom.json +++ b/frontend/src/locales/fr_FR/rom.json @@ -59,6 +59,8 @@ "completion": "Complétion", "completionist": "Complétionniste", "confirm-delete-note": "Êtes-vous sûr de vouloir supprimer la note \"{title}\" ?", + "confirm-launch-protected-body": "Vous avez marqué « {name} » comme {status}. Voulez-vous quand même y jouer ?", + "confirm-launch-protected-title": "Lancer ce jeu ?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copier le lien de téléchargement", diff --git a/frontend/src/locales/fr_FR/settings.json b/frontend/src/locales/fr_FR/settings.json index 491e67f78..2c674de6b 100644 --- a/frontend/src/locales/fr_FR/settings.json +++ b/frontend/src/locales/fr_FR/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Configuration", "confirm-delete-mapping": "Confirmez-vous ?", + "confirm-protected-launch": "Confirmer le lancement des jeux mis de côté", + "confirm-protected-launch-desc": "Demander avant de lancer un jeu marqué comme Abandonné ou Jamais joué.", "continue-playing-as-grid": "Continuer à jouer en grille", "continue-playing-as-grid-desc": "Voir les cartes de continuer à jouer en grille sur la page d'accueil", "controller-debug": "Débogage manette", @@ -161,6 +163,7 @@ "folder-name": "Nom du dossier", "folder-name-header": "Nom du dossier", "gallery": "Galerie", + "gameplay": "Jeu", "games-label": "Jeux", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/hu_HU/rom.json b/frontend/src/locales/hu_HU/rom.json index 2de4897b7..90e2ed4ce 100644 --- a/frontend/src/locales/hu_HU/rom.json +++ b/frontend/src/locales/hu_HU/rom.json @@ -59,6 +59,8 @@ "completion": "Befejezve", "completionist": "Completionista", "confirm-delete-note": "Biztos hogy törölni akarod ezt a jegyzetet \"{title}\"?", + "confirm-launch-protected-body": "A(z) „{name}“ játékot {status} állapotúnak jelölted. Mindenképp játszani szeretnél vele?", + "confirm-launch-protected-title": "Elindítod ezt a játékot?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Letöltési link másolása", diff --git a/frontend/src/locales/hu_HU/settings.json b/frontend/src/locales/hu_HU/settings.json index 7d2def849..dac7146fc 100644 --- a/frontend/src/locales/hu_HU/settings.json +++ b/frontend/src/locales/hu_HU/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Konfigurálás", "confirm-delete-mapping": "Megerősíted?", + "confirm-protected-launch": "Félretett játékok indításának megerősítése", + "confirm-protected-launch-desc": "Rákérdezés a Félretett vagy Soha nem játszom jelölésű játék indítása előtt.", "continue-playing-as-grid": "Folytatás rácsnézetben", "continue-playing-as-grid-desc": "A Rom kártyák továbbjátszását rácsnézetben megtekintheted a kezdőlapon", "controller-debug": "Kontroller hibakeresés", @@ -161,6 +163,7 @@ "folder-name": "Mappanév", "folder-name-header": "Mappa név", "gallery": "Galléria", + "gameplay": "Játékmenet", "games-label": "Játékok", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/it_IT/rom.json b/frontend/src/locales/it_IT/rom.json index 0491c39cb..77bb00c54 100644 --- a/frontend/src/locales/it_IT/rom.json +++ b/frontend/src/locales/it_IT/rom.json @@ -59,6 +59,8 @@ "completion": "Completamento", "completionist": "Completista", "confirm-delete-note": "Sei sicuro di voler eliminare la nota \"{title}\"?", + "confirm-launch-protected-body": "Hai contrassegnato «{name}» come {status}. Vuoi comunque giocarci?", + "confirm-launch-protected-title": "Avviare questo gioco?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copia link per il download", diff --git a/frontend/src/locales/it_IT/settings.json b/frontend/src/locales/it_IT/settings.json index e41fd8d1d..104c9edbf 100644 --- a/frontend/src/locales/it_IT/settings.json +++ b/frontend/src/locales/it_IT/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Configurazione", "confirm-delete-mapping": "Confermi?", + "confirm-protected-launch": "Conferma l'avvio dei giochi accantonati", + "confirm-protected-launch-desc": "Chiedi conferma prima di avviare un gioco contrassegnato come Abbandonato o Mai giocare.", "continue-playing-as-grid": "\"Continua a giocare\" come griglia", "continue-playing-as-grid-desc": "Visualizza le ROM di \"Continua a giocare\" come una griglia nella home", "controller-debug": "Debug controller", @@ -161,6 +163,7 @@ "folder-name": "Nome cartella", "folder-name-header": "Nome cartella", "gallery": "Galleria", + "gameplay": "Gameplay", "games-label": "Giochi", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/ja_JP/rom.json b/frontend/src/locales/ja_JP/rom.json index 1da82f21b..45794e646 100644 --- a/frontend/src/locales/ja_JP/rom.json +++ b/frontend/src/locales/ja_JP/rom.json @@ -59,6 +59,8 @@ "completion": "完了度", "completionist": "コンプリート", "confirm-delete-note": "ノート\"{title}\"を削除してもよろしいですか?", + "confirm-launch-protected-body": "「{name}」を{status}に設定しています。それでもプレイしますか?", + "confirm-launch-protected-title": "このゲームを起動しますか?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "ダウンロードリンクをコピー", diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index fcc357a22..f61fccd6a 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "設定", "confirm-delete-mapping": "確認しますか?", + "confirm-protected-launch": "棚上げしたゲームの起動を確認する", + "confirm-protected-launch-desc": "「中断」または「プレイしない」に設定したゲームを起動する前に確認します。", "continue-playing-as-grid": "プレイを継続をグリッドで表示", "continue-playing-as-grid-desc": "ホームのプレイを継続をグリッドで表示", "controller-debug": "コントローラーデバッグ", @@ -161,6 +163,7 @@ "folder-name": "フォルダ名", "folder-name-header": "フォルダ名", "gallery": "ギャラリー", + "gameplay": "ゲームプレイ", "games-label": "ゲーム", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/ko_KR/rom.json b/frontend/src/locales/ko_KR/rom.json index 9aee1b00e..ba7bf8ff8 100644 --- a/frontend/src/locales/ko_KR/rom.json +++ b/frontend/src/locales/ko_KR/rom.json @@ -59,6 +59,8 @@ "completion": "완료율", "completionist": "완주주의자", "confirm-delete-note": "노트 \"{title}\"을(를) 삭제하시겠습니까?", + "confirm-launch-protected-body": "\"{name}\"을(를) {status}(으)로 표시했습니다. 그래도 플레이하시겠습니까?", + "confirm-launch-protected-title": "이 게임을 실행할까요?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "다운로드 링크 복사", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index 89d8961ed..8c152efe3 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "구성", "confirm-delete-mapping": "확인하시겠습니까?", + "confirm-protected-launch": "보류한 게임 실행 확인", + "confirm-protected-launch-desc": "중단 또는 플레이 안 함으로 표시한 게임을 실행하기 전에 확인합니다.", "continue-playing-as-grid": "계속 플레이하기 그리드 뷰", "continue-playing-as-grid-desc": "홈페이지에 계속 플레이하기를 그리드 뷰로 보여줍니다", "controller-debug": "컨트롤러 디버그", @@ -161,6 +163,7 @@ "folder-name": "폴더 이름", "folder-name-header": "폴더 이름", "gallery": "갤러리", + "gameplay": "게임플레이", "games-label": "게임", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/pl_PL/rom.json b/frontend/src/locales/pl_PL/rom.json index 9a7e68f43..343d3731b 100644 --- a/frontend/src/locales/pl_PL/rom.json +++ b/frontend/src/locales/pl_PL/rom.json @@ -59,6 +59,8 @@ "completion": "Ukończenie", "completionist": "Kompletista", "confirm-delete-note": "Czy na pewno chcesz usunąć notatkę \"{title}\"?", + "confirm-launch-protected-body": "Oznaczono „{name}“ jako {status}. Czy mimo to chcesz w nią zagrać?", + "confirm-launch-protected-title": "Uruchomić tę grę?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Kopiuj link do pobrania", diff --git a/frontend/src/locales/pl_PL/settings.json b/frontend/src/locales/pl_PL/settings.json index 7106bec59..21c5b1285 100644 --- a/frontend/src/locales/pl_PL/settings.json +++ b/frontend/src/locales/pl_PL/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Konfiguracja", "confirm-delete-mapping": "Potwierdzasz?", + "confirm-protected-launch": "Potwierdzaj uruchamianie odłożonych gier", + "confirm-protected-launch-desc": "Pytaj przed uruchomieniem gry oznaczonej jako Porzucone lub Nigdy nie gram.", "continue-playing-as-grid": "Kontynuuj grę w widoku siatki", "continue-playing-as-grid-desc": "Wyświetl karty „kontynuuj grę” w formie siatki na stronie głównej", "controller-debug": "Debugowanie kontrolera", @@ -161,6 +163,7 @@ "folder-name": "Nazwa folderu", "folder-name-header": "Nazwa folderu", "gallery": "Galeria", + "gameplay": "Rozgrywka", "games-label": "Gry", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/pt_BR/rom.json b/frontend/src/locales/pt_BR/rom.json index 804393325..263647944 100644 --- a/frontend/src/locales/pt_BR/rom.json +++ b/frontend/src/locales/pt_BR/rom.json @@ -59,6 +59,8 @@ "completion": "Conclusão", "completionist": "Completista", "confirm-delete-note": "Tem certeza de que deseja excluir a nota \"{title}\"?", + "confirm-launch-protected-body": "Você marcou \"{name}\" como {status}. Deseja jogá-lo mesmo assim?", + "confirm-launch-protected-title": "Iniciar este jogo?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copiar link de download", diff --git a/frontend/src/locales/pt_BR/settings.json b/frontend/src/locales/pt_BR/settings.json index 8ccc6bc6f..60fb7da99 100644 --- a/frontend/src/locales/pt_BR/settings.json +++ b/frontend/src/locales/pt_BR/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Configuração", "confirm-delete-mapping": "Você confirma?", + "confirm-protected-launch": "Confirmar a inicialização de jogos arquivados", + "confirm-protected-launch-desc": "Perguntar antes de iniciar um jogo marcado como Abandonado ou Nunca jogar.", "continue-playing-as-grid": "Continuar jogando como grade", "continue-playing-as-grid-desc": "Ver cartões de continuar jogando como uma grade na página inicial", "controller-debug": "Depuração do controle", @@ -161,6 +163,7 @@ "folder-name": "Nome da pasta", "folder-name-header": "Nome da pasta", "gallery": "Galeria", + "gameplay": "Jogabilidade", "games-label": "Jogos", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/ro_RO/rom.json b/frontend/src/locales/ro_RO/rom.json index a9aa2a05c..fdc4c864a 100644 --- a/frontend/src/locales/ro_RO/rom.json +++ b/frontend/src/locales/ro_RO/rom.json @@ -59,6 +59,8 @@ "completion": "Finalizare", "completionist": "Completist", "confirm-delete-note": "Sunteți sigur că vreți să ștergeți notația \"{title}\"?", + "confirm-launch-protected-body": "Ai marcat „{name}“ ca {status}. Vrei să îl joci oricum?", + "confirm-launch-protected-title": "Pornești acest joc?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Copiază linkul de descărcare", diff --git a/frontend/src/locales/ro_RO/settings.json b/frontend/src/locales/ro_RO/settings.json index a8e347652..4c736da83 100644 --- a/frontend/src/locales/ro_RO/settings.json +++ b/frontend/src/locales/ro_RO/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Configurare", "confirm-delete-mapping": "Confirmați?", + "confirm-protected-launch": "Confirmă pornirea jocurilor puse deoparte", + "confirm-protected-launch-desc": "Întreabă înainte de a porni un joc marcat ca Abandonat sau Nu voi juca niciodată.", "continue-playing-as-grid": "Continuă jocul în grilă", "continue-playing-as-grid-desc": "Vezi cardurile „Continuă jocul” în grilă pe pagina principală", "controller-debug": "Depanare controller", @@ -161,6 +163,7 @@ "folder-name": "Nume folder", "folder-name-header": "Nume folder", "gallery": "Galerie", + "gameplay": "Joc", "games-label": "Jocuri", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/ru_RU/rom.json b/frontend/src/locales/ru_RU/rom.json index b133302b0..f2740cb7b 100644 --- a/frontend/src/locales/ru_RU/rom.json +++ b/frontend/src/locales/ru_RU/rom.json @@ -59,6 +59,8 @@ "completion": "Завершение", "completionist": "Перфекционист", "confirm-delete-note": "Вы уверены, что хотите удалить заметку \"{title}\"?", + "confirm-launch-protected-body": "Вы отметили «{name}» как {status}. Всё равно хотите поиграть?", + "confirm-launch-protected-title": "Запустить эту игру?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "Копировать ссылку для скачивания", diff --git a/frontend/src/locales/ru_RU/settings.json b/frontend/src/locales/ru_RU/settings.json index 150d68cc6..edc93b8a7 100644 --- a/frontend/src/locales/ru_RU/settings.json +++ b/frontend/src/locales/ru_RU/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Конфигурация", "confirm-delete-mapping": "Вы подтверждаете?", + "confirm-protected-launch": "Подтверждать запуск отложенных игр", + "confirm-protected-launch-desc": "Спрашивать перед запуском игры, отмеченной как «Заброшено» или «Никогда не играть».", "continue-playing-as-grid": "Продолжение игры в виде сетки", "continue-playing-as-grid-desc": "Просмотр карточек продолжения игры в виде сетки на главной странице", "controller-debug": "Отладка контроллера", @@ -161,6 +163,7 @@ "folder-name": "Имя папки", "folder-name-header": "Имя папки", "gallery": "Галерея", + "gameplay": "Игровой процесс", "games-label": "Игры", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/tr_TR/rom.json b/frontend/src/locales/tr_TR/rom.json index 1f837390b..e8c0b64b0 100644 --- a/frontend/src/locales/tr_TR/rom.json +++ b/frontend/src/locales/tr_TR/rom.json @@ -59,6 +59,8 @@ "completion": "Tamamlama", "completionist": "Yüzde yüz tamamlayıcı", "confirm-delete-note": "\"{title}\" notunu silmek istediğinizden emin misiniz?", + "confirm-launch-protected-body": "\"{name}\" oyununu {status} olarak işaretlediniz. Yine de oynamak istiyor musunuz?", + "confirm-launch-protected-title": "Bu oyun başlatılsın mı?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "İndirme bağlantısını kopyala", diff --git a/frontend/src/locales/tr_TR/settings.json b/frontend/src/locales/tr_TR/settings.json index a67f7dc5c..ba36c31e5 100644 --- a/frontend/src/locales/tr_TR/settings.json +++ b/frontend/src/locales/tr_TR/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "Yapılandırma", "confirm-delete-mapping": "Onaylıyor musunuz?", + "confirm-protected-launch": "Ertelenen oyunların başlatılmasını onayla", + "confirm-protected-launch-desc": "Bırakıldı veya Hiç Oynanmayacak olarak işaretlediğiniz bir oyunu başlatmadan önce sorun.", "continue-playing-as-grid": "Devam edilen oyunları ızgara olarak göster", "continue-playing-as-grid-desc": "Ana sayfada devam edilen oyunları ızgara görünümünde göster", "controller-debug": "Oyun kumandası hata ayıklama", @@ -161,6 +163,7 @@ "folder-name": "Klasör adı", "folder-name-header": "Klasör adı", "gallery": "Galeri", + "gameplay": "Oynanış", "games-label": "Oyunlar", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/zh_CN/rom.json b/frontend/src/locales/zh_CN/rom.json index d3c198c47..299338d37 100644 --- a/frontend/src/locales/zh_CN/rom.json +++ b/frontend/src/locales/zh_CN/rom.json @@ -59,6 +59,8 @@ "completion": "完成度", "completionist": "完美主义者", "confirm-delete-note": "确定要删除笔记\"{title}\"吗?", + "confirm-launch-protected-body": "您已将“{name}”标记为{status}。仍要玩吗?", + "confirm-launch-protected-title": "启动这个游戏吗?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "复制下载链接", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index 9e63b2798..28725d03a 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "配置", "confirm-delete-mapping": "确认吗?", + "confirm-protected-launch": "确认启动已搁置的游戏", + "confirm-protected-launch-desc": "在启动标记为“已搁置”或“不玩”的游戏前进行确认。", "continue-playing-as-grid": "继续游玩(网格)", "continue-playing-as-grid-desc": "以网格形式在主页上显示继续游玩(卡片)部分", "controller-debug": "手柄调试", @@ -161,6 +163,7 @@ "folder-name": "文件夹名称", "folder-name-header": "文件夹名称", "gallery": "游戏库", + "gameplay": "游戏玩法", "games-label": "游戏", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/locales/zh_TW/rom.json b/frontend/src/locales/zh_TW/rom.json index 77883b216..33f6e1a37 100644 --- a/frontend/src/locales/zh_TW/rom.json +++ b/frontend/src/locales/zh_TW/rom.json @@ -59,6 +59,8 @@ "completion": "完成度", "completionist": "完美主義者", "confirm-delete-note": "確定要刪除筆記\"{title}\"嗎?", + "confirm-launch-protected-body": "您已將「{name}」標記為{status}。仍要玩嗎?", + "confirm-launch-protected-title": "啟動這個遊戲嗎?", "convert-to-folder-body": "This action will convert the ROM to a multi-file ROM. This action is not reversible.", "convert-to-folder-title": "Convert to folder ROM?", "copy-download-link-title": "複製下載連結", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index 027f0a5fc..b6ae7c368 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -52,6 +52,8 @@ "config-file-parse-error-title": "Configuration file could not be parsed!", "config-tab": "組態", "confirm-delete-mapping": "確認嗎?", + "confirm-protected-launch": "確認啟動已擱置的遊戲", + "confirm-protected-launch-desc": "在啟動標記為「已擱置」或「不玩」的遊戲前進行確認。", "continue-playing-as-grid": "顯示繼續遊玩卡片", "continue-playing-as-grid-desc": "在首頁上以卡片方式顯示繼續遊玩", "controller-debug": "控制器除錯", @@ -161,6 +163,7 @@ "folder-name": "資料夾名稱", "folder-name-header": "資料夾名稱", "gallery": "遊戲庫", + "gameplay": "遊戲玩法", "games-label": "遊戲", "grant-full": "Full access", "grant-none": "Not granted", diff --git a/frontend/src/services/api/play-session.ts b/frontend/src/services/api/play-session.ts index 60374f821..3b86b78e0 100644 --- a/frontend/src/services/api/play-session.ts +++ b/frontend/src/services/api/play-session.ts @@ -1,16 +1,19 @@ +import Cookies from "js-cookie"; import api from "@/services/api"; +interface PlaySessionEntry { + rom_id: number; + start_time: string; + end_time: string; + duration_ms: number; +} + async function ingestPlaySessions({ deviceId = null, sessions, }: { deviceId?: string | null; - sessions: { - rom_id: number; - start_time: string; - end_time: string; - duration_ms: number; - }[]; + sessions: PlaySessionEntry[]; }) { return api.post("/play-sessions", { device_id: deviceId, @@ -18,4 +21,23 @@ async function ingestPlaySessions({ }); } -export default { ingestPlaySessions }; +function ingestPlaySessionsKeepalive({ + deviceId = null, + sessions, +}: { + deviceId?: string | null; + sessions: PlaySessionEntry[]; +}): void { + void fetch("/api/play-sessions", { + method: "POST", + keepalive: true, + credentials: "same-origin", + headers: { + "Content-Type": "application/json", + "x-csrftoken": Cookies.get("romm_csrftoken") ?? "", + }, + body: JSON.stringify({ device_id: deviceId, sessions }), + }).catch((err) => console.error("Failed to submit play session:", err)); +} + +export default { ingestPlaySessions, ingestPlaySessionsKeepalive }; diff --git a/frontend/src/v2/composables/useGameActions/index.test.ts b/frontend/src/v2/composables/useGameActions/index.test.ts new file mode 100644 index 000000000..0fd174f8e --- /dev/null +++ b/frontend/src/v2/composables/useGameActions/index.test.ts @@ -0,0 +1,117 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { SimpleRom } from "@/stores/roms"; +import { useGameActions } from "./index"; + +// Controllable stubs shared with the mocked modules below. +const push = vi.fn(); +const confirmFn = vi.fn(); +const confirmProtectedLaunch = { value: true }; + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ t: (key: string) => key }), +})); +vi.mock("vue-router", () => ({ + useRouter: () => ({ push }), +})); +vi.mock("@/composables/useFavoriteToggle", () => ({ + useFavoriteToggle: () => ({ + isFavorite: () => false, + toggleFavorite: vi.fn(), + }), +})); +vi.mock("@/composables/useUISettings", () => ({ + useUISettings: () => ({ confirmProtectedLaunch }), +})); +vi.mock("@/services/api/rom", () => ({ + default: { updateUserRomProps: vi.fn() }, +})); +vi.mock("@/stores/auth", () => ({ + default: () => ({ scopes: [] as string[] }), +})); +vi.mock("@/stores/roms", () => ({ + default: () => ({ update: vi.fn(), removeFromContinuePlaying: vi.fn() }), +})); +vi.mock("@/stores/streaming", () => ({ + useStreamingStore: () => ({ containerForPlatform: () => null }), +})); +vi.mock("@/utils", () => ({ + getDownloadLink: vi.fn(), + getDownloadPath: vi.fn(), + isNintendoDSRom: () => false, +})); +vi.mock("@/v2/composables/useCan", () => ({ + useCan: () => ({ value: true }), +})); +// EJS is the only playable core in these tests, so play() routes to /ejs. +vi.mock("@/v2/composables/useCanPlay", () => ({ + useCanPlay: () => ({ + canPlayEJS: { value: true }, + canPlayRuffle: { value: false }, + }), +})); +vi.mock("@/v2/composables/useClipboard", () => ({ + useClipboard: () => ({ copy: vi.fn() }), +})); +vi.mock("@/v2/composables/useConfirm", () => ({ + useConfirm: () => confirmFn, +})); +vi.mock("@/v2/composables/useSnackbar", () => ({ + useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), +})); +vi.mock("@/v2/composables/useViewTransition", () => ({ + useViewTransition: () => ({ + morphTransition: (_opts: unknown, cb: () => void) => cb(), + }), +})); + +function makeRom(status: SimpleRom["rom_user"]["status"] = null): SimpleRom { + return { + id: 1, + name: "Chrono Trigger", + fs_name_no_ext: "Chrono Trigger", + platform_slug: "snes", + rom_user: { status }, + } as unknown as SimpleRom; +} + +beforeEach(() => { + push.mockClear(); + confirmFn.mockClear(); + confirmProtectedLaunch.value = true; +}); + +describe("useGameActions.play — launch confirmation", () => { + it("launches a normal game without confirming", async () => { + const actions = useGameActions(() => makeRom(null)); + await actions.play(); + expect(confirmFn).not.toHaveBeenCalled(); + expect(push).toHaveBeenCalledWith("/rom/1/ejs"); + }); + + it.each(["retired", "never_playing"] as const)( + "asks before launching a %s game and aborts on cancel", + async (status) => { + confirmFn.mockResolvedValue(false); + const actions = useGameActions(() => makeRom(status)); + await actions.play(); + expect(confirmFn).toHaveBeenCalledTimes(1); + expect(push).not.toHaveBeenCalled(); + }, + ); + + it("launches a shelved game once the user confirms", async () => { + confirmFn.mockResolvedValue(true); + const actions = useGameActions(() => makeRom("retired")); + await actions.play(); + expect(confirmFn).toHaveBeenCalledTimes(1); + expect(push).toHaveBeenCalledWith("/rom/1/ejs"); + }); + + it("skips the prompt when the preference is disabled", async () => { + confirmProtectedLaunch.value = false; + const actions = useGameActions(() => makeRom("never_playing")); + await actions.play(); + expect(confirmFn).not.toHaveBeenCalled(); + expect(push).toHaveBeenCalledWith("/rom/1/ejs"); + }); +}); diff --git a/frontend/src/v2/composables/useGameActions/index.ts b/frontend/src/v2/composables/useGameActions/index.ts index baeb57714..55be3e261 100644 --- a/frontend/src/v2/composables/useGameActions/index.ts +++ b/frontend/src/v2/composables/useGameActions/index.ts @@ -15,6 +15,7 @@ import { useI18n } from "vue-i18n"; import { useRouter } from "vue-router"; import type { RomUserData, RomUserStatus } from "@/__generated__"; import { useFavoriteToggle } from "@/composables/useFavoriteToggle"; +import { useUISettings } from "@/composables/useUISettings"; import romApi from "@/services/api/rom"; import storeAuth from "@/stores/auth"; import storeRoms from "@/stores/roms"; @@ -26,6 +27,7 @@ import { getDownloadLink, getDownloadPath, isNintendoDSRom } from "@/utils"; import { useCan } from "@/v2/composables/useCan"; import { useCanPlay } from "@/v2/composables/useCanPlay"; import { useClipboard } from "@/v2/composables/useClipboard"; +import { useConfirm } from "@/v2/composables/useConfirm"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useViewTransition } from "@/v2/composables/useViewTransition"; @@ -52,6 +54,8 @@ export function useGameActions( const { morphTransition } = useViewTransition(); const emitter = inject>("emitter"); const snackbar = useSnackbar(); + const confirm = useConfirm(); + const { confirmProtectedLaunch } = useUISettings(); const clipboard = useClipboard(); const romsStore = storeRoms(); const auth = storeAuth(); @@ -199,9 +203,34 @@ export function useGameActions( ); }); - function play() { + async function play() { const rom = getRom(); if (!rom) return; + + // Guard launching a game the user deliberately shelved. `retired` / + // `never_playing` encode an opt-in "don't play" intent, so confirm + // before booting one. Gated by a per-user preference (on by default). + const status = rom.rom_user?.status; + if ( + confirmProtectedLaunch.value && + (status === "retired" || status === "never_playing") + ) { + const ok = await confirm({ + title: t("rom.confirm-launch-protected-title"), + body: t("rom.confirm-launch-protected-body", { + name: rom.name ?? rom.fs_name_no_ext ?? "", + status: t( + status === "retired" + ? "rom.status-retired" + : "rom.status-never-playing", + ), + }), + confirmText: t("play.play"), + tone: "warning", + }); + if (!ok) return; + } + // The launch "load" flourish (disc/cartridge insert) lives on the // player view itself — see EmulatorJS's onPlay — so navigation is // immediate here. diff --git a/frontend/src/v2/composables/usePlaySession/index.test.ts b/frontend/src/v2/composables/usePlaySession/index.test.ts new file mode 100644 index 000000000..44448f3e9 --- /dev/null +++ b/frontend/src/v2/composables/usePlaySession/index.test.ts @@ -0,0 +1,102 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import playSessionApi from "@/services/api/play-session"; +import type { SimpleRom } from "@/stores/roms"; +import { usePlaySession } from "./index"; + +vi.mock("@/services/api/play-session", () => ({ + default: { ingestPlaySessionsKeepalive: vi.fn() }, +})); + +// Controllable auth stand-in: tests tweak scopes / user between cases. +const authState = { + scopes: ["roms.user.write"] as string[], + user: { current_device_id: "device-1" } as { + current_device_id: string; + } | null, +}; +vi.mock("@/stores/auth", () => ({ + default: () => authState, +})); + +const ingest = vi.mocked(playSessionApi.ingestPlaySessionsKeepalive); + +function makeRom(id = 7): SimpleRom { + return { id } as unknown as SimpleRom; +} + +beforeEach(() => { + ingest.mockReset(); + authState.scopes = ["roms.user.write"]; + authState.user = { current_device_id: "device-1" }; + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-07-21T10:00:00.000Z")); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("usePlaySession", () => { + it("ingests a session with real start/end/duration on flush", () => { + const { start, flush } = usePlaySession(); + start(makeRom(42)); + vi.advanceTimersByTime(90_000); + flush(); + + expect(ingest).toHaveBeenCalledTimes(1); + expect(ingest).toHaveBeenCalledWith({ + deviceId: "device-1", + sessions: [ + { + rom_id: 42, + start_time: "2026-07-21T10:00:00.000Z", + end_time: "2026-07-21T10:01:30.000Z", + duration_ms: 90_000, + }, + ], + }); + }); + + it("does nothing without a write scope", () => { + authState.scopes = ["roms.user.read"]; + const { start, flush } = usePlaySession(); + start(makeRom()); + vi.advanceTimersByTime(90_000); + flush(); + expect(ingest).not.toHaveBeenCalled(); + }); + + it("drops sub-second sessions", () => { + const { start, flush } = usePlaySession(); + start(makeRom()); + vi.advanceTimersByTime(500); + flush(); + expect(ingest).not.toHaveBeenCalled(); + }); + + it("is idempotent — a second flush does not resubmit", () => { + const { start, flush } = usePlaySession(); + start(makeRom()); + vi.advanceTimersByTime(90_000); + flush(); + flush(); + expect(ingest).toHaveBeenCalledTimes(1); + }); + + it("flush without a prior start is a no-op", () => { + const { flush } = usePlaySession(); + flush(); + expect(ingest).not.toHaveBeenCalled(); + }); + + it("sends a null device id when the user has none", () => { + authState.user = null; + const { start, flush } = usePlaySession(); + start(makeRom()); + vi.advanceTimersByTime(90_000); + flush(); + expect(ingest).toHaveBeenCalledWith( + expect.objectContaining({ deviceId: null }), + ); + }); +}); diff --git a/frontend/src/v2/composables/usePlaySession/index.ts b/frontend/src/v2/composables/usePlaySession/index.ts new file mode 100644 index 000000000..eafa6d07b --- /dev/null +++ b/frontend/src/v2/composables/usePlaySession/index.ts @@ -0,0 +1,60 @@ +// usePlaySession — records a single play session's wall-clock and ingests it +// on flush. The session is what drives the server-side rom_user update +// (last_played + now_playing + status), replacing the old optimistic +// launch-time write. +// +// Fire-and-forget: entering or leaving gameplay must never block on the +// network. flush() is idempotent, so the several exit paths a player has +// (stop button, save-and-exit, back navigation, unmount) can each call it +// without risking a double submission. +import playSessionApi from "@/services/api/play-session"; +import storeAuth from "@/stores/auth"; +import type { SimpleRom } from "@/stores/roms"; + +// Sessions shorter than a second carry no meaningful playtime and would be +// rejected anyway: the backend floors timestamps to whole seconds and +// requires end_time > start_time. A tap-Play-then-quit is dropped. +const MIN_SESSION_MS = 1000; + +export function usePlaySession(): { + start: (rom: SimpleRom) => void; + flush: () => void; +} { + const auth = storeAuth(); + let startTime: Date | null = null; + let romId: number | null = null; + + function start(rom: SimpleRom): void { + // Recording is gated on the same scope the ingest endpoint requires. + if (!auth.scopes.includes("roms.user.write")) return; + startTime = new Date(); + romId = rom.id; + } + + function flush(): void { + if (startTime === null || romId === null) return; + const sessionStart = startTime; + const sessionRomId = romId; + // Clear before the async call so a second flush is a no-op. + startTime = null; + romId = null; + + const endTime = new Date(); + const durationMs = endTime.getTime() - sessionStart.getTime(); + if (durationMs < MIN_SESSION_MS) return; + + playSessionApi.ingestPlaySessionsKeepalive({ + deviceId: auth.user?.current_device_id ?? null, + sessions: [ + { + rom_id: sessionRomId, + start_time: sessionStart.toISOString(), + end_time: endTime.toISOString(), + duration_ms: durationMs, + }, + ], + }); + } + + return { start, flush }; +} diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index b49f68642..e2b2c9395 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -48,6 +48,7 @@ import { useBackgroundArt } from "@/v2/composables/useBackgroundArt"; import { useCoverArt } from "@/v2/composables/useCoverArt"; import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; import { useInputModality } from "@/v2/composables/useInputModality"; +import { usePlaySession } from "@/v2/composables/usePlaySession"; import type { SliderBtnGroupItem } from "@/v2/lib/primitives/RSliderBtnGroup/types"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; import { installIOSFullscreenShim } from "@/views/Player/EmulatorJS/utils"; @@ -68,6 +69,7 @@ const configStore = storeConfig(); const { playing, fullScreen } = storeToRefs(playingStore); const { fullscreenOnPlay } = useFullscreenPref(); const { modality } = useInputModality(); +const playSession = usePlaySession(); // Ref the Play CTA so we can imperatively focus it on enter (and again // when the user comes back from a running session). RBtn forwards to @@ -225,14 +227,6 @@ async function onPlay() { removeIOSFullscreenShim.value?.(); removeIOSFullscreenShim.value = installIOSFullscreenShim(); - if (rom.value && auth.scopes.includes("roms.user.write")) { - romApi.updateUserRomProps({ - romId: rom.value.id, - data: rom.value.rom_user, - updateLastPlayed: true, - }); - } - gameRunning.value = true; window.EJS_fullscreenOnLoaded = fullscreenOnPlay.value; fullScreen.value = fullscreenOnPlay.value; @@ -445,10 +439,12 @@ onMounted(async () => { // to Play on exit so a Start-Play loop stays on the pad. watch(gameRunning, (running, prev) => { if (running && !prev) { + if (rom.value) playSession.start(rom.value); emitActivityStart(); startActivityHeartbeat(); } if (prev && !running) { + playSession.flush(); stopActivityHeartbeat(); emitActivityStop(); nextTick(focusPlayButton); @@ -465,7 +461,9 @@ function onGamepadButton(e: CustomEvent<{ name?: string }>) { onBeforeUnmount(() => { // Leaving the player (back nav / route change) ends the session even if - // the user never exited the game to the config screen first. + // the user never exited the game to the config screen first. flush() is + // idempotent, so an exit that already flushed via the watch is a no-op. + playSession.flush(); stopActivityHeartbeat(); emitActivityStop(); // Hand the keyboard and gamepad back to the UI; the flag otherwise diff --git a/frontend/src/v2/views/Player/Ruffle.vue b/frontend/src/v2/views/Player/Ruffle.vue index f8512e5ef..dbc56e085 100644 --- a/frontend/src/v2/views/Player/Ruffle.vue +++ b/frontend/src/v2/views/Player/Ruffle.vue @@ -23,6 +23,7 @@ import { getDownloadPath } from "@/utils"; import GameCover from "@/v2/components/shared/GameCover.vue"; import { useBackgroundArt } from "@/v2/composables/useBackgroundArt"; import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; +import { usePlaySession } from "@/v2/composables/usePlaySession"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; import { colorCanvas } from "@/v2/tokens"; @@ -34,6 +35,7 @@ const route = useRoute(); const router = useRouter(); const { fullscreenOnPlay } = useFullscreenPref(); const playingStore = storePlaying(); +const playSession = usePlaySession(); const rom = ref(null); const gameRunning = ref(false); @@ -142,6 +144,11 @@ function onPlay() { player.style.width = "100%"; player.style.height = "100%"; + // Start timing the session only once playback is actually under way, so a + // failed player creation / load records nothing. The session is ingested + // on unmount, which is what updates last_played / now_playing / status. + playSession.start(rom.value); + if (player.fullscreenEnabled && fullscreenOnPlay.value) { player.enterFullscreen(); } @@ -196,6 +203,9 @@ onMounted(async () => { }); onBeforeUnmount(() => { + // Every exit path (Quit, back links, route change) unmounts the view, so + // this is the single choke point for recording the session. + playSession.flush(); // Hand the keyboard and gamepad back to the UI on any exit path. playingStore.setPlaying(false); }); diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index 6380bdc00..7c57bca2b 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -27,6 +27,7 @@ import storeRoms, { type DetailedRom, type SimpleRom } from "@/stores/roms"; import { useStreamingStore } from "@/stores/streaming"; import GameCover from "@/v2/components/shared/GameCover.vue"; import { useBackgroundArt } from "@/v2/composables/useBackgroundArt"; +import { usePlaySession } from "@/v2/composables/usePlaySession"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import storeGalleryRoms from "@/v2/stores/galleryRoms"; @@ -44,6 +45,7 @@ const setBgArt = useBackgroundArt(); const romsStore = storeRoms(); const galleryRoms = storeGalleryRoms(); const playingStore = storePlaying(); +const playSession = usePlaySession(); const rom = ref(null); const playerState = ref("idle"); @@ -185,6 +187,9 @@ onBeforeUnmount(() => { iframeLoadCleanup = null; contentWindowCleanup?.(); contentWindowCleanup = null; + // Every exit path (Stop, Save & Exit, back nav) unmounts the view, so this + // is the single choke point for recording the session. + playSession.flush(); // Hand controller input back to the UI regardless of how we leave. playingStore.setPlaying(false); if (playerState.value === "exited") { @@ -322,6 +327,13 @@ async function handlePlay(): Promise { errorMessage.value = error.message ?? t("play.stream-error-generic"); } } + + // Start timing the session once the claim succeeds and playback is live. + // The session is ingested on unmount, which updates last_played / + // now_playing / status server-side. + if (rom.value && playerState.value === "playing") { + playSession.start(rom.value); + } } async function handleStop(): Promise { diff --git a/frontend/src/v2/views/Settings/UserInterface.vue b/frontend/src/v2/views/Settings/UserInterface.vue index 4bbeb2543..ce6f1f394 100644 --- a/frontend/src/v2/views/Settings/UserInterface.vue +++ b/frontend/src/v2/views/Settings/UserInterface.vue @@ -6,8 +6,9 @@ // 2. Theme (3-button compact picker) // 3. Home (toggle grid) // 4. Gallery (toggle grid + boxart RSelect prefix-label) -// 5. Virtual collections (single toggle + RSelect prefix-label) -// 6. UI version (v2-only, beta — kept last) +// 5. Gameplay (launch-confirmation toggle) +// 6. Virtual collections (single toggle + RSelect prefix-label) +// 7. UI version (v2-only, beta — kept last) // // The v1 "Platforms drawer" section was removed (no equivalent in v2). // `useUISettings` still exposes `platformsGroupBy` for v1 — we just @@ -57,6 +58,8 @@ const { disableAnimations, enableExperimentalCache, boxartStyle, + // Gameplay + confirmProtectedLaunch, } = useUISettings(); type Theme = "dark" | "light" | "auto"; @@ -341,6 +344,20 @@ function onVirtualCollectionTypeChange(value: unknown) { + + +
+ +
+
+ (); const romRef = ref(props.rom); const saveRef = ref(props.save); -const sessionStartTime = ref(null); const deviceIDRef = ref(authStore.user?.current_device_id ?? undefined); const theme = useTheme(); const emitter = inject>("emitter"); @@ -385,8 +383,6 @@ window.EJS_onSaveState = async function ({ }; window.EJS_onGameStart = async () => { - sessionStartTime.value = new Date(); - // Install netplay overrides synchronously, before any await below, so they // are in place before room polling or a Create/Join action can start. const netplay = window.EJS_emulator?.netplay; @@ -501,37 +497,12 @@ window.EJS_onGameStart = async () => { }; function immediateExit() { - if (!sessionStartTime.value) { - return router - .push({ name: ROUTES.ROM, params: { rom: romRef.value.id } }) - .catch((error) => { - console.error("Error navigating to console rom", error); - }); - } - - const endTime = new Date(); - const durationMs = endTime.getTime() - sessionStartTime.value.getTime(); - - playSessionApi - .ingestPlaySessions({ - deviceId: deviceIDRef.value, - sessions: [ - { - rom_id: romRef.value.id, - start_time: sessionStartTime.value.toISOString(), - end_time: endTime.toISOString(), - duration_ms: durationMs, - }, - ], - }) - .catch((err) => console.error("Failed to submit play session:", err)) - .finally(() => { - sessionStartTime.value = null; - router - .push({ name: ROUTES.ROM, params: { rom: romRef.value.id } }) - .catch((error) => { - console.error("Error navigating to console rom", error); - }); + // Play-session recording is owned by the v2 player shell (usePlaySession); + // this only returns to the game details view. + router + .push({ name: ROUTES.ROM, params: { rom: romRef.value.id } }) + .catch((error) => { + console.error("Error navigating to console rom", error); }); }