From 47514db9462260068902772952cba1c7c5b54301 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 15 Sep 2026 17:51:10 -0400 Subject: [PATCH 01/28] fix(player): attach a real screenshot to a manual save state EmulatorJS 4.2.3 resolves its screenshot capture under `blob`, not the `screenshot` key `EJS_onSaveState` destructures, so a state saved from the emulator's own menu reached the server with no picture; the upstream fix for that still hands back a partially rendered frame. Read the live canvas through the game manager, which is the path Save & Quit already uses. Fixes #4509 Co-Authored-By: Claude Opus 5 (1M context) --- frontend/src/console/views/Play.vue | 21 ++++++---- .../src/views/Player/EmulatorJS/Player.vue | 6 ++- .../src/views/Player/EmulatorJS/utils.test.ts | 41 ++++++++++++++++++- frontend/src/views/Player/EmulatorJS/utils.ts | 14 +++++++ 4 files changed, 72 insertions(+), 10 deletions(-) diff --git a/frontend/src/console/views/Play.vue b/frontend/src/console/views/Play.vue index 46ae447ee..e0fed5820 100644 --- a/frontend/src/console/views/Play.vue +++ b/frontend/src/console/views/Play.vue @@ -36,6 +36,7 @@ import { getDownloadPath, } from "@/utils"; import { buildFormInput } from "@/utils/formData"; +import { captureStateScreenshot } from "@/views/Player/EmulatorJS/utils"; import { installEJSDefaultOptionsTrap, invalidateEmulatorJSRomCacheIfRenamed, @@ -530,19 +531,25 @@ async function boot() { // Set up EmulatorJS callbacks window.EJS_onSaveState = async function ({ state: stateFile, - screenshot: screenshotFile, + screenshot: emulatorScreenshot, }: { state: ArrayBuffer; - screenshot: ArrayBuffer; + screenshot?: ArrayBuffer; }) { + const screenshotFile = + (await captureStateScreenshot()) ?? emulatorScreenshot; try { const formData = buildFormInput([ ["stateFile", new Blob([stateFile]), "state.save"], - [ - "screenshotFile", - new Blob([screenshotFile], { type: "image/png" }), - "screenshot.png", - ], + ...(screenshotFile + ? ([ + [ + "screenshotFile", + new Blob([screenshotFile], { type: "image/png" }), + "screenshot.png", + ], + ] as const) + : []), ]); await api.post("/states", formData, { diff --git a/frontend/src/views/Player/EmulatorJS/Player.vue b/frontend/src/views/Player/EmulatorJS/Player.vue index ed2a47d71..3ab2b705c 100644 --- a/frontend/src/views/Player/EmulatorJS/Player.vue +++ b/frontend/src/views/Player/EmulatorJS/Player.vue @@ -26,6 +26,7 @@ import { } from "@/utils"; import { saveSave, + captureStateScreenshot, saveState, loadEmulatorJSSave, loadEmulatorJSState, @@ -114,7 +115,7 @@ declare global { EJS_disableBatchBootup: boolean; EJS_onGameStart: () => void; EJS_onSaveState: (args: { - screenshot: ArrayBuffer; + screenshot?: ArrayBuffer; state: ArrayBuffer; }) => void; EJS_onLoadState: () => void; @@ -402,8 +403,9 @@ window.EJS_onLoadState = async function () { window.EJS_onSaveState = async function ({ state: stateFile, - screenshot: screenshotFile, + screenshot: emulatorScreenshot, }) { + const screenshotFile = (await captureStateScreenshot()) ?? emulatorScreenshot; const state = await saveState({ rom: romRef.value, stateFile, diff --git a/frontend/src/views/Player/EmulatorJS/utils.test.ts b/frontend/src/views/Player/EmulatorJS/utils.test.ts index 75dac7470..b8b1aeeff 100644 --- a/frontend/src/views/Player/EmulatorJS/utils.test.ts +++ b/frontend/src/views/Player/EmulatorJS/utils.test.ts @@ -1,5 +1,9 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { createSaveSyncTracker, installEJSDefaultOptionsTrap } from "./utils"; +import { + captureStateScreenshot, + createSaveSyncTracker, + installEJSDefaultOptionsTrap, +} from "./utils"; const STORAGE_KEY = "ejs-7-n64-Test Game-settings"; @@ -187,3 +191,38 @@ describe("createSaveSyncTracker", () => { expect(tracker.shouldUpload(bytes(1, 2, 3, 0))).toBe(false); }); }); + +describe("captureStateScreenshot", () => { + /* eslint-disable @typescript-eslint/no-explicit-any */ + afterEach(() => { + delete (window as any).EJS_emulator; + }); + + it("reads the live canvas through the game manager", async () => { + const shot = new ArrayBuffer(8); + (window as any).EJS_emulator = { + gameManager: { screenshot: async () => shot }, + }; + + await expect(captureStateScreenshot()).resolves.toBe(shot); + }); + + // A manual save state still has to reach the server without its picture. + it("returns nothing when the emulator has no game manager yet", async () => { + (window as any).EJS_emulator = {}; + + await expect(captureStateScreenshot()).resolves.toBeUndefined(); + }); + + it("swallows a capture that throws", async () => { + (window as any).EJS_emulator = { + gameManager: { + screenshot: async () => { + throw new Error("canvas is gone"); + }, + }, + }; + + await expect(captureStateScreenshot()).resolves.toBeUndefined(); + }); +}); diff --git a/frontend/src/views/Player/EmulatorJS/utils.ts b/frontend/src/views/Player/EmulatorJS/utils.ts index c9638e422..42436a6ca 100644 --- a/frontend/src/views/Player/EmulatorJS/utils.ts +++ b/frontend/src/views/Player/EmulatorJS/utils.ts @@ -15,6 +15,20 @@ function buildSaveName(rom: DetailedRom): string { return `${romName} [${new Date().toISOString().replace(/[:.]/g, "-").replace("T", " ").replace("Z", "")}]`; } +// EmulatorJS 4.2.3 hands `EJS_onSaveState` nothing under `screenshot`, and its +// own canvas capture renders only a slice of the frame even with the upstream +// fix applied. Reading the live canvas is the path Save & Quit already takes. +export async function captureStateScreenshot(): Promise< + ArrayBuffer | undefined +> { + try { + return await window.EJS_emulator?.gameManager?.screenshot(); + } catch (error) { + console.error("Failed to capture a state screenshot", error); + return undefined; + } +} + export async function saveState({ rom, stateFile, From 4400aaa3aab0fa460687d730dedc0e5161a2d0e5 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 15 Sep 2026 18:05:30 -0400 Subject: [PATCH 02/28] fix(v2): stop offering a missing rom's files for download The Files tab flagged a rom missing from the filesystem on its summary card only, and still offered Download and Copy link on rows whose bytes are not there, so both actions answered 404. Carry the flag onto every row and take the fetch actions out of reach, per-row and in the selection toolbar. Delete stays, since removing the database row is exactly what a missing file needs. Fixes #4037 Co-Authored-By: Claude Opus 5 (1M context) --- frontend/src/locales/bg_BG/rom.json | 1 + frontend/src/locales/cs_CZ/rom.json | 1 + frontend/src/locales/de_DE/rom.json | 1 + frontend/src/locales/en_GB/rom.json | 1 + frontend/src/locales/en_US/rom.json | 1 + frontend/src/locales/es_ES/rom.json | 1 + frontend/src/locales/fr_FR/rom.json | 1 + frontend/src/locales/hu_HU/rom.json | 1 + frontend/src/locales/it_IT/rom.json | 1 + frontend/src/locales/ja_JP/rom.json | 1 + frontend/src/locales/ko_KR/rom.json | 1 + frontend/src/locales/pl_PL/rom.json | 1 + frontend/src/locales/pt_BR/rom.json | 1 + frontend/src/locales/ro_RO/rom.json | 1 + frontend/src/locales/ru_RU/rom.json | 1 + frontend/src/locales/tr_TR/rom.json | 1 + frontend/src/locales/zh_CN/rom.json | 1 + frontend/src/locales/zh_TW/rom.json | 1 + .../GameDetails/FilesTab/FileRow.vue | 10 ++++++ .../GameDetails/FilesTab/FilesSummary.vue | 9 ++++- .../GameDetails/FilesTab/FilesTab.test.ts | 35 +++++++++++++++++++ .../GameDetails/FilesTab/FilesTab.vue | 3 ++ 22 files changed, 74 insertions(+), 1 deletion(-) diff --git a/frontend/src/locales/bg_BG/rom.json b/frontend/src/locales/bg_BG/rom.json index ae0b5e85d..5b8c9dfda 100644 --- a/frontend/src/locales/bg_BG/rom.json +++ b/frontend/src/locales/bg_BG/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Завършеност", "metric-difficulty": "Трудност", "metric-rating": "Оценка", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Липсваща платформа от файловата система", "more-actions": "Още действия", "my-notes": "Моите бележки", diff --git a/frontend/src/locales/cs_CZ/rom.json b/frontend/src/locales/cs_CZ/rom.json index f22e43c25..e452375aa 100644 --- a/frontend/src/locales/cs_CZ/rom.json +++ b/frontend/src/locales/cs_CZ/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Dokončení", "metric-difficulty": "Obtížnost", "metric-rating": "Hodnocení", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Chybějící platforma ze souborového systému", "more-actions": "Další akce", "my-notes": "Mé poznámky", diff --git a/frontend/src/locales/de_DE/rom.json b/frontend/src/locales/de_DE/rom.json index b54d6f896..7f7cff719 100644 --- a/frontend/src/locales/de_DE/rom.json +++ b/frontend/src/locales/de_DE/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Abschluss", "metric-difficulty": "Schwierigkeit", "metric-rating": "Bewertung", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Plattform im Dateisystem fehlt", "more-actions": "Weitere Aktionen", "my-notes": "Meine Notizen", diff --git a/frontend/src/locales/en_GB/rom.json b/frontend/src/locales/en_GB/rom.json index ae78e1e06..05918e906 100644 --- a/frontend/src/locales/en_GB/rom.json +++ b/frontend/src/locales/en_GB/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Completion", "metric-difficulty": "Difficulty", "metric-rating": "Rating", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Missing platform from filesystem", "more-actions": "More actions", "my-notes": "My notes", diff --git a/frontend/src/locales/en_US/rom.json b/frontend/src/locales/en_US/rom.json index 204343830..a24eddcb2 100644 --- a/frontend/src/locales/en_US/rom.json +++ b/frontend/src/locales/en_US/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Completion", "metric-difficulty": "Difficulty", "metric-rating": "Rating", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Missing platform from filesystem", "more-actions": "More actions", "my-notes": "My notes", diff --git a/frontend/src/locales/es_ES/rom.json b/frontend/src/locales/es_ES/rom.json index 17b33f46c..99f96e647 100644 --- a/frontend/src/locales/es_ES/rom.json +++ b/frontend/src/locales/es_ES/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Completado", "metric-difficulty": "Dificultad", "metric-rating": "Valoración", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Plataforma ausente en el sistema de archivos", "more-actions": "Más acciones", "my-notes": "Mis notas", diff --git a/frontend/src/locales/fr_FR/rom.json b/frontend/src/locales/fr_FR/rom.json index ed5568694..c89d6542f 100644 --- a/frontend/src/locales/fr_FR/rom.json +++ b/frontend/src/locales/fr_FR/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Complétion", "metric-difficulty": "Difficulté", "metric-rating": "Note", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Plateforme manquante du système de fichiers", "more-actions": "Plus d'actions", "my-notes": "Mes notes", diff --git a/frontend/src/locales/hu_HU/rom.json b/frontend/src/locales/hu_HU/rom.json index d368580b4..b1e68d4a7 100644 --- a/frontend/src/locales/hu_HU/rom.json +++ b/frontend/src/locales/hu_HU/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Befejezés", "metric-difficulty": "Nehézség", "metric-rating": "Értékelés", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Hiányzó platform a fájlrendszerből", "more-actions": "További műveletek", "my-notes": "Jegyzeteim", diff --git a/frontend/src/locales/it_IT/rom.json b/frontend/src/locales/it_IT/rom.json index fa42ebe80..66ba2eff7 100644 --- a/frontend/src/locales/it_IT/rom.json +++ b/frontend/src/locales/it_IT/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Completamento", "metric-difficulty": "Difficoltà", "metric-rating": "Valutazione", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Piattaforma mancante dal filesystem", "more-actions": "Altre azioni", "my-notes": "Mie note", diff --git a/frontend/src/locales/ja_JP/rom.json b/frontend/src/locales/ja_JP/rom.json index 2d6aa7529..b00745b50 100644 --- a/frontend/src/locales/ja_JP/rom.json +++ b/frontend/src/locales/ja_JP/rom.json @@ -242,6 +242,7 @@ "metric-completion": "完了度", "metric-difficulty": "難易度", "metric-rating": "評価", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "ファイルシステムにプラットフォームが存在しません", "more-actions": "その他の操作", "my-notes": "メモ", diff --git a/frontend/src/locales/ko_KR/rom.json b/frontend/src/locales/ko_KR/rom.json index 49d2ff5a6..85cf40ca4 100644 --- a/frontend/src/locales/ko_KR/rom.json +++ b/frontend/src/locales/ko_KR/rom.json @@ -242,6 +242,7 @@ "metric-completion": "완료율", "metric-difficulty": "난이도", "metric-rating": "평가", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "파일 시스템에서 누락된 플랫폼", "more-actions": "추가 작업", "my-notes": "개인 노트", diff --git a/frontend/src/locales/pl_PL/rom.json b/frontend/src/locales/pl_PL/rom.json index 201938764..bb13adce0 100644 --- a/frontend/src/locales/pl_PL/rom.json +++ b/frontend/src/locales/pl_PL/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Ukończenie", "metric-difficulty": "Trudność", "metric-rating": "Ocena", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Brakująca platforma z systemu plików", "more-actions": "Więcej akcji", "my-notes": "Moje notatki", diff --git a/frontend/src/locales/pt_BR/rom.json b/frontend/src/locales/pt_BR/rom.json index 63e92c604..b59252433 100644 --- a/frontend/src/locales/pt_BR/rom.json +++ b/frontend/src/locales/pt_BR/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Conclusão", "metric-difficulty": "Dificuldade", "metric-rating": "Avaliação", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Plataforma ausente do sistema de arquivos", "more-actions": "Mais ações", "my-notes": "Minhas notas", diff --git a/frontend/src/locales/ro_RO/rom.json b/frontend/src/locales/ro_RO/rom.json index 68d2028f9..980a32e9a 100644 --- a/frontend/src/locales/ro_RO/rom.json +++ b/frontend/src/locales/ro_RO/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Finalizare", "metric-difficulty": "Dificultate", "metric-rating": "Evaluare", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Platformă lipsă din sistemul de fișiere", "more-actions": "Mai multe acțiuni", "my-notes": "Notițele mele", diff --git a/frontend/src/locales/ru_RU/rom.json b/frontend/src/locales/ru_RU/rom.json index 204477725..3f0924265 100644 --- a/frontend/src/locales/ru_RU/rom.json +++ b/frontend/src/locales/ru_RU/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Прохождение", "metric-difficulty": "Сложность", "metric-rating": "Рейтинг", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Платформа отсутствует в файловой системе", "more-actions": "Ещё действия", "my-notes": "Мои заметки", diff --git a/frontend/src/locales/tr_TR/rom.json b/frontend/src/locales/tr_TR/rom.json index d89d491ea..3e31ede98 100644 --- a/frontend/src/locales/tr_TR/rom.json +++ b/frontend/src/locales/tr_TR/rom.json @@ -242,6 +242,7 @@ "metric-completion": "Tamamlama", "metric-difficulty": "Zorluk", "metric-rating": "Puan", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "Platform dosya sisteminde bulunamadı", "more-actions": "Daha fazla işlem", "my-notes": "Notlarım", diff --git a/frontend/src/locales/zh_CN/rom.json b/frontend/src/locales/zh_CN/rom.json index 0ee011b78..5b67e75af 100644 --- a/frontend/src/locales/zh_CN/rom.json +++ b/frontend/src/locales/zh_CN/rom.json @@ -242,6 +242,7 @@ "metric-completion": "完成度", "metric-difficulty": "难度", "metric-rating": "评分", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "文件系统中缺失的平台", "more-actions": "更多操作", "my-notes": "我的笔记", diff --git a/frontend/src/locales/zh_TW/rom.json b/frontend/src/locales/zh_TW/rom.json index 9519c8b95..82f4d896b 100644 --- a/frontend/src/locales/zh_TW/rom.json +++ b/frontend/src/locales/zh_TW/rom.json @@ -242,6 +242,7 @@ "metric-completion": "完成度", "metric-difficulty": "難度", "metric-rating": "評分", + "missing-from-fs-path": "Missing from filesystem: {path}", "missing-platform": "檔案系統中缺少平台", "more-actions": "更多動作", "my-notes": "我的筆記", diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue index 0773b42e9..bfb469107 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FileRow.vue @@ -18,6 +18,7 @@ import { useI18n } from "vue-i18n"; import type { RomFileCategory, RomFileSchema } from "@/__generated__"; import { formatBytes } from "@/utils"; import HashChip from "@/v2/components/shared/HashChip.vue"; +import MissingFSBadge from "@/v2/components/shared/MissingFSBadge.vue"; defineOptions({ inheritAttrs: false }); @@ -38,6 +39,8 @@ const props = defineProps<{ showCategoryBadge: boolean; /** Show the per-row delete button (gated on the caller's grant). */ canDelete: boolean; + /** The rom's file is not on disk, so there is nothing to fetch. */ + missing: boolean; }>(); const emit = defineEmits<{ @@ -142,6 +145,11 @@ const hasAnyHash = computed( {{ displayPath }} +
@@ -211,6 +219,7 @@ const hasAnyHash = computed( icon="mdi-download-outline" variant="text" size="small" + :disabled="missing" :tooltip="t('rom.download-file')" :aria-label="t('rom.download-named', { name: relativePath })" @click="emit('download')" @@ -219,6 +228,7 @@ const hasAnyHash = computed( icon="mdi-link-variant" variant="text" size="small" + :disabled="missing" :tooltip="t('rom.copy-download-link-title')" :aria-label="t('rom.copy-link-for', { path: relativePath })" @click="emit('copyLink')" diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FilesSummary.vue b/frontend/src/v2/components/GameDetails/FilesTab/FilesSummary.vue index db8abbce5..f76d815f3 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FilesSummary.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FilesSummary.vue @@ -4,6 +4,7 @@ // Carries the missing-from-fs flag when applicable. import { RIcon } from "@v2/lib"; import { computed } from "vue"; +import { useI18n } from "vue-i18n"; import type { DetailedRomSchema } from "@/__generated__"; import { formatBytes } from "@/utils"; import HashChip from "@/v2/components/shared/HashChip.vue"; @@ -12,6 +13,8 @@ import MissingFSBadge from "@/v2/components/shared/MissingFSBadge.vue"; defineOptions({ inheritAttrs: false }); +const { t } = useI18n(); + const props = defineProps<{ rom: DetailedRomSchema }>(); const fileCount = computed(() => props.rom.files?.length ?? 0); @@ -44,7 +47,11 @@ const hashes = computed(() => { {{ rom.fs_name }}
diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts index bb4d4d4a8..6d4e38ab3 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts +++ b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.test.ts @@ -71,6 +71,7 @@ function rom(overrides: Partial = {}): DetailedRomSchema { full_path: ROM_PATH, has_simple_single_file: false, fs_size_bytes: 20, + missing_from_fs: false, files: [file(1, "game.n64"), file(2, "hack/patched.n64")], ...overrides, } as DetailedRomSchema; @@ -229,3 +230,37 @@ describe("FilesTab uploads", () => { expect(refetchRom).not.toHaveBeenCalled(); }); }); + +describe("FilesTab on a rom missing from the filesystem", () => { + beforeEach(() => { + setActivePinia(createPinia()); + vi.clearAllMocks(); + routeQuery.subtab = undefined; + grants.upload = true; + }); + + // Nothing is on disk to fetch, so the download endpoint would 404. + it("marks every row missing and refuses the fetch actions", async () => { + const wrapper = mountTab(rom({ missing_from_fs: true })); + await flushPromises(); + + const rows = wrapper.findAllComponents({ name: "FileRow" }); + expect(rows.length).toBeGreaterThan(0); + expect(rows.every((r) => r.props("missing") === true)).toBe(true); + + wrapper.findAllComponents({ name: "FileRow" })[0].vm.$emit("toggle"); + await flushPromises(); + const download = wrapper + .findAll("button.btn") + .find((b) => b.attributes("data-icon") === "mdi-cloud-download-outline"); + expect(download?.attributes("disabled")).toBeDefined(); + }); + + it("leaves the actions alone when the rom is on disk", async () => { + const wrapper = mountTab(); + await flushPromises(); + + const rows = wrapper.findAllComponents({ name: "FileRow" }); + expect(rows.every((r) => r.props("missing") === false)).toBe(true); + }); +}); diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue index 12b605496..379fd34f9 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue @@ -773,6 +773,7 @@ async function refreshRom() { icon="mdi-cloud-download-outline" variant="text" size="small" + :disabled="rom.missing_from_fs" :tooltip="t('rom.download-selected')" :aria-label="t('rom.download-selected')" @click="downloadSelected" @@ -781,6 +782,7 @@ async function refreshRom() { icon="mdi-link-variant" variant="text" size="small" + :disabled="rom.missing_from_fs" :tooltip="t('rom.copy-link-action')" :aria-label="t('rom.copy-link-action')" @click="copySelectedLink" @@ -827,6 +829,7 @@ async function refreshRom() { :show-row-icon="subTab === 'all'" :show-category-badge="subTab === 'all'" :can-delete="canDelete" + :missing="rom.missing_from_fs" @toggle="toggleFile(file)" @download="downloadFile(file)" @copy-link="copyFileLink(file)" From 27da58c6fe6d9aa377b6cdc153915f095d6f5449 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 12:47:53 +0200 Subject: [PATCH 03/28] fix(tasks): refuse a manual task run when no worker is listening A task run with no RQ worker sat queued forever while the UI reported it queued and later refreshed as if it had run. The endpoint now answers 503 with the reason, the Settings sections show that reason instead of the axios wrapper, and the developer setup documents how to start the workers. The delete-ROM dialog's filesystem warning gets its bottom padding above the footer, and the cleanup-queued message loses its em dash in every locale. Co-Authored-By: Claude Fable 5.1 --- DEVELOPER_SETUP.md | 10 +++++ backend/endpoints/tasks.py | 10 ++++- backend/tests/endpoints/test_tasks.py | 37 +++++++++++++++++-- frontend/src/locales/bg_BG/settings.json | 2 +- frontend/src/locales/cs_CZ/settings.json | 2 +- frontend/src/locales/de_DE/settings.json | 2 +- frontend/src/locales/en_GB/settings.json | 2 +- frontend/src/locales/en_US/settings.json | 2 +- frontend/src/locales/es_ES/settings.json | 2 +- frontend/src/locales/fr_FR/settings.json | 2 +- frontend/src/locales/hu_HU/settings.json | 2 +- frontend/src/locales/it_IT/settings.json | 2 +- frontend/src/locales/ja_JP/settings.json | 2 +- frontend/src/locales/ko_KR/settings.json | 2 +- frontend/src/locales/pl_PL/settings.json | 2 +- frontend/src/locales/pt_BR/settings.json | 2 +- frontend/src/locales/ro_RO/settings.json | 2 +- frontend/src/locales/ru_RU/settings.json | 2 +- frontend/src/locales/tr_TR/settings.json | 2 +- frontend/src/locales/zh_CN/settings.json | 2 +- frontend/src/locales/zh_TW/settings.json | 2 +- .../v2/components/Dialogs/DeleteRomDialog.vue | 2 +- .../Settings/MissingFirmwareSection.vue | 9 ++++- .../Settings/MissingGamesSection.vue | 5 ++- 24 files changed, 82 insertions(+), 27 deletions(-) diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index fcc3d916f..e3967c38c 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -126,6 +126,16 @@ cd backend uv run python3 main.py ``` +#### - Run the task workers + +Manual tasks (the missing ROMs and firmware cleanups, folder sync) and the scheduled jobs run on an RQ worker, and scans on a worker of their own. Without them a task stays queued. + +```sh +cd backend +uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker --with-scheduler high default low +uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker scans +``` + ### Setting up the frontend #### - Install node.js dependencies diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index 781be1b6e..04f8d0694 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -1,7 +1,7 @@ from datetime import datetime, timezone from typing import Any, Final, Mapping, cast -from fastapi import Body, HTTPException, Request +from fastapi import Body, HTTPException, Request, status from rq import Worker from rq.exceptions import NoSuchJobError from rq.job import Job, JobStatus @@ -27,6 +27,7 @@ from handler.redis_handler import ( ALL_QUEUES, get_job_func_name, get_worker_current_job, + low_prio_queue, redis_client, ) from tasks.registry import MANUAL_TASKS, SCHEDULED_TASKS, enqueue_task @@ -301,6 +302,13 @@ async def run_single_task( detail=f"Task '{task_name}' cannot be run", ) + # Without a worker the job would sit queued while the UI reports it done. + if not Worker.all(queue=low_prio_queue, connection=redis_client): + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="No task worker is running, so the task cannot be queued", + ) + # The caller's arguments are nested rather than spread, so a body cannot # name a different task than the one this route just authorized. job = enqueue_task(task_name, task_kwargs=task_kwargs or {}) diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index bc5045bc1..43d594aaa 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -254,10 +254,11 @@ class TestRunSingleTask: ) def test_run_single_task_success(self, mock_enqueue, client, access_token): """Test successful running of a single task""" - response = client.post( - "/api/tasks/run/test_task", - headers={"Authorization": f"Bearer {access_token}"}, - ) + with patch("endpoints.tasks.Worker.all", return_value=[Mock()]): + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) assert response.status_code == status.HTTP_200_OK data = response.json() @@ -271,6 +272,34 @@ class TestRunSingleTask: mock_enqueue.assert_called_once() + @patch("endpoints.tasks.enqueue_task") + @patch( + "endpoints.tasks.RUNNABLE_TASKS", + { + "test_task": Mock( + spec=Task, + task_type=TaskType.CLEANUP, + title="Test Task", + enabled=True, + manual_run=True, + can_run_manually=True, + run=Mock(), + ), + }, + ) + def test_run_single_task_without_a_worker_is_refused( + self, mock_enqueue, client, access_token + ): + with patch("endpoints.tasks.Worker.all", return_value=[]): + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE + assert "worker" in response.json()["detail"] + mock_enqueue.assert_not_called() + @patch("endpoints.tasks.RUNNABLE_TASKS", {}) def test_run_single_task_not_found(self, client, access_token): """Test running a non-existent task""" diff --git a/frontend/src/locales/bg_BG/settings.json b/frontend/src/locales/bg_BG/settings.json index e44881f55..6e054e4ac 100644 --- a/frontend/src/locales/bg_BG/settings.json +++ b/frontend/src/locales/bg_BG/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Това ще изтрие окончателно всички липсващи ROM-ове{platform} от базата данни и техните директории. Това действие е необратимо.", "cleanup-firmware-confirm": "Това ще изтрие окончателно всеки запис за фърмуер{platform}, чийто файл липсва от файловата система. Нищо няма да бъде премахнато от диска.", "cleanup-firmware-queued": "Задачата за почистване е на опашка, липсващият фърмуер ще бъде изтрит скоро", - "cleanup-queued": "Задачата за почистване е на опашка — липсващите ROM-ове ще бъдат изтрити скоро", + "cleanup-queued": "Задачата за почистване е на опашка, липсващите ROM-ове ще бъдат изтрити скоро", "client-api-tokens": "API токени", "client-token-confirm-delete": "Сигурен ли си, че искаш да отмениш този токен? Всички устройства които го използват ще загубят достъп.", "client-token-confirm-regenerate": "Това ще анулира текущия токен. Всички устройства използващи стария токен ще трябва да се сдвоят отново.", diff --git a/frontend/src/locales/cs_CZ/settings.json b/frontend/src/locales/cs_CZ/settings.json index 8d6eff176..551e45a3e 100644 --- a/frontend/src/locales/cs_CZ/settings.json +++ b/frontend/src/locales/cs_CZ/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Tímto se z databáze trvale odstraní každý záznam firmwaru{platform}, jehož soubor v souborovém systému chybí. Na disku se nic nesmaže.", "cleanup-firmware-queued": "Úloha vyčištění zařazena do fronty, chybějící firmware bude brzy smazán", - "cleanup-queued": "Úloha vyčištění zařazena do fronty — chybějící ROMy budou brzy smazány", + "cleanup-queued": "Úloha vyčištění zařazena do fronty, chybějící ROMy budou brzy smazány", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/de_DE/settings.json b/frontend/src/locales/de_DE/settings.json index f8652f65b..82aac3b55 100644 --- a/frontend/src/locales/de_DE/settings.json +++ b/frontend/src/locales/de_DE/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Dadurch wird jeder Firmware-Eintrag{platform}, dessen Datei im Dateisystem fehlt, dauerhaft aus der Datenbank gelöscht. Auf der Festplatte wird nichts entfernt.", "cleanup-firmware-queued": "Bereinigungsaufgabe in Warteschlange, fehlende Firmware wird in Kürze gelöscht", - "cleanup-queued": "Bereinigungsaufgabe in Warteschlange — fehlende ROMs werden in Kürze gelöscht", + "cleanup-queued": "Bereinigungsaufgabe in Warteschlange, fehlende ROMs werden in Kürze gelöscht", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/en_GB/settings.json b/frontend/src/locales/en_GB/settings.json index 33cee5a75..15991bb83 100644 --- a/frontend/src/locales/en_GB/settings.json +++ b/frontend/src/locales/en_GB/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "This will permanently delete every firmware entry{platform} whose file is missing from the filesystem. Nothing is removed from disk.", "cleanup-firmware-queued": "Cleanup task queued, missing firmware will be deleted shortly", - "cleanup-queued": "Cleanup task queued — missing ROMs will be deleted shortly", + "cleanup-queued": "Cleanup task queued, missing ROMs will be deleted shortly", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/en_US/settings.json b/frontend/src/locales/en_US/settings.json index d937dfb81..a65550cbc 100644 --- a/frontend/src/locales/en_US/settings.json +++ b/frontend/src/locales/en_US/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "This will permanently delete every firmware entry{platform} whose file is missing from the filesystem. Nothing is removed from disk.", "cleanup-firmware-queued": "Cleanup task queued, missing firmware will be deleted shortly", - "cleanup-queued": "Cleanup task queued — missing ROMs will be deleted shortly", + "cleanup-queued": "Cleanup task queued, missing ROMs will be deleted shortly", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/es_ES/settings.json b/frontend/src/locales/es_ES/settings.json index 436d9086f..8288d1918 100644 --- a/frontend/src/locales/es_ES/settings.json +++ b/frontend/src/locales/es_ES/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Esto eliminará permanentemente de la base de datos cada entrada de firmware{platform} cuyo archivo falte en el sistema de archivos. No se elimina nada del disco.", "cleanup-firmware-queued": "Tarea de limpieza en cola, el firmware ausente se eliminará en breve", - "cleanup-queued": "Tarea de limpieza en cola — las ROMs ausentes se eliminarán en breve", + "cleanup-queued": "Tarea de limpieza en cola, las ROMs ausentes se eliminarán en breve", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/fr_FR/settings.json b/frontend/src/locales/fr_FR/settings.json index fa935cda0..e51b89588 100644 --- a/frontend/src/locales/fr_FR/settings.json +++ b/frontend/src/locales/fr_FR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Cette action supprimera définitivement de la base de données chaque entrée de firmware{platform} dont le fichier est absent du système de fichiers. Rien n'est supprimé du disque.", "cleanup-firmware-queued": "Tâche de nettoyage mise en file d'attente, les firmwares manquants seront supprimés sous peu", - "cleanup-queued": "Tâche de nettoyage mise en file d'attente — les ROMs manquantes seront supprimées sous peu", + "cleanup-queued": "Tâche de nettoyage mise en file d'attente, les ROMs manquantes seront supprimées sous peu", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/hu_HU/settings.json b/frontend/src/locales/hu_HU/settings.json index 852efb92c..bec569027 100644 --- a/frontend/src/locales/hu_HU/settings.json +++ b/frontend/src/locales/hu_HU/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Ez véglegesen törli az adatbázisból minden olyan firmware-bejegyzést{platform}, amelynek a fájlja hiányzik a fájlrendszerből. A lemezről semmi sem törlődik.", "cleanup-firmware-queued": "Takarítási feladat sorba állítva, a hiányzó firmware hamarosan törlődik", - "cleanup-queued": "Takarítási feladat sorba állítva — a hiányzó ROM-ok hamarosan törlődnek", + "cleanup-queued": "Takarítási feladat sorba állítva, a hiányzó ROM-ok hamarosan törlődnek", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/it_IT/settings.json b/frontend/src/locales/it_IT/settings.json index 0a765ff44..a7b82eddf 100644 --- a/frontend/src/locales/it_IT/settings.json +++ b/frontend/src/locales/it_IT/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Questa azione eliminerà definitivamente dal database ogni voce di firmware{platform} il cui file manca dal filesystem. Nulla viene rimosso dal disco.", "cleanup-firmware-queued": "Attività di pulizia accodata, il firmware mancante verrà eliminato a breve", - "cleanup-queued": "Attività di pulizia accodata — le ROM mancanti verranno eliminate a breve", + "cleanup-queued": "Attività di pulizia accodata, le ROM mancanti verranno eliminate a breve", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index b9b1eac35..453fc2a3d 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "ファイルシステムにファイルが存在しないファームウェアの登録{platform}をデータベースから完全に削除します。ディスク上のファイルは削除されません。", "cleanup-firmware-queued": "クリーンアップタスクをキューに追加しました。不足しているファームウェアはまもなく削除されます", - "cleanup-queued": "クリーンアップタスクをキューに追加しました — 不足しているROMはまもなく削除されます", + "cleanup-queued": "クリーンアップタスクをキューに追加しました, 不足しているROMはまもなく削除されます", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index 675e110d8..f0fcbab95 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "파일 시스템에서 파일이 사라진 모든 펌웨어 항목{platform}을 데이터베이스에서 영구적으로 삭제합니다. 디스크에서는 아무것도 삭제되지 않습니다.", "cleanup-firmware-queued": "정리 작업이 대기열에 추가되었습니다. 누락된 펌웨어는 곧 삭제됩니다", - "cleanup-queued": "정리 작업이 대기열에 추가되었습니다 — 누락된 ROM은 곧 삭제됩니다", + "cleanup-queued": "정리 작업이 대기열에 추가되었습니다, 누락된 ROM은 곧 삭제됩니다", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/pl_PL/settings.json b/frontend/src/locales/pl_PL/settings.json index 37e4589ce..862779eac 100644 --- a/frontend/src/locales/pl_PL/settings.json +++ b/frontend/src/locales/pl_PL/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Spowoduje to trwałe usunięcie z bazy danych każdego wpisu oprogramowania{platform}, którego plik nie istnieje w systemie plików. Nic nie zostanie usunięte z dysku.", "cleanup-firmware-queued": "Zadanie czyszczenia w kolejce, brakujące oprogramowanie zostanie wkrótce usunięte", - "cleanup-queued": "Zadanie czyszczenia w kolejce — brakujące ROM-y zostaną wkrótce usunięte", + "cleanup-queued": "Zadanie czyszczenia w kolejce, brakujące ROM-y zostaną wkrótce usunięte", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/pt_BR/settings.json b/frontend/src/locales/pt_BR/settings.json index b6e6d637c..69b38e47e 100644 --- a/frontend/src/locales/pt_BR/settings.json +++ b/frontend/src/locales/pt_BR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Isso excluirá permanentemente do banco de dados todas as ROMs ausentes{platform} e seus diretórios de recursos. Esta ação não pode ser desfeita.", "cleanup-firmware-confirm": "Isso excluirá permanentemente do banco de dados cada entrada de firmware{platform} cujo arquivo esteja ausente no sistema de arquivos. Nada é removido do disco.", "cleanup-firmware-queued": "Tarefa de limpeza na fila, o firmware ausente será excluído em breve", - "cleanup-queued": "Tarefa de limpeza na fila — as ROMs ausentes serão excluídas em breve", + "cleanup-queued": "Tarefa de limpeza na fila, as ROMs ausentes serão excluídas em breve", "client-api-tokens": "Tokens de API de cliente", "client-token-confirm-delete": "Tem certeza de que deseja revogar este token? Qualquer dispositivo que o utilize perderá o acesso.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ro_RO/settings.json b/frontend/src/locales/ro_RO/settings.json index 0015b9032..fdd01ec01 100644 --- a/frontend/src/locales/ro_RO/settings.json +++ b/frontend/src/locales/ro_RO/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Aceasta va șterge definitiv din baza de date fiecare intrare de firmware{platform} al cărei fișier lipsește din sistemul de fișiere. Nu se șterge nimic de pe disc.", "cleanup-firmware-queued": "Sarcina de curățare a fost pusă în coadă, firmware-ul lipsă va fi șters în scurt timp", - "cleanup-queued": "Sarcina de curățare a fost pusă în coadă — ROM-urile lipsă vor fi șterse în scurt timp", + "cleanup-queued": "Sarcina de curățare a fost pusă în coadă, ROM-urile lipsă vor fi șterse în scurt timp", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ru_RU/settings.json b/frontend/src/locales/ru_RU/settings.json index fc092e0ed..8e9fd6ce5 100644 --- a/frontend/src/locales/ru_RU/settings.json +++ b/frontend/src/locales/ru_RU/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "Это навсегда удалит из базы данных каждую запись прошивки{platform}, файл которой отсутствует в файловой системе. С диска ничего не удаляется.", "cleanup-firmware-queued": "Задача очистки поставлена в очередь, отсутствующие прошивки скоро будут удалены", - "cleanup-queued": "Задача очистки поставлена в очередь — отсутствующие ROM-ы скоро будут удалены", + "cleanup-queued": "Задача очистки поставлена в очередь, отсутствующие ROM-ы скоро будут удалены", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/tr_TR/settings.json b/frontend/src/locales/tr_TR/settings.json index 9980d17f7..4af68ae01 100644 --- a/frontend/src/locales/tr_TR/settings.json +++ b/frontend/src/locales/tr_TR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "Bu işlem, veritabanından tüm eksik ROM'ları{platform} ve kaynak dizinlerini kalıcı olarak siler. Bu işlem geri alınamaz.", "cleanup-firmware-confirm": "Bu işlem, dosyası dosya sisteminde bulunmayan her firmware kaydını{platform} veritabanından kalıcı olarak siler. Diskten hiçbir şey silinmez.", "cleanup-firmware-queued": "Temizlik görevi sıraya alındı, eksik firmware kısa süre içinde silinecek", - "cleanup-queued": "Temizlik görevi sıraya alındı — eksik ROM'lar kısa süre içinde silinecek", + "cleanup-queued": "Temizlik görevi sıraya alındı, eksik ROM'lar kısa süre içinde silinecek", "client-api-tokens": "İstemci API Tokenları", "client-token-confirm-delete": "Bu tokenı iptal etmek istediğinizden emin misiniz? Kullanan tüm cihazlar erişimini kaybedecek.", "client-token-confirm-regenerate": "Bu işlem mevcut kimlik bilgisini geçersiz kılacak. Eski tokenı kullanan cihazların yeniden eşleştirilmesi gerekecek.", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index e88aea1f4..73878b961 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "这会从数据库中永久删除所有缺失的 ROM{platform} 及其资源目录。此操作无法撤销。", "cleanup-firmware-confirm": "这将从数据库中永久删除文件已从文件系统中缺失的所有固件条目{platform}。磁盘上的文件不会被删除。", "cleanup-firmware-queued": "清理任务已排队,缺失的固件将很快被删除", - "cleanup-queued": "清理任务已排队 — 缺失的 ROM 将很快被删除", + "cleanup-queued": "清理任务已排队, 缺失的 ROM 将很快被删除", "client-api-tokens": "客户端 API 令牌", "client-token-confirm-delete": "确定要吊销此令牌吗?任何使用它的设备都将失去访问权限。", "client-token-confirm-regenerate": "这会使当前凭据失效。任何使用旧令牌的设备都需要重新配对。", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index b49966b49..5f4036918 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "這將從資料庫中永久刪除檔案已從檔案系統中缺失的所有韌體項目{platform}。磁碟上的檔案不會被刪除。", "cleanup-firmware-queued": "清理任務已排程,缺失的韌體將在稍後被刪除", - "cleanup-queued": "清理任務已排程 — 缺失的 ROM 將在稍後被刪除", + "cleanup-queued": "清理任務已排程, 缺失的 ROM 將在稍後被刪除", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue b/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue index 5fde135cb..c17f84c37 100644 --- a/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue +++ b/frontend/src/v2/components/Dialogs/DeleteRomDialog.vue @@ -423,7 +423,7 @@ function closeDialog() { } .r-v2-del-rom__append { - padding: 10px 14px 0; + padding: 10px 14px 12px; display: flex; flex-direction: column; gap: 8px; diff --git a/frontend/src/v2/components/Settings/MissingFirmwareSection.vue b/frontend/src/v2/components/Settings/MissingFirmwareSection.vue index bf6a2eb5d..3190f452c 100644 --- a/frontend/src/v2/components/Settings/MissingFirmwareSection.vue +++ b/frontend/src/v2/components/Settings/MissingFirmwareSection.vue @@ -15,6 +15,7 @@ import PlatformSelect from "@/v2/components/shared/PlatformSelect.vue"; import { useConfirm } from "@/v2/composables/useConfirm"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useTaskCompletion } from "@/v2/composables/useTaskCompletion"; +import { errorMessage } from "@/v2/utils/errorMessage"; defineOptions({ inheritAttrs: false }); @@ -74,7 +75,9 @@ async function fetchMissingFirmware() { ); } catch (err) { snackbar.error( - t("settings.couldnt-fetch-missing-firmware", { error: String(err) }), + t("settings.couldnt-fetch-missing-firmware", { + error: errorMessage(err), + }), ); } finally { loading.value = false; @@ -103,7 +106,9 @@ async function cleanupAll() { snackbar.success(t("settings.cleanup-firmware-queued")); if (await awaitTask(data.task_id)) await fetchMissingFirmware(); } catch (err) { - snackbar.error(t("settings.couldnt-queue-cleanup", { error: String(err) })); + snackbar.error( + t("settings.couldnt-queue-cleanup", { error: errorMessage(err) }), + ); } finally { cleaningUp.value = false; } diff --git a/frontend/src/v2/components/Settings/MissingGamesSection.vue b/frontend/src/v2/components/Settings/MissingGamesSection.vue index c8ab5ff12..46b7494c2 100644 --- a/frontend/src/v2/components/Settings/MissingGamesSection.vue +++ b/frontend/src/v2/components/Settings/MissingGamesSection.vue @@ -45,6 +45,7 @@ import { useTaskCompletion } from "@/v2/composables/useTaskCompletion"; import { useWebpSupport } from "@/v2/composables/useWebpSupport"; import storeGalleryRoms, { NO_SIDECARS } from "@/v2/stores/galleryRoms"; import storeGallerySelection from "@/v2/stores/gallerySelection"; +import { errorMessage } from "@/v2/utils/errorMessage"; interface PlatformItem { id: number; @@ -238,7 +239,9 @@ async function cleanupAll() { await galleryRoms.fetchInitialMetadata(NO_SIDECARS); } } catch (err) { - snackbar.error(t("settings.couldnt-queue-cleanup", { error: String(err) })); + snackbar.error( + t("settings.couldnt-queue-cleanup", { error: errorMessage(err) }), + ); } finally { cleaningUp.value = false; } From 91134e8cfe7691d153d5ffa1cf0e6354ca7784ff Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 13:20:38 +0200 Subject: [PATCH 04/28] test(player): cover the state screenshot wiring The player and console callbacks now share `resolveStateScreenshot` (live canvas first, EmulatorJS's picture as the fallback) and the console builds its multipart body through `buildStateFormData`, so the utils spec can check what reaches the upload: the screenshot named after the state, no screenshot part without a picture, and the fallback order. Co-Authored-By: Claude Fable 5.1 --- frontend/src/console/views/Play.vue | 27 ++----- .../src/views/Player/EmulatorJS/Player.vue | 4 +- .../src/views/Player/EmulatorJS/utils.test.ts | 79 +++++++++++++++++++ frontend/src/views/Player/EmulatorJS/utils.ts | 32 +++++++- 4 files changed, 118 insertions(+), 24 deletions(-) diff --git a/frontend/src/console/views/Play.vue b/frontend/src/console/views/Play.vue index e0fed5820..2616e1712 100644 --- a/frontend/src/console/views/Play.vue +++ b/frontend/src/console/views/Play.vue @@ -12,10 +12,7 @@ import { } from "vue"; import { useI18n } from "vue-i18n"; import { useRoute, useRouter } from "vue-router"; -import type { - Body_add_state_api_states_post as AddStateInput, - FirmwareSchema, -} from "@/__generated__"; +import type { FirmwareSchema } from "@/__generated__"; import NavigationText from "@/console/components/NavigationText.vue"; import { useInputScope } from "@/console/composables/useInputScope"; import { useThemeAssets } from "@/console/composables/useThemeAssets"; @@ -35,8 +32,10 @@ import { areThreadsRequiredForEJSCore, getDownloadPath, } from "@/utils"; -import { buildFormInput } from "@/utils/formData"; -import { captureStateScreenshot } from "@/views/Player/EmulatorJS/utils"; +import { + buildStateFormData, + resolveStateScreenshot, +} from "@/views/Player/EmulatorJS/utils"; import { installEJSDefaultOptionsTrap, invalidateEmulatorJSRomCacheIfRenamed, @@ -536,21 +535,9 @@ async function boot() { state: ArrayBuffer; screenshot?: ArrayBuffer; }) { - const screenshotFile = - (await captureStateScreenshot()) ?? emulatorScreenshot; + const screenshotFile = await resolveStateScreenshot(emulatorScreenshot); try { - const formData = buildFormInput([ - ["stateFile", new Blob([stateFile]), "state.save"], - ...(screenshotFile - ? ([ - [ - "screenshotFile", - new Blob([screenshotFile], { type: "image/png" }), - "screenshot.png", - ], - ] as const) - : []), - ]); + const formData = buildStateFormData(stateFile, screenshotFile); await api.post("/states", formData, { headers: { "Content-Type": "multipart/form-data" }, diff --git a/frontend/src/views/Player/EmulatorJS/Player.vue b/frontend/src/views/Player/EmulatorJS/Player.vue index a5a2c883a..fec1dd753 100644 --- a/frontend/src/views/Player/EmulatorJS/Player.vue +++ b/frontend/src/views/Player/EmulatorJS/Player.vue @@ -26,7 +26,7 @@ import { } from "@/utils"; import { saveSave, - captureStateScreenshot, + resolveStateScreenshot, saveState, loadEmulatorJSSave, loadEmulatorJSState, @@ -461,7 +461,7 @@ window.EJS_onSaveState = async function ({ state: stateFile, screenshot: emulatorScreenshot, }) { - const screenshotFile = (await captureStateScreenshot()) ?? emulatorScreenshot; + const screenshotFile = await resolveStateScreenshot(emulatorScreenshot); const state = await saveState({ rom: romRef.value, stateFile, diff --git a/frontend/src/views/Player/EmulatorJS/utils.test.ts b/frontend/src/views/Player/EmulatorJS/utils.test.ts index f8dcad82d..95304acb0 100644 --- a/frontend/src/views/Player/EmulatorJS/utils.test.ts +++ b/frontend/src/views/Player/EmulatorJS/utils.test.ts @@ -1,22 +1,30 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { SaveSchema } from "@/__generated__"; +import type { StateSchema } from "@/__generated__"; import type { DetailedRom } from "@/stores/roms"; import { + buildStateFormData, captureStateScreenshot, createSaveSyncTracker, installEJSDefaultOptionsTrap, + resolveStateScreenshot, saveSave, + saveState, } from "./utils"; const saveApiMocks = vi.hoisted(() => ({ uploadSaves: vi.fn(), updateSave: vi.fn(), })); +const stateApiMocks = vi.hoisted(() => ({ + uploadStates: vi.fn(), +})); vi.mock("@/services/api/save", async (importOriginal) => ({ ...(await importOriginal()), default: saveApiMocks, })); +vi.mock("@/services/api/state", () => ({ default: stateApiMocks })); const STORAGE_KEY = "ejs-7-n64-Test Game-settings"; @@ -270,6 +278,77 @@ describe("captureStateScreenshot", () => { }); }); +describe("resolveStateScreenshot", () => { + /* eslint-disable @typescript-eslint/no-explicit-any */ + afterEach(() => { + delete (window as any).EJS_emulator; + }); + + it("prefers the live canvas over what EmulatorJS passed", async () => { + const live = new ArrayBuffer(8); + (window as any).EJS_emulator = { + gameManager: { screenshot: async () => live }, + }; + + await expect(resolveStateScreenshot(new ArrayBuffer(4))).resolves.toBe( + live, + ); + }); + + it("falls back to EmulatorJS's picture when the canvas gives none", async () => { + const fallback = new ArrayBuffer(4); + (window as any).EJS_emulator = {}; + + await expect(resolveStateScreenshot(fallback)).resolves.toBe(fallback); + await expect(resolveStateScreenshot()).resolves.toBeUndefined(); + }); + /* eslint-enable @typescript-eslint/no-explicit-any */ +}); + +describe("saveState", () => { + const bytes = new Uint8Array([1, 2, 3]).buffer; + let rom: DetailedRom; + + beforeEach(() => { + rom = { + id: 1, + fs_name_no_ext: "game", + user_states: [], + } as unknown as DetailedRom; + stateApiMocks.uploadStates.mockReset(); + stateApiMocks.uploadStates.mockResolvedValue([ + { status: "fulfilled", value: { id: 7 } as StateSchema }, + ]); + }); + + it("uploads the screenshot named after the state", async () => { + await saveState({ rom, stateFile: bytes, screenshotFile: bytes }); + + const { statesToUpload } = stateApiMocks.uploadStates.mock.calls[0][0]; + expect(statesToUpload[0].screenshotFile.name).toMatch(/^game \[.*\]\.png$/); + expect(rom.user_states).toEqual([{ id: 7 }]); + }); + + it("still uploads the state when there is no screenshot", async () => { + await saveState({ rom, stateFile: bytes }); + + const { statesToUpload } = stateApiMocks.uploadStates.mock.calls[0][0]; + expect(statesToUpload[0].screenshotFile).toBeUndefined(); + }); +}); + +describe("buildStateFormData", () => { + const bytes = new Uint8Array([1, 2, 3]).buffer; + + it("adds the screenshot part only when there is a picture", () => { + expect( + buildStateFormData(bytes, bytes).get("screenshotFile"), + ).toBeInstanceOf(Blob); + expect(buildStateFormData(bytes).get("screenshotFile")).toBeNull(); + expect(buildStateFormData(bytes).get("stateFile")).toBeInstanceOf(Blob); + }); +}); + describe("saveSave", () => { const save = { id: 3, file_name: "a.srm", slot: "main_quest" } as SaveSchema; const updated = { ...save, file_size_bytes: 4 } as SaveSchema; diff --git a/frontend/src/views/Player/EmulatorJS/utils.ts b/frontend/src/views/Player/EmulatorJS/utils.ts index 5afaf3a97..619f8ca77 100644 --- a/frontend/src/views/Player/EmulatorJS/utils.ts +++ b/frontend/src/views/Player/EmulatorJS/utils.ts @@ -1,9 +1,13 @@ import Bowser from "bowser"; -import { type SaveSchema } from "@/__generated__"; -import { type StateSchema } from "@/__generated__"; +import { + type Body_add_state_api_states_post as AddStateInput, + type SaveSchema, + type StateSchema, +} from "@/__generated__"; import saveApi, { AUTOSAVE_SLOT } from "@/services/api/save"; import stateApi from "@/services/api/state"; import { type DetailedRom } from "@/stores/roms"; +import { buildFormInput } from "@/utils/formData"; function buildStateName(rom: DetailedRom): string { const romName = rom.fs_name_no_ext.trim(); @@ -24,6 +28,30 @@ export async function captureStateScreenshot(): Promise< } } +/** The picture for a save state: the live canvas, else what EmulatorJS passed. */ +export async function resolveStateScreenshot( + emulatorScreenshot?: ArrayBuffer, +): Promise { + return (await captureStateScreenshot()) ?? emulatorScreenshot; +} + +/** Console-mode state upload; without a picture there is no screenshot part. */ +export function buildStateFormData( + stateFile: ArrayBuffer, + screenshotFile?: ArrayBuffer, +): FormData { + return buildFormInput([ + ["stateFile", new Blob([stateFile]), "state.save"], + [ + "screenshotFile", + screenshotFile + ? new Blob([screenshotFile], { type: "image/png" }) + : undefined, + "screenshot.png", + ], + ]); +} + export async function saveState({ rom, stateFile, From 3972feabb55b60c768e7054fd56cf83281e18050 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 13:30:15 +0200 Subject: [PATCH 05/28] fix(tasks): describe the cleanup stats a finished job actually carries `GET /tasks/status` failed response validation once a missing-ROMs cleanup had run: the task reports `platform_ids` while the schema still declared `platform_id`, and the missing-firmware cleanup had no schema at all. Both shapes are declared now, the generated types follow, and the task-by-id test checks a finished job of each kind. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01F9ta8rXUTP9aMdatPYKX4K --- backend/endpoints/responses/__init__.py | 15 +++++++- backend/tests/endpoints/test_tasks.py | 37 +++++++++++++++++++ frontend/src/__generated__/index.ts | 1 + .../__generated__/models/CleanupTaskMeta.ts | 3 +- .../models/MissingFirmwareCleanupStats.ts | 11 ++++++ .../models/MissingRomsCleanupStats.ts | 2 +- 6 files changed, 65 insertions(+), 4 deletions(-) create mode 100644 frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts diff --git a/backend/endpoints/responses/__init__.py b/backend/endpoints/responses/__init__.py index b225d6f89..6f1fa89c2 100644 --- a/backend/endpoints/responses/__init__.py +++ b/backend/endpoints/responses/__init__.py @@ -53,13 +53,24 @@ class OrphanedResourcesCleanupStats(TypedDict): class MissingRomsCleanupStats(TypedDict): - platform_id: int | None + platform_ids: list[int] | None roms_found: int roms_deleted: int errors: int -CleanupStats = Union[OrphanedResourcesCleanupStats, MissingRomsCleanupStats] +class MissingFirmwareCleanupStats(TypedDict): + platform_ids: list[int] | None + firmware_found: int + firmware_deleted: int + errors: int + + +CleanupStats = Union[ + OrphanedResourcesCleanupStats, + MissingRomsCleanupStats, + MissingFirmwareCleanupStats, +] class CleanupTaskMeta(TypedDict): diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index 43d594aaa..73db588b2 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -6,6 +6,8 @@ from fastapi import status from rq.exceptions import NoSuchJobError from handler.redis_handler import redis_client +from tasks.manual.cleanup_missing_firmware import CleanupMissingFirmwareStats +from tasks.manual.cleanup_missing_roms import CleanupMissingRomsStats from tasks.tasks import Task, TaskType @@ -411,6 +413,41 @@ class TestGetTasksStatus: class TestGetTaskById: """Test suite for the get_task_by_id endpoint""" + @pytest.mark.parametrize( + "stats", + [ + CleanupMissingRomsStats(platform_ids=[3], roms_found=2, roms_deleted=2), + CleanupMissingFirmwareStats(firmware_found=1, firmware_deleted=1), + ], + ) + @patch("endpoints.tasks.Job.fetch") + def test_a_finished_cleanup_reports_its_stats( + self, mock_job_fetch, client, access_token, stats + ): + mock_job = Mock() + for field in ("enqueued_at", "created_at", "started_at", "ended_at"): + setattr(mock_job, field, Mock()) + getattr(mock_job, field).isoformat.return_value = "2023-01-01T00:00:00" + mock_job.get_meta.return_value = { + "task_key": "cleanup_missing_roms", + "task_type": TaskType.CLEANUP, + "cleanup_stats": stats.to_dict(), + } + mock_job.func_name = "tasks.tasks.run_task_by_name" + mock_job.kwargs = {"name": "cleanup_missing_roms"} + mock_job.get_status.return_value = "finished" + mock_job.id = "cleanup-job" + mock_job.result = stats.to_dict() + mock_job_fetch.return_value = mock_job + + response = client.get( + "/api/tasks/cleanup-job", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["meta"]["cleanup_stats"] == stats.to_dict() + @patch("endpoints.tasks.Job.fetch") def test_get_task_by_id_success(self, mock_job_fetch, client, access_token): """Test successful retrieval of a task by job ID""" diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 95ca60ceb..7ef424937 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -130,6 +130,7 @@ export type { MemoryCardVersionSchema } from './models/MemoryCardVersionSchema'; export type { MetadataCoverageItem } from './models/MetadataCoverageItem'; export type { MetadataMediaType } from './models/MetadataMediaType'; export type { MetadataSourcesDict } from './models/MetadataSourcesDict'; +export type { MissingFirmwareCleanupStats } from './models/MissingFirmwareCleanupStats'; export type { MissingRomsCleanupStats } from './models/MissingRomsCleanupStats'; export type { MobyMetadataPlatform } from './models/MobyMetadataPlatform'; export type { MusicGameFacetSchema } from './models/MusicGameFacetSchema'; diff --git a/frontend/src/__generated__/models/CleanupTaskMeta.ts b/frontend/src/__generated__/models/CleanupTaskMeta.ts index ad55db405..1e0897265 100644 --- a/frontend/src/__generated__/models/CleanupTaskMeta.ts +++ b/frontend/src/__generated__/models/CleanupTaskMeta.ts @@ -2,9 +2,10 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ +import type { MissingFirmwareCleanupStats } from './MissingFirmwareCleanupStats'; import type { MissingRomsCleanupStats } from './MissingRomsCleanupStats'; import type { OrphanedResourcesCleanupStats } from './OrphanedResourcesCleanupStats'; export type CleanupTaskMeta = { - cleanup_stats: (OrphanedResourcesCleanupStats | MissingRomsCleanupStats | null); + cleanup_stats: (OrphanedResourcesCleanupStats | MissingRomsCleanupStats | MissingFirmwareCleanupStats | null); }; diff --git a/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts b/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts new file mode 100644 index 000000000..ed5c09be1 --- /dev/null +++ b/frontend/src/__generated__/models/MissingFirmwareCleanupStats.ts @@ -0,0 +1,11 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type MissingFirmwareCleanupStats = { + platform_ids: (Array | null); + firmware_found: number; + firmware_deleted: number; + errors: number; +}; + diff --git a/frontend/src/__generated__/models/MissingRomsCleanupStats.ts b/frontend/src/__generated__/models/MissingRomsCleanupStats.ts index ced1b85cb..59d8bffc4 100644 --- a/frontend/src/__generated__/models/MissingRomsCleanupStats.ts +++ b/frontend/src/__generated__/models/MissingRomsCleanupStats.ts @@ -3,7 +3,7 @@ /* tslint:disable */ /* eslint-disable */ export type MissingRomsCleanupStats = { - platform_id: (number | null); + platform_ids: (Array | null); roms_found: number; roms_deleted: number; errors: number; From 7a7347f9a90c085d4033fb099186ffb7ac10aa0c Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 16 Sep 2026 07:51:20 -0400 Subject: [PATCH 06/28] docs: require screenshots and mermaid diagrams in PR descriptions A reviewer who can't see a UI change reviews the diff instead of the result, and a boundary change described in prose takes several reads. Ask for both in the PR body: enough screenshots to convey what changed, and a mermaid block when the change moves a boundary. Co-Authored-By: Claude Opus 5 (1M context) --- .claude/skills/pr-ready/SKILL.md | 4 ++ .claude/skills/review-polish/SKILL.md | 65 ++++++++++++++++++++++++++- CLAUDE.md | 2 + 3 files changed, 70 insertions(+), 1 deletion(-) diff --git a/.claude/skills/pr-ready/SKILL.md b/.claude/skills/pr-ready/SKILL.md index 8c97d1fb6..94ee44d49 100644 --- a/.claude/skills/pr-ready/SKILL.md +++ b/.claude/skills/pr-ready/SKILL.md @@ -86,5 +86,9 @@ Finish with one consolidated summary rather than four transcripts: the security verdict, what steps 2 and 3 changed by area, which checks ran and their results, and anything still needing a human decision. +The summary also carries what the PR description needs and the transcripts hold: the +screenshots step 4 captured, as paths the user can drag into the `Screenshots` section, +and the `mermaid` block for a change that moved a boundary. + Four passes in one session is a lot of context. For a very large diff, run the steps in separate sessions against the same `$RANGE`. diff --git a/.claude/skills/review-polish/SKILL.md b/.claude/skills/review-polish/SKILL.md index 18da72963..e47e434a2 100644 --- a/.claude/skills/review-polish/SKILL.md +++ b/.claude/skills/review-polish/SKILL.md @@ -1,6 +1,6 @@ --- name: review-polish -description: The before-review and before-handoff pass for RomM, covering both stacks. First shapes the code the checks can't see — comment and docstring discipline (the single most-corrected thing in this repo), duplicated constants/types/getters, imprecise names, loose typing in tests. Then runs the verification gate that keeps CI green — frontend (typecheck/lint/test/build/i18n/tokens), backend (pytest/alembic/trunk), the OpenAPI regen step, and (for UI) manual browser/theme/input/Storybook checks. Use after the code works, right before committing, opening a PR, or telling the user a change is done. +description: The before-review and before-handoff pass for RomM, covering both stacks. First shapes the code the checks can't see — comment and docstring discipline (the single most-corrected thing in this repo), duplicated constants/types/getters, imprecise names, loose typing in tests. Then runs the verification gate that keeps CI green — frontend (typecheck/lint/test/build/i18n/tokens), backend (pytest/alembic/trunk), the OpenAPI regen step, and (for UI) manual browser/theme/input/Storybook checks. Ends with what the PR description owes a reviewer: screenshots of a UI change, a mermaid diagram of an architectural one. Use after the code works, right before committing, opening a PR, or telling the user a change is done. --- # RomM: Review Polish & Verification @@ -163,6 +163,10 @@ With `uiVersion = "v2"`: - **Responsive sweep:** 320px → 4K across the `useBreakpoint` tiers; overlays full-bleed on `xs`. - **Accessibility:** contrast, keyboard reachability with no traps, aria-labels on icon-only controls. - **Performance:** lists/grids of 1000+ items stay smooth; every `v-for` has a stable `:key`. +- **Screenshots:** capture the change while you're in there, at least one and enough to + convey what's different. Shoot the component or view in its real surroundings, not a + full-page dump, and save to a temp dir outside the repo. + See [F. The PR description](#f-the-pr-description). #### Storybook (for `/lib`) @@ -186,11 +190,67 @@ Run from `backend/`: ### Don't - Open a PR without manually testing the UI when UI was touched. +- Open a PR on a UI change with an empty `Screenshots` section. +- Describe a boundary change in prose alone when a diagram would land it in one read. - `--no-verify` on commits. - Leave a locale key English-only, a token un-generated, or a migration one-directional. --- +## F. The PR description + +Base it on `.github/PULL_REQUEST_TEMPLATE.md`, and carry the two things a reviewer cannot +reconstruct from the diff. + +### Screenshots, for a UI change + +The template's `Screenshots (if applicable)` heading is not optional for a UI change; a reviewer +who can't see the change reviews the diff instead of the result. Shoot enough to give that +reviewer the gist, and stop there: one shot carries most changes. + +- **Before/after** when the change alters something that already existed and the after alone + wouldn't read as different, labelled as such. +- **A second theme** only when the change is theme-dependent; a state or breakpoint only when it's + the point of the change. +- Name the files for what they show (`missing-games-actions.png`), so the handoff list reads on + its own. + +Attachments on github.com live under `user-attachments`, and nothing uploads there from the CLI. +So unless you have a URL the PR body can point at, open the PR with the heading and a one-line +placeholder naming each shot, then give the user the file paths in your summary to drag into the +description. Never commit the images or push them to a branch to get a URL. + +### Mermaid diagram, for an architectural change + +GitHub renders a fenced `mermaid` block in a PR body, so a change that moves a boundary gets one: +a new service, handler, or task in a request or job path; a model or relationship change; a new +external provider or integration; a different call path across layers; an auth, session, or socket +flow. Code that changes inside an existing boundary does not. + +- **Draw what changed**, with the new pieces distinguishable from what was already there. A + diagram that redraws the whole backend teaches nothing. +- **Pick the type for the question:** `flowchart` for a call or data path, `sequenceDiagram` for an + exchange whose order over time is the point (auth handshake, scan lifecycle), `erDiagram` for + models and their relationships. +- **Label the edges** with what crosses them, the call, the payload, the event name, not "uses". +- **No custom colors or styling.** The default theme is the one that reads in both of GitHub's. +- **Make sure it parses.** An unparseable block renders as raw text in the description. When the + syntax isn't one you're sure of, render it first: + `npx -y @mermaid-js/mermaid-cli -i d.mmd -o d.svg -p pc.json`, where `pc.json` is + `{"executablePath": "", "args": ["--no-sandbox"]}` (puppeteer downloads no + browser of its own here). + +```mermaid +flowchart LR + client[Web client] -->|POST /api/roms/scan| api[roms endpoint] + api -->|enqueue| queue[(RQ queue)] + queue --> worker[scan task] + worker -->|emit scan:done| socket[Socket.IO] + socket --> client +``` + +--- + ## Checklist - [ ] No comment or docstring over two lines of prose; no change history, no @@ -202,4 +262,7 @@ Run from `backend/`: pytest, migrations both directions, OpenAPI regen) - [ ] UI changes tested in the browser: both themes, all four input modalities, responsive sweep +- [ ] UI changes screenshotted (enough to convey the change), and the shots + attached to the PR or handed to the user +- [ ] Architectural changes carry a `mermaid` diagram in the PR description - [ ] `trunk fmt && trunk check` clean, with whatever fmt rewrote committed diff --git a/CLAUDE.md b/CLAUDE.md index faceaf031..f058e8820 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -72,6 +72,8 @@ These live in `.claude/skills/` and carry the detailed rules. Invoke the one tha **Python tools live in `backend/tools/`.** Standalone dev/test utilities and scripts (not part of the app runtime) go in `backend/tools/`, not scattered across `backend/`. **Link PRs to issues.** In the PR description, use `Fixes #XXXX` for issue/bug fixes and `Closes #XXXX` for feature implementations. **Use the PR template.** Base every PR description on `.github/PULL_REQUEST_TEMPLATE.md`. +**Show UI changes in the PR.** A PR that touches anything visible ships with at least one screenshot under the template's `Screenshots` heading, captured from the running app during the `review-polish` browser pass. Enough shots to convey what changed, not a catalogue of every state. Save the files outside the repo and never commit them. If you can't attach them to the PR yourself, open the PR with the section in place and hand the user the file paths to drop in. +**Diagram architectural changes in the PR.** When a change moves a boundary (a new service, task, or provider in a path, a model relationship, a different call path across layers, an auth or socket flow), the PR description carries a `mermaid` block showing it. GitHub renders them. Draw what changed, not the whole system. See `review-polish`. --- From bd90488e73f036834c84cdcbe339646591330e7e Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 13:58:45 +0200 Subject: [PATCH 07/28] fix(tasks): count only live workers, and cover the review's gaps The worker guard now ignores workers that announced their death or are suspended, and the tests run with a live worker on the task queue by default, so the other successful-run tests pass again; a scan-only, dead or suspended worker is checked to be refused. The developer setup runs each worker in its own terminal, adds the RQ cron process that registers the schedule, and ties the Redis URL to the `.env` defaults. The Japanese, Korean and Chinese cleanup messages use their own punctuation, and both Settings sections have a test that the server's reason reaches the error snackbar. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01F9ta8rXUTP9aMdatPYKX4K --- DEVELOPER_SETUP.md | 13 +++- backend/endpoints/tasks.py | 20 +++++- backend/tests/endpoints/test_tasks.py | 72 +++++++++++++++++-- frontend/src/locales/ja_JP/settings.json | 2 +- frontend/src/locales/ko_KR/settings.json | 2 +- frontend/src/locales/zh_CN/settings.json | 2 +- frontend/src/locales/zh_TW/settings.json | 2 +- .../Settings/MissingFirmwareSection.test.ts | 65 ++++++++++++++--- .../Settings/MissingGamesSection.test.ts | 71 +++++++++++++++--- 9 files changed, 218 insertions(+), 31 deletions(-) diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index e3967c38c..6b0518c13 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -128,14 +128,25 @@ uv run python3 main.py #### - Run the task workers -Manual tasks (the missing ROMs and firmware cleanups, folder sync) and the scheduled jobs run on an RQ worker, and scans on a worker of their own. Without them a task stays queued. +Manual tasks (the missing ROMs and firmware cleanups, folder sync) and every scheduled job run on RQ workers, and scans on a worker of their own. Without them a task stays queued. Each command is a foreground process, so run them in separate terminals. The Redis URL below matches the `REDIS_*` defaults in `.env`; adjust it if you changed them. ```sh cd backend uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker --with-scheduler high default low +``` + +```sh +cd backend uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker scans ``` +`--with-scheduler` only releases delayed jobs. The recurring schedule itself is registered by the RQ cron process, which the workers then execute: + +```sh +cd backend +RQ_REDIS_URL=redis://127.0.0.1:6379/0 uv run rq cron tasks.cron_config +``` + ### Setting up the frontend #### - Install node.js dependencies diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index 04f8d0694..119957b14 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -2,10 +2,11 @@ from datetime import datetime, timezone from typing import Any, Final, Mapping, cast from fastapi import Body, HTTPException, Request, status -from rq import Worker +from rq import Queue, Worker from rq.exceptions import NoSuchJobError from rq.job import Job, JobStatus from rq.registry import FailedJobRegistry, FinishedJobRegistry +from rq.worker import WorkerStatus from config import ENABLE_RESCAN_ON_FILESYSTEM_CHANGE, RESCAN_ON_FILESYSTEM_CHANGE_DELAY from decorators.auth import protected_route @@ -274,6 +275,19 @@ async def get_task_by_id(request: Request, task_id: str) -> TaskStatusResponse: TASK_KWARGS = Body(default=None) +def _listening_workers(queue: Queue) -> list[Worker]: + """Registered workers of ``queue`` that are alive and not suspended. + + A crashed worker stays registered until its TTL expires, which RQ's own + maintenance sweep bounds; this filters the ones that told us they left. + """ + return [ + worker + for worker in Worker.all(queue=queue, connection=redis_client) + if worker.death_date is None and worker.get_state() != WorkerStatus.SUSPENDED + ] + + @protected_route(router.post, "/run/{task_name}", [Scope.TASKS_RUN]) async def run_single_task( request: Request, @@ -302,8 +316,8 @@ async def run_single_task( detail=f"Task '{task_name}' cannot be run", ) - # Without a worker the job would sit queued while the UI reports it done. - if not Worker.all(queue=low_prio_queue, connection=redis_client): + # Without a worker the job would sit queued while the UI waits on it. + if not _listening_workers(low_prio_queue): raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="No task worker is running, so the task cannot be queued", diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index 73db588b2..dd73d6f0f 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -5,12 +5,31 @@ import pytest from fastapi import status from rq.exceptions import NoSuchJobError -from handler.redis_handler import redis_client +from handler.redis_handler import low_prio_queue, redis_client, scan_queue from tasks.manual.cleanup_missing_firmware import CleanupMissingFirmwareStats from tasks.manual.cleanup_missing_roms import CleanupMissingRomsStats from tasks.tasks import Task, TaskType +def _live_worker() -> Mock: + worker = Mock(death_date=None) + worker.get_state.return_value = "idle" + return worker + + +@pytest.fixture(autouse=True) +def task_queue_worker(): + """A live worker on the task queue, so a run is accepted unless a test + takes it away.""" + worker = _live_worker() + + def workers_for(connection=None, queue=None, **_kwargs): + return [worker] if queue is low_prio_queue else [] + + with patch("endpoints.tasks.Worker.all", side_effect=workers_for) as mocked: + yield mocked + + def _job_with_meta(meta: dict[str, Any]) -> Mock: """A finished job carrying `meta`, for asserting on what the response reports.""" job = Mock() @@ -256,11 +275,10 @@ class TestRunSingleTask: ) def test_run_single_task_success(self, mock_enqueue, client, access_token): """Test successful running of a single task""" - with patch("endpoints.tasks.Worker.all", return_value=[Mock()]): - response = client.post( - "/api/tasks/run/test_task", - headers={"Authorization": f"Bearer {access_token}"}, - ) + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) assert response.status_code == status.HTTP_200_OK data = response.json() @@ -302,6 +320,48 @@ class TestRunSingleTask: assert "worker" in response.json()["detail"] mock_enqueue.assert_not_called() + @pytest.mark.parametrize( + "workers_for", + [ + # A scan worker does not serve the task queue. + lambda connection=None, queue=None, **_: ( + [_live_worker()] if queue is scan_queue else [] + ), + # One that announced its death or was suspended does not count. + lambda connection=None, queue=None, **_: [Mock(death_date="gone")], + lambda connection=None, queue=None, **_: [ + Mock(death_date=None, **{"get_state.return_value": "suspended"}) + ], + ], + ids=["scan-worker-only", "dead-worker", "suspended-worker"], + ) + @patch("endpoints.tasks.enqueue_task") + @patch( + "endpoints.tasks.RUNNABLE_TASKS", + { + "test_task": Mock( + spec=Task, + task_type=TaskType.CLEANUP, + title="Test Task", + enabled=True, + manual_run=True, + can_run_manually=True, + run=Mock(), + ), + }, + ) + def test_only_a_live_worker_on_the_task_queue_counts( + self, mock_enqueue, client, access_token, workers_for + ): + with patch("endpoints.tasks.Worker.all", side_effect=workers_for): + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE + mock_enqueue.assert_not_called() + @patch("endpoints.tasks.RUNNABLE_TASKS", {}) def test_run_single_task_not_found(self, client, access_token): """Test running a non-existent task""" diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index 453fc2a3d..4b5fcf10d 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "ファイルシステムにファイルが存在しないファームウェアの登録{platform}をデータベースから完全に削除します。ディスク上のファイルは削除されません。", "cleanup-firmware-queued": "クリーンアップタスクをキューに追加しました。不足しているファームウェアはまもなく削除されます", - "cleanup-queued": "クリーンアップタスクをキューに追加しました, 不足しているROMはまもなく削除されます", + "cleanup-queued": "クリーンアップタスクをキューに追加しました。不足しているROMはまもなく削除されます", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index f0fcbab95..a86085b76 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "파일 시스템에서 파일이 사라진 모든 펌웨어 항목{platform}을 데이터베이스에서 영구적으로 삭제합니다. 디스크에서는 아무것도 삭제되지 않습니다.", "cleanup-firmware-queued": "정리 작업이 대기열에 추가되었습니다. 누락된 펌웨어는 곧 삭제됩니다", - "cleanup-queued": "정리 작업이 대기열에 추가되었습니다, 누락된 ROM은 곧 삭제됩니다", + "cleanup-queued": "정리 작업이 대기열에 추가되었습니다. 누락된 ROM은 곧 삭제됩니다", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index 73878b961..a3a9bacbd 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "这会从数据库中永久删除所有缺失的 ROM{platform} 及其资源目录。此操作无法撤销。", "cleanup-firmware-confirm": "这将从数据库中永久删除文件已从文件系统中缺失的所有固件条目{platform}。磁盘上的文件不会被删除。", "cleanup-firmware-queued": "清理任务已排队,缺失的固件将很快被删除", - "cleanup-queued": "清理任务已排队, 缺失的 ROM 将很快被删除", + "cleanup-queued": "清理任务已排队,缺失的 ROM 将很快被删除", "client-api-tokens": "客户端 API 令牌", "client-token-confirm-delete": "确定要吊销此令牌吗?任何使用它的设备都将失去访问权限。", "client-token-confirm-regenerate": "这会使当前凭据失效。任何使用旧令牌的设备都需要重新配对。", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index 5f4036918..39b9111ff 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -32,7 +32,7 @@ "cleanup-all-confirm": "This will permanently delete all missing ROMs{platform} from the database and their resource directories. This action cannot be undone.", "cleanup-firmware-confirm": "這將從資料庫中永久刪除檔案已從檔案系統中缺失的所有韌體項目{platform}。磁碟上的檔案不會被刪除。", "cleanup-firmware-queued": "清理任務已排程,缺失的韌體將在稍後被刪除", - "cleanup-queued": "清理任務已排程, 缺失的 ROM 將在稍後被刪除", + "cleanup-queued": "清理任務已排程,缺失的 ROM 將在稍後被刪除", "client-api-tokens": "Client API Tokens", "client-token-confirm-delete": "Are you sure you want to revoke this token? Any device using it will lose access.", "client-token-confirm-regenerate": "This will invalidate the current credential. Any device using the old token will need to be re-paired.", diff --git a/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts b/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts index fc380aee4..c20a8a93a 100644 --- a/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts +++ b/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts @@ -1,30 +1,55 @@ import { flushPromises, mount } from "@vue/test-utils"; +import { AxiosError } from "axios"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import storePlatforms from "@/stores/platforms"; import MissingFirmwareSection from "./MissingFirmwareSection.vue"; -const { getFirmware, runTask, getTaskById, confirm } = vi.hoisted(() => ({ - getFirmware: vi.fn(), - runTask: vi.fn(), - getTaskById: vi.fn(), - confirm: vi.fn(), -})); +const { getFirmware, runTask, getTaskById, confirm, snackbarError } = + vi.hoisted(() => ({ + getFirmware: vi.fn(), + runTask: vi.fn(), + getTaskById: vi.fn(), + confirm: vi.fn(), + snackbarError: vi.fn(), + })); vi.mock("@/services/api/firmware", () => ({ default: { getFirmware } })); vi.mock("@/services/api/task", () => ({ default: { runTask, getTaskById } })); +// Error messages keep their `error` parameter so the tests can see what +// reached the snackbar. vi.mock("vue-i18n", () => ({ - useI18n: () => ({ t: (key: string) => key }), + useI18n: () => ({ + t: (key: string, params?: { error?: string }) => + params?.error ? `${key}: ${params.error}` : key, + }), })); vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => confirm, })); vi.mock("@/v2/composables/useSnackbar", () => ({ - useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), + useSnackbar: () => ({ success: vi.fn(), error: snackbarError }), })); +// The server's reason for a refused request, as axios delivers it. +function serverError(detail: string) { + return new AxiosError( + "Request failed with status code 503", + "ERR_BAD_RESPONSE", + undefined, + undefined, + { + status: 503, + statusText: "Service Unavailable", + data: { detail }, + headers: {}, + config: {} as never, + }, + ); +} + const PS1 = { id: 1, slug: "ps", @@ -96,6 +121,7 @@ describe("MissingFirmwareSection", () => { getTaskById.mockResolvedValue({ data: { status: "finished" } }); confirm.mockReset(); confirm.mockResolvedValue(true); + snackbarError.mockReset(); getFirmware.mockReset(); getFirmware.mockResolvedValue({ data: [firmware(10, PS1.id, "scph5501.bin")], @@ -238,4 +264,27 @@ describe("MissingFirmwareSection", () => { 0, ); }); + + it("tells why the server refused the cleanup", async () => { + runTask.mockRejectedValue(serverError("No task worker is running")); + const wrapper = mountSection(); + await flushPromises(); + + wrapper.findComponent({ name: "RMenuItem" }).vm.$emit("click"); + await flushPromises(); + + expect(snackbarError).toHaveBeenCalledWith( + "settings.couldnt-queue-cleanup: No task worker is running", + ); + }); + + it("tells why the list could not be fetched", async () => { + getFirmware.mockRejectedValue(serverError("Database unavailable")); + mountSection(); + await flushPromises(); + + expect(snackbarError).toHaveBeenCalledWith( + "settings.couldnt-fetch-missing-firmware: Database unavailable", + ); + }); }); diff --git a/frontend/src/v2/components/Settings/MissingGamesSection.test.ts b/frontend/src/v2/components/Settings/MissingGamesSection.test.ts index 1f35876f8..8b4c7b163 100644 --- a/frontend/src/v2/components/Settings/MissingGamesSection.test.ts +++ b/frontend/src/v2/components/Settings/MissingGamesSection.test.ts @@ -1,28 +1,46 @@ import { flushPromises, mount } from "@vue/test-utils"; +import { AxiosError } from "axios"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import MissingGamesSection from "./MissingGamesSection.vue"; -const { getRoms } = vi.hoisted(() => ({ getRoms: vi.fn() })); +const { getRoms, runTask, getTaskById, confirm, snackbarError } = vi.hoisted( + () => ({ + getRoms: vi.fn(), + runTask: vi.fn(), + getTaskById: vi.fn(), + confirm: vi.fn(), + snackbarError: vi.fn(), + }), +); vi.mock("@/services/api/rom", () => ({ default: { getRoms } })); vi.mock("@/services/api/task", () => ({ - default: { - runTask: vi.fn().mockResolvedValue({ data: { task_id: "job-1" } }), - getTaskById: vi.fn().mockResolvedValue({ data: { status: "finished" } }), - }, + default: { runTask, getTaskById }, })); +// Error messages keep their `error` parameter so the tests can see what +// reached the snackbar. vi.mock("vue-i18n", () => ({ - useI18n: () => ({ t: (key: string) => key }), + useI18n: () => ({ + t: (key: string, params?: { error?: string }) => + params?.error ? `${key}: ${params.error}` : key, + }), })); vi.mock("@/v2/composables/useConfirm", () => ({ - useConfirm: () => vi.fn().mockResolvedValue(false), + useConfirm: () => confirm, })); vi.mock("@/v2/composables/useSnackbar", () => ({ - useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), + useSnackbar: () => ({ success: vi.fn(), error: snackbarError }), })); + +// The kebab's items live in RMenu's default slot; the auto-stub drops slot +// content, so render it to reach the cleanup action. +const RMenuStub = { + name: "RMenu", + template: '
', +}; vi.mock("@/v2/composables/useWebpSupport", () => ({ useWebpSupport: () => ({ supportsWebp: { value: true } }), })); @@ -37,7 +55,7 @@ function mountSection() { GameListSkeletonRow: true, RBtn: true, RIcon: true, - RMenu: true, + RMenu: RMenuStub, RMenuItem: true, RSelect: true, RTag: true, @@ -54,6 +72,13 @@ describe("MissingGamesSection", () => { getRoms.mockResolvedValue({ data: { total: 0, items: [], char_index: {}, rom_id_index: [] }, }); + runTask.mockReset(); + runTask.mockResolvedValue({ data: { task_id: "job-1" } }); + getTaskById.mockReset(); + getTaskById.mockResolvedValue({ data: { status: "finished" } }); + confirm.mockReset(); + confirm.mockResolvedValue(false); + snackbarError.mockReset(); }); // The tab renders no filter drawer, no A-Z strip and drives its scroller @@ -87,4 +112,32 @@ describe("MissingGamesSection", () => { expect(params.withFilterValues).toBe(false); expect(params.withRomIdIndex).toBe(false); }); + + it("tells why the server refused the cleanup", async () => { + confirm.mockResolvedValue(true); + runTask.mockRejectedValue( + new AxiosError( + "Request failed with status code 503", + "ERR_BAD_RESPONSE", + undefined, + undefined, + { + status: 503, + statusText: "Service Unavailable", + data: { detail: "No task worker is running" }, + headers: {}, + config: {} as never, + }, + ), + ); + const wrapper = mountSection(); + await flushPromises(); + + wrapper.findComponent({ name: "RMenuItem" }).vm.$emit("click"); + await flushPromises(); + + expect(snackbarError).toHaveBeenCalledWith( + "settings.couldnt-queue-cleanup: No task worker is running", + ); + }); }); From f9f68dc0f1f3cb74beb24fe7aa5f16cc85f498ce Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 15:29:22 +0200 Subject: [PATCH 08/28] Unify manual file uploads into a ROM across the Files and Media tabs The Files tab streamed chunks through /roms/upload/* and registered the result with the scanner listing, while each Media route (soundtracks, screenshots, manual files, walkthrough files) carried its own copy of the sanitize, promote, mkdir, stream, stat and DB upsert sequence. Those copies crashed with FileNotFoundError on a file name outside Latin-1: the browser sends the header as Latin-1 and the multipart field name as UTF-8, so the parser target registered under the header name never received the part and os.stat failed after the folder had been created. handler/rom_upload.py now owns the shared ingestion (resolve and prepare the destination, stage next to the target, move into place, refresh the ROM's file rows through the scanner) and both the chunked completion and a new receive_rom_file sit on it. The media routes only check the extension and delegate; a body naming the part differently is a 400. /start gains an optional body filename that wins over the header, so names outside Latin-1 arrive intact, and rom_id becomes optional in that body. On the v2 frontend a single useRomFileUpload composable wraps the chunked upload, the single-file conversion prompt, the toasts and the refetch; the Files tab, Soundtrack panel, Screenshots subtab, Walkthrough subtab and the manual "add to ROM folder" target all call it with their folder. The service sends the real name in the body and a percent-encoded one in the header. The v2-only uploadScreenshots/uploadWalkthroughFiles service functions and the soundtrack-only toasts are gone. Media subtabs now refuse an existing file name (409) like the Files tab, instead of overwriting it silently. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01X1FgnCzXjM3rzkxggi7g6C --- backend/endpoints/roms/manual.py | 90 +---- backend/endpoints/roms/screenshot.py | 96 +---- backend/endpoints/roms/soundtrack.py | 126 +------ backend/endpoints/roms/upload.py | 346 ++++++++---------- backend/endpoints/roms/walkthrough.py | 113 +----- backend/handler/rom_upload.py | 205 +++++++++++ backend/tests/endpoints/roms/conftest.py | 24 ++ .../endpoints/roms/test_convert_to_folder.py | 9 - backend/tests/endpoints/roms/test_manual.py | 32 +- .../tests/endpoints/roms/test_screenshot.py | 35 +- .../tests/endpoints/roms/test_soundtrack.py | 109 ++++-- backend/tests/endpoints/roms/test_upload.py | 74 +++- .../tests/endpoints/roms/test_walkthrough.py | 42 +-- .../models/UploadTargetPayload.ts | 11 +- frontend/src/locales/bg_BG/rom.json | 3 - frontend/src/locales/cs_CZ/rom.json | 3 - frontend/src/locales/de_DE/rom.json | 3 - frontend/src/locales/en_GB/rom.json | 3 - frontend/src/locales/en_US/rom.json | 3 - frontend/src/locales/es_ES/rom.json | 3 - frontend/src/locales/fr_FR/rom.json | 3 - frontend/src/locales/hu_HU/rom.json | 3 - frontend/src/locales/it_IT/rom.json | 3 - frontend/src/locales/ja_JP/rom.json | 3 - frontend/src/locales/ko_KR/rom.json | 3 - frontend/src/locales/pl_PL/rom.json | 3 - frontend/src/locales/pt_BR/rom.json | 3 - frontend/src/locales/ro_RO/rom.json | 3 - frontend/src/locales/ru_RU/rom.json | 3 - frontend/src/locales/tr_TR/rom.json | 3 - frontend/src/locales/zh_CN/rom.json | 3 - frontend/src/locales/zh_TW/rom.json | 3 - frontend/src/services/api/rom.test.ts | 26 +- frontend/src/services/api/rom.ts | 86 +---- .../Dialogs/ManualUploadTargetDialog.test.ts | 26 +- .../Dialogs/ManualUploadTargetDialog.vue | 56 ++- .../GameDetails/FilesTab/FilesTab.vue | 71 +--- .../v2/components/GameDetails/MediaTab.vue | 59 +-- .../GameDetails/ScreenshotsSubtab.vue | 29 +- .../GameDetails/WalkthroughSubtab.vue | 22 +- .../useRomFileUpload/index.test.ts | 120 ++++++ .../v2/composables/useRomFileUpload/index.ts | 119 ++++++ 42 files changed, 932 insertions(+), 1048 deletions(-) create mode 100644 backend/handler/rom_upload.py create mode 100644 frontend/src/v2/composables/useRomFileUpload/index.test.ts create mode 100644 frontend/src/v2/composables/useRomFileUpload/index.ts diff --git a/backend/endpoints/roms/manual.py b/backend/endpoints/roms/manual.py index 62d5b071b..f016074d0 100644 --- a/backend/endpoints/roms/manual.py +++ b/backend/endpoints/roms/manual.py @@ -10,24 +10,22 @@ from streaming_form_data import StreamingFormDataParser from streaming_form_data.targets import FileTarget, NullTarget from decorators.auth import protected_route +from endpoints.roms.upload import receive_rom_file from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException -from exceptions.fs_exceptions import RomAlreadyExistsException from handler.auth.constants import Scope from handler.auth.dependencies import assert_rom_visible from handler.database import db_rom_handler from handler.filesystem import fs_resource_handler, fs_rom_handler from handler.filesystem.resources_handler import ALLOWED_MANUAL_EXTENSIONS -from handler.rom_conversion import promote_single_file_to_folder +from handler.rom_upload import CATEGORY_UPLOAD_FOLDERS from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log -from models.rom import RomFile, RomFileCategory +from models.rom import RomFileCategory from utils.router import APIRouter router = APIRouter() -MANUAL_FOLDER = "manual" - def _is_allowed_manual_file(file_name: str) -> bool: _, ext = os.path.splitext(file_name) @@ -209,7 +207,7 @@ async def add_rom_manual_file( ), ], ) -> Response: - """Upload a manual PDF into the ROM's own manual/ subfolder.""" + """Upload a manual document into the ROM's own manual/ subfolder.""" rom = db_rom_handler.get_rom(id) if not rom: @@ -217,29 +215,7 @@ async def add_rom_manual_file( assert_rom_visible(request, rom) - if rom.has_simple_single_file: - try: - rom = await promote_single_file_to_folder(rom) - except RomAlreadyExistsException as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, detail=str(exc) - ) from exc - - try: - safe_filename = fs_rom_handler._sanitize_filename(filename) - except ValueError as exc: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload filename: {exc}", - ) from exc - - if safe_filename != filename: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload filename must be a plain file name, not a path", - ) - - if not _is_allowed_manual_file(safe_filename): + if not _is_allowed_manual_file(filename): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=( @@ -248,61 +224,9 @@ async def add_rom_manual_file( ), ) - manual_dir_rel = f"{rom.full_path}/{MANUAL_FOLDER}" - file_rel_path = f"{manual_dir_rel}/{safe_filename}" - file_location = fs_rom_handler.validate_path(file_rel_path) - log.info(f"Uploading manual file to {hl(str(file_location))}") - - await fs_rom_handler.make_directory(manual_dir_rel) - - parser = StreamingFormDataParser(headers=request.headers) - parser.register("x-upload-platform", NullTarget()) - parser.register(safe_filename, FileTarget(str(file_location))) - - def cleanup_partial_file(): - if file_location.exists(): - file_location.unlink() - - try: - async for chunk in request.stream(): - parser.data_received(chunk) - except ClientDisconnect: - log.error("Client disconnected during upload") - cleanup_partial_file() - raise - except Exception as exc: - log.error("Error uploading manual file", exc_info=exc) - cleanup_partial_file() - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="There was an error uploading the manual file", - ) from exc - - stat = os.stat(file_location) - existing = db_rom_handler.get_rom_file_by_path( - rom_id=rom.id, file_path=manual_dir_rel, file_name=safe_filename + await receive_rom_file( + request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.MANUAL], filename ) - if existing: - db_rom_handler.update_rom_file( - existing.id, - { - "file_size_bytes": stat.st_size, - "last_modified": stat.st_mtime, - "category": RomFileCategory.MANUAL, - "missing_from_fs": False, - }, - ) - else: - db_rom_handler.add_rom_file( - RomFile( - rom_id=rom.id, - file_name=safe_filename, - file_path=manual_dir_rel, - file_size_bytes=stat.st_size, - last_modified=stat.st_mtime, - category=RomFileCategory.MANUAL, - ) - ) return Response(status_code=status.HTTP_201_CREATED) diff --git a/backend/endpoints/roms/screenshot.py b/backend/endpoints/roms/screenshot.py index 6228446ac..90af9c3b8 100644 --- a/backend/endpoints/roms/screenshot.py +++ b/backend/endpoints/roms/screenshot.py @@ -1,26 +1,22 @@ -import os from typing import Annotated from fastapi import Header, HTTPException from fastapi import Path as PathVar from fastapi import Request, status from fastapi.responses import Response -from starlette.requests import ClientDisconnect -from streaming_form_data import StreamingFormDataParser -from streaming_form_data.targets import FileTarget, NullTarget from decorators.auth import protected_route +from endpoints.roms.upload import receive_rom_file from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException -from exceptions.fs_exceptions import RomAlreadyExistsException from handler.auth.constants import Scope from handler.auth.dependencies import assert_rom_visible from handler.database import db_rom_handler from handler.filesystem import fs_rom_handler -from handler.rom_conversion import promote_single_file_to_folder +from handler.rom_upload import CATEGORY_UPLOAD_FOLDERS from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log -from models.rom import RomFile, RomFileCategory +from models.rom import RomFileCategory from utils.media_types import ( ALLOWED_IMAGE_EXTENSIONS, is_allowed_image_file, @@ -29,8 +25,6 @@ from utils.router import APIRouter router = APIRouter() -SCREENSHOT_FOLDER = "screenshots" - @protected_route( router.post, @@ -50,7 +44,7 @@ async def add_rom_screenshots( ), ], ) -> Response: - """Upload a screenshot image for a multi-file ROM.""" + """Upload a screenshot image into the ROM's screenshots/ subfolder.""" rom = db_rom_handler.get_rom(id) if not rom: @@ -58,31 +52,7 @@ async def add_rom_screenshots( assert_rom_visible(request, rom) - if rom.has_simple_single_file: - try: - rom = await promote_single_file_to_folder(rom) - except RomAlreadyExistsException as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, detail=str(exc) - ) from exc - - try: - safe_filename = fs_rom_handler._sanitize_filename(filename) - except ValueError as exc: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload filename: {exc}", - ) from exc - - # Reject rather than silently strip — otherwise the client's form-field - # name won't match what we register with the parser below. - if safe_filename != filename: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload filename must be a plain file name, not a path", - ) - - if not is_allowed_image_file(safe_filename): + if not is_allowed_image_file(filename): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=( @@ -91,61 +61,9 @@ async def add_rom_screenshots( ), ) - screenshot_dir_rel = f"{rom.full_path}/{SCREENSHOT_FOLDER}" - file_rel_path = f"{screenshot_dir_rel}/{safe_filename}" - file_location = fs_rom_handler.validate_path(file_rel_path) - log.info(f"Uploading screenshot to {hl(str(file_location))}") - - await fs_rom_handler.make_directory(screenshot_dir_rel) - - parser = StreamingFormDataParser(headers=request.headers) - parser.register("x-upload-platform", NullTarget()) - parser.register(safe_filename, FileTarget(str(file_location))) - - def cleanup_partial_file(): - if file_location.exists(): - file_location.unlink() - - try: - async for chunk in request.stream(): - parser.data_received(chunk) - except ClientDisconnect: - log.error("Client disconnected during upload") - cleanup_partial_file() - raise - except Exception as exc: - log.error("Error uploading screenshot", exc_info=exc) - cleanup_partial_file() - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="There was an error uploading the screenshot", - ) from exc - - stat = os.stat(file_location) - existing = db_rom_handler.get_rom_file_by_path( - rom_id=rom.id, file_path=screenshot_dir_rel, file_name=safe_filename + await receive_rom_file( + request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.SCREENSHOT], filename ) - if existing: - db_rom_handler.update_rom_file( - existing.id, - { - "file_size_bytes": stat.st_size, - "last_modified": stat.st_mtime, - "category": RomFileCategory.SCREENSHOT, - "missing_from_fs": False, - }, - ) - else: - db_rom_handler.add_rom_file( - RomFile( - rom_id=rom.id, - file_name=safe_filename, - file_path=screenshot_dir_rel, - file_size_bytes=stat.st_size, - last_modified=stat.st_mtime, - category=RomFileCategory.SCREENSHOT, - ) - ) return Response(status_code=status.HTTP_201_CREATED) diff --git a/backend/endpoints/roms/soundtrack.py b/backend/endpoints/roms/soundtrack.py index 6976ec254..38740b31b 100644 --- a/backend/endpoints/roms/soundtrack.py +++ b/backend/endpoints/roms/soundtrack.py @@ -1,41 +1,32 @@ -import os from typing import Annotated from fastapi import Header, HTTPException from fastapi import Path as PathVar from fastapi import Request, status from fastapi.responses import Response -from starlette.requests import ClientDisconnect -from streaming_form_data import StreamingFormDataParser -from streaming_form_data.targets import FileTarget, NullTarget from decorators.auth import protected_route from endpoints.responses.rom import SoundtrackTrackMetaSchema, TrackMetaSchema +from endpoints.roms.upload import receive_rom_file from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException -from exceptions.fs_exceptions import RomAlreadyExistsException from handler.auth.constants import Scope from handler.auth.dependencies import assert_rom_visible from handler.database import db_rom_handler from handler.filesystem import fs_rom_handler -from handler.rom_conversion import promote_single_file_to_folder +from handler.rom_upload import CATEGORY_UPLOAD_FOLDERS from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log -from models.rom import RomFile, RomFileCategory, TrackMeta +from models.rom import RomFileCategory from utils.audio_tags import ( ALLOWED_AUDIO_EXTENSIONS, - extract_audio_meta, is_allowed_audio_file, - persist_embedded_cover, remove_persisted_cover, - track_meta_columns, ) from utils.router import APIRouter router = APIRouter() -SOUNDTRACK_FOLDER = "soundtrack" - @protected_route( router.get, @@ -90,7 +81,7 @@ async def add_rom_soundtracks( ), ], ) -> Response: - """Upload a soundtrack audio file for a multi-file ROM.""" + """Upload a soundtrack audio file into the ROM's soundtrack/ subfolder.""" rom = db_rom_handler.get_rom(id) if not rom: @@ -98,31 +89,7 @@ async def add_rom_soundtracks( assert_rom_visible(request, rom) - if rom.has_simple_single_file: - try: - rom = await promote_single_file_to_folder(rom) - except RomAlreadyExistsException as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, detail=str(exc) - ) from exc - - try: - safe_filename = fs_rom_handler._sanitize_filename(filename) - except ValueError as exc: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload filename: {exc}", - ) from exc - - # Reject rather than silently strip — otherwise the client's form-field - # name won't match what we register with the parser below. - if safe_filename != filename: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload filename must be a plain file name, not a path", - ) - - if not is_allowed_audio_file(safe_filename): + if not is_allowed_audio_file(filename): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=( @@ -131,88 +98,9 @@ async def add_rom_soundtracks( ), ) - soundtrack_dir_rel = f"{rom.full_path}/{SOUNDTRACK_FOLDER}" - file_rel_path = f"{soundtrack_dir_rel}/{safe_filename}" - file_location = fs_rom_handler.validate_path(file_rel_path) - log.info(f"Uploading soundtrack to {hl(str(file_location))}") - - await fs_rom_handler.make_directory(soundtrack_dir_rel) - - parser = StreamingFormDataParser(headers=request.headers) - parser.register("x-upload-platform", NullTarget()) - parser.register(safe_filename, FileTarget(str(file_location))) - - def cleanup_partial_file(): - if file_location.exists(): - file_location.unlink() - - try: - async for chunk in request.stream(): - parser.data_received(chunk) - except ClientDisconnect: - log.error("Client disconnected during upload") - cleanup_partial_file() - raise - except Exception as exc: - log.error("Error uploading soundtrack", exc_info=exc) - cleanup_partial_file() - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="There was an error uploading the soundtrack", - ) from exc - - stat = os.stat(file_location) - audio_meta = extract_audio_meta(str(file_location)) - cols = track_meta_columns(audio_meta) if audio_meta else None - existing = db_rom_handler.get_rom_file_by_path( - rom_id=rom.id, file_path=soundtrack_dir_rel, file_name=safe_filename + await receive_rom_file( + request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.SOUNDTRACK], filename ) - if existing: - # Reuploading: drop stale cover first so a new id-based path can replace it. - if existing.track_meta and existing.track_meta.cover_path: - remove_persisted_cover(existing.track_meta.cover_path) - saved = db_rom_handler.update_rom_file( - existing.id, - { - "file_size_bytes": stat.st_size, - "last_modified": stat.st_mtime, - "category": RomFileCategory.SOUNDTRACK, - "missing_from_fs": False, - }, - ) - if cols: - db_rom_handler.upsert_track_meta(existing.id, rom.id, cols) - else: - db_rom_handler.delete_track_meta(existing.id) - else: - saved = db_rom_handler.add_rom_file( - RomFile( - rom_id=rom.id, - file_name=safe_filename, - file_path=soundtrack_dir_rel, - file_size_bytes=stat.st_size, - last_modified=stat.st_mtime, - category=RomFileCategory.SOUNDTRACK, - track_meta=(TrackMeta(rom_id=rom.id, **cols) if cols else None), - ) - ) - - if saved and audio_meta and audio_meta.get("has_embedded_cover"): - cover_path = persist_embedded_cover( - audio_full_path=str(file_location), - platform_id=rom.platform_id, - rom_id=rom.id, - file_id=saved.id, - ) - if cover_path: - db_rom_handler.upsert_track_meta( - saved.id, rom.id, {"cover_path": cover_path} - ) - else: - log.error(f"[audio_tags] cover persist failed for {file_location}") - db_rom_handler.upsert_track_meta( - saved.id, rom.id, {"has_embedded_cover": False} - ) return Response(status_code=status.HTTP_201_CREATED) diff --git a/backend/endpoints/roms/upload.py b/backend/endpoints/roms/upload.py index 8228e6a27..f48fb1517 100644 --- a/backend/endpoints/roms/upload.py +++ b/backend/endpoints/roms/upload.py @@ -1,20 +1,19 @@ import json -import os import shutil from pathlib import Path from typing import Annotated from uuid import UUID, uuid4 +from anyio import Path as AsyncPath from anyio import open_file from fastapi import Header, HTTPException, Request, status from pydantic import BaseModel, Field +from starlette.requests import ClientDisconnect from starlette.responses import Response +from streaming_form_data import StreamingFormDataParser +from streaming_form_data.targets import FileTarget, NullTarget -from config import ( - ROM_UPLOAD_ASSEMBLING_EXT, - ROM_UPLOAD_TMP_BASE, - ROM_UPLOAD_TTL, -) +from config import ROM_UPLOAD_TMP_BASE, ROM_UPLOAD_TTL from decorators.auth import protected_route from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException from exceptions.fs_exceptions import RomAlreadyExistsException @@ -23,8 +22,18 @@ from handler.auth.dependencies import assert_rom_visible from handler.database import db_platform_handler, db_rom_handler from handler.filesystem import fs_rom_handler from handler.redis_handler import async_cache -from handler.rom_conversion import promote_single_file_to_folder -from handler.rom_files import refresh_rom_files +from handler.rom_upload import ( + UploadConflictException, + UploadDestination, + UploadNotRegisteredException, + UploadRejectedException, + commit_upload, + parse_upload_folder, + prepare_upload_destination, + resolve_upload_destination, + sanitize_upload_filename, + staging_path, +) from logger.logger import log from models.rom import Rom from utils.router import APIRouter @@ -101,46 +110,11 @@ async def _cleanup_upload_state(upload_id: str) -> None: def _sanitized_filename(filename: str) -> str: try: - safe_filename = fs_rom_handler._sanitize_filename(filename) - except ValueError as exc: + return sanitize_upload_filename(filename) + except UploadRejectedException as exc: raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload filename: {exc}", + status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc) ) from exc - if safe_filename != filename: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload filename must be a plain file name, not a path", - ) - return safe_filename - - -def _parse_upload_folder(folder: str) -> str: - """Normalize the target subfolder to a relative path made of plain names.""" - raw = folder.strip() - if raw.startswith("/") or "\\" in raw: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload folder must be a relative, forward-slashed path", - ) - raw = raw.rstrip("/") - if not raw: - return "" - segments = raw.split("/") - for segment in segments: - try: - safe_segment = fs_rom_handler._sanitize_filename(segment) - except ValueError as exc: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload folder: {exc}", - ) from exc - if safe_segment != segment: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload folder must be a relative path inside the game folder", - ) - return "/".join(segments) def _get_upload_rom(request: Request, rom_id: int, platform_id: int) -> Rom: @@ -156,94 +130,118 @@ def _get_upload_rom(request: Request, rom_id: int, platform_id: int) -> Rom: return rom -def _free_rom_destination(rom: Rom, folder: str, filename: str) -> tuple[str, Path]: - """The library-relative directory and absolute file path of an upload into a - ROM, kept inside the folder a lone file gets promoted into and refused when - a file of that name is already there (or will be, once promoted).""" - root = ( - f"{rom.fs_path}/{rom.fs_name_no_ext}" - if rom.has_simple_single_file - else rom.full_path - ) - rel_dir = f"{root}/{folder}" if folder else root +async def _prepare_rom_destination( + rom: Rom, folder: str, filename: str, *, overwrite: bool +) -> UploadDestination: try: - root_location = fs_rom_handler.validate_path(root) - location = fs_rom_handler.validate_path(f"{rel_dir}/{filename}") - except ValueError as exc: + return await prepare_upload_destination( + rom, folder, filename, overwrite=overwrite + ) + except UploadRejectedException as exc: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc) ) from exc - if not location.is_relative_to(root_location): + except (UploadConflictException, RomAlreadyExistsException) as exc: raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload destination must be inside the game folder", - ) - - promoted_over_itself = ( - rom.has_simple_single_file and not folder and filename == rom.fs_name - ) - if location.exists() or promoted_over_itself: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"File {filename} already exists in the game folder", - ) - return rel_dir, location - - -def _claim_destination(location: Path) -> None: - """Create the final path exclusively, so two completions racing for the - same name cannot overwrite each other's bytes.""" - try: - os.close(os.open(location, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)) - except FileExistsError as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"File {location.name} already exists", + status_code=status.HTTP_409_CONFLICT, detail=str(exc) ) from exc -async def _resolve_destination( - request: Request, session: dict -) -> tuple[str, Path, Rom | None]: - """Where a completed upload lands: the directory to create, the file path, - and the ROM it belongs to when it targets one.""" +async def _commit( + destination: UploadDestination, staged: Path, *, overwrite: bool +) -> None: + try: + await commit_upload(destination, staged, overwrite=overwrite) + except UploadConflictException as exc: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, detail=str(exc) + ) from exc + except UploadNotRegisteredException as exc: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc) + ) from exc + + +async def receive_rom_file( + request: Request, rom: Rom, folder: str, filename: str +) -> UploadDestination: + """Stream a single-file multipart body into a subfolder of the ROM and + register it the way a chunked upload is, replacing a file of the same name.""" + safe_filename = _sanitized_filename(filename) + destination = await _prepare_rom_destination( + rom, folder, safe_filename, overwrite=True + ) + staged = staging_path(destination.location) + log.info(f"Uploading {safe_filename} to {destination.location}") + + parser = StreamingFormDataParser(headers=request.headers) + parser.register("x-upload-platform", NullTarget()) + parser.register(safe_filename, FileTarget(str(staged))) + try: + async for chunk in request.stream(): + parser.data_received(chunk) + except ClientDisconnect: + log.error("Client disconnected during upload") + await AsyncPath(staged).unlink(missing_ok=True) + raise + except Exception as exc: + log.error(f"Error uploading {safe_filename}", exc_info=exc) + await AsyncPath(staged).unlink(missing_ok=True) + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="There was an error uploading the file", + ) from exc + + # The parser only writes the part whose field name matches the header, so + # a body naming the file differently leaves nothing behind. + if not await AsyncPath(staged).exists(): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"The upload body has no file part named {safe_filename}", + ) + + await _commit(destination, staged, overwrite=True) + return destination + + +async def _resolve_destination(request: Request, session: dict) -> UploadDestination: + """Where a completed upload lands, with its directory created.""" filename = session["filename"] rom_id = session.get("rom_id") if rom_id is None: try: roms_path = fs_rom_handler.get_roms_upload_path(session["platform_fs_slug"]) - return ( - roms_path, - fs_rom_handler.validate_path(f"{roms_path}/{filename}"), - None, - ) + location = fs_rom_handler.validate_path(f"{roms_path}/{filename}") except ValueError as exc: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc) ) from exc + await fs_rom_handler.make_directory(roms_path) + return UploadDestination(rom=None, rel_dir=roms_path, location=location) rom = _get_upload_rom(request, rom_id, session["platform_id"]) - folder = session["folder"] - rel_dir, location = _free_rom_destination(rom, folder, filename) - if rom.has_simple_single_file: - try: - rom = await promote_single_file_to_folder(rom) - except RomAlreadyExistsException as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, detail=str(exc) - ) from exc - return rel_dir, location, rom + return await _prepare_rom_destination( + rom, session["folder"], filename, overwrite=False + ) class UploadTargetPayload(BaseModel): """Optional body of `/start`: upload into a ROM's folder instead of the - platform folder.""" + platform folder, and name the file where the header cannot.""" - rom_id: int = Field(ge=1) + rom_id: int | None = Field( + default=None, + ge=1, + description="Upload into this ROM's folder instead of the platform folder.", + ) folder: str = Field( default="", description="Subfolder inside the ROM's folder, relative and forward-slashed. Empty for the root.", ) + filename: str | None = Field( + default=None, + description="The file name. Takes precedence over the header, which cannot carry characters outside Latin-1.", + ) @protected_route( @@ -282,10 +280,13 @@ async def start_chunked_upload( ) platform_fs_slug = db_platform.fs_slug + if target and target.filename: + filename = target.filename safe_filename = _sanitized_filename(filename) + rom_id = target.rom_id if target else None rel_folder = "" - if target is None: + if rom_id is None: try: roms_path = fs_rom_handler.get_roms_upload_path(platform_fs_slug) except ValueError as exc: @@ -298,14 +299,18 @@ async def start_chunked_upload( detail=f"File {filename} already exists", ) else: - rom = _get_upload_rom(request, target.rom_id, platform_id) - rel_folder = _parse_upload_folder(target.folder) - if fs_rom_handler.is_excluded_multi_part(safe_filename): + rom = _get_upload_rom(request, rom_id, platform_id) + try: + rel_folder = parse_upload_folder(target.folder if target else "") + resolve_upload_destination(rom, rel_folder, safe_filename) + except UploadRejectedException as exc: raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"File {filename} would be ignored by the scanner", - ) - _free_rom_destination(rom, rel_folder, safe_filename) + status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc) + ) from exc + except UploadConflictException as exc: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, detail=str(exc) + ) from exc upload_id = str(uuid4()) tmp_dir = ROM_UPLOAD_TMP_BASE / upload_id @@ -319,13 +324,13 @@ async def start_chunked_upload( "total_chunks": total_chunks, "total_size": total_size, "user_id": request.user.id, - "rom_id": target.rom_id if target else None, + "rom_id": rom_id, "folder": rel_folder, } await _save_session(upload_id, session) log.info( - f"Started chunked upload session {upload_id} for {filename} " + f"Started chunked upload session {upload_id} for {safe_filename} " f"({total_chunks} chunks, {total_size} bytes)" ) @@ -419,6 +424,42 @@ async def upload_chunk( return {"received": received_count, "total": session["total_chunks"]} +async def _assemble_chunks(upload_id: str, session: dict, staged: Path) -> None: + """Concatenate the received chunks into the staged file, dropping it on + any failure.""" + total_chunks = session["total_chunks"] + log.info(f"Assembling {total_chunks} chunks into {staged}") + assembled_bytes = 0 + try: + async with await open_file(staged, "wb") as dest: + for i in range(total_chunks): + chunk_path = ROM_UPLOAD_TMP_BASE / upload_id / f"{i:05d}" + async with await open_file(chunk_path, "rb") as src: + while True: + buf = await src.read(ROM_ASSEMBLY_CHUNK_SIZE) + if not buf: + break + assembled_bytes += len(buf) + await dest.write(buf) + if assembled_bytes != session["total_size"]: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=( + "Assembled file size mismatch: " + f"expected {session['total_size']}, got {assembled_bytes}" + ), + ) + except Exception as exc: + await AsyncPath(staged).unlink(missing_ok=True) + if isinstance(exc, HTTPException): + raise + log.error(f"Error assembling upload {upload_id}", exc_info=exc) + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Error assembling file chunks", + ) from exc + + @protected_route( router.post, "/{upload_id}/complete", @@ -459,75 +500,12 @@ async def complete_chunked_upload( ) try: - target_dir, file_location, rom = await _resolve_destination(request, session) - except Exception: + destination = await _resolve_destination(request, session) + staged = staging_path(destination.location) + await _assemble_chunks(upload_id, session, staged) + await _commit(destination, staged, overwrite=False) + finally: await _cleanup_upload_state(upload_id) - raise - - await fs_rom_handler.make_directory(target_dir) - - log.info(f"Assembling {total_chunks} chunks into {file_location}") - - # Assemble chunks in order into final file with a temporary filename - # then atomically rename to final location - temp_location = file_location.with_name( - f".{file_location.name}.{uuid4().hex}.{ROM_UPLOAD_ASSEMBLING_EXT}" - ) - assembled_bytes = 0 - claimed = False - - try: - async with await open_file(temp_location, "wb") as dest: - for i in range(total_chunks): - chunk_path = ROM_UPLOAD_TMP_BASE / upload_id / f"{i:05d}" - async with await open_file(chunk_path, "rb") as src: - while True: - buf = await src.read(ROM_ASSEMBLY_CHUNK_SIZE) - if not buf: - break - assembled_bytes += len(buf) - await dest.write(buf) - if assembled_bytes != session["total_size"]: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=( - "Assembled file size mismatch: " - f"expected {session['total_size']}, got {assembled_bytes}" - ), - ) - - _claim_destination(file_location) - claimed = True - temp_location.replace(file_location) - except Exception as exc: - if temp_location.exists(): - temp_location.unlink() - if claimed: - # The claim is an empty placeholder the rename never replaced; - # left behind, a scan would ingest it as a zero-byte ROM. - file_location.unlink(missing_ok=True) - await _cleanup_upload_state(upload_id) - if isinstance(exc, HTTPException): - raise - log.error(f"Error assembling upload {upload_id}", exc_info=exc) - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="Error assembling file chunks", - ) from exc - - await _cleanup_upload_state(upload_id) - - log.info(f"Chunked upload complete: {file_location}") - - if rom is not None: - try: - await refresh_rom_files(rom) - except Exception as exc: - log.error(f"Error registering uploaded file for ROM {rom.id}", exc_info=exc) - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="File uploaded but not registered yet, run a quick scan", - ) from exc return Response(status_code=status.HTTP_201_CREATED) diff --git a/backend/endpoints/roms/walkthrough.py b/backend/endpoints/roms/walkthrough.py index 0c7adc0c0..ffa193a0c 100644 --- a/backend/endpoints/roms/walkthrough.py +++ b/backend/endpoints/roms/walkthrough.py @@ -8,11 +8,9 @@ from fastapi import Body, Header, HTTPException from fastapi import Path as PathVar from fastapi import Request, status from fastapi.responses import Response -from starlette.requests import ClientDisconnect -from streaming_form_data import StreamingFormDataParser -from streaming_form_data.targets import FileTarget, NullTarget from decorators.auth import protected_route +from endpoints.roms.upload import receive_rom_file from exceptions.endpoint_exceptions import RomNotFoundInDatabaseException from exceptions.fs_exceptions import RomAlreadyExistsException from handler.auth.constants import Scope @@ -20,6 +18,7 @@ from handler.auth.dependencies import assert_rom_visible from handler.database import db_rom_handler from handler.filesystem import fs_rom_handler from handler.rom_conversion import promote_single_file_to_folder +from handler.rom_upload import CATEGORY_UPLOAD_FOLDERS from handler.walkthrough import fetch_gamefaqs_guide, validate_gamefaqs_url from handler.walkthrough.gamefaqs import GameFAQsFetchError from logger.formatter import BLUE @@ -31,8 +30,6 @@ from utils.router import APIRouter router = APIRouter() -WALKTHROUGH_FOLDER = "walkthrough" - _SLUG_RE = re.compile(r"[^a-z0-9]+") @@ -91,29 +88,7 @@ async def add_rom_walkthrough_file( assert_rom_visible(request, rom) - if rom.has_simple_single_file: - try: - rom = await promote_single_file_to_folder(rom) - except RomAlreadyExistsException as exc: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, detail=str(exc) - ) from exc - - try: - safe_filename = fs_rom_handler._sanitize_filename(filename) - except ValueError as exc: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Invalid upload filename: {exc}", - ) from exc - - if safe_filename != filename: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Upload filename must be a plain file name, not a path", - ) - - if not _is_allowed_walkthrough_file(safe_filename): + if not _is_allowed_walkthrough_file(filename): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=( @@ -122,73 +97,23 @@ async def add_rom_walkthrough_file( ), ) - walkthrough_dir_rel = f"{rom.full_path}/{WALKTHROUGH_FOLDER}" - file_rel_path = f"{walkthrough_dir_rel}/{safe_filename}" - file_location = fs_rom_handler.validate_path(file_rel_path) - log.info(f"Uploading walkthrough file to {hl(str(file_location))}") - - await fs_rom_handler.make_directory(walkthrough_dir_rel) - - parser = StreamingFormDataParser(headers=request.headers) - parser.register("x-upload-platform", NullTarget()) - parser.register(safe_filename, FileTarget(str(file_location))) - - def cleanup_partial_file(): - if file_location.exists(): - file_location.unlink() - - try: - async for chunk in request.stream(): - parser.data_received(chunk) - except ClientDisconnect: - log.error("Client disconnected during upload") - cleanup_partial_file() - raise - except Exception as exc: - log.error("Error uploading walkthrough file", exc_info=exc) - cleanup_partial_file() - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="There was an error uploading the walkthrough file", - ) from exc - - stat = os.stat(file_location) - existing = db_rom_handler.get_rom_file_by_path( - rom_id=rom.id, file_path=walkthrough_dir_rel, file_name=safe_filename + destination = await receive_rom_file( + request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.WALKTHROUGH], filename ) - if existing: - db_rom_handler.update_rom_file( - existing.id, - { - "file_size_bytes": stat.st_size, - "last_modified": stat.st_mtime, - "category": RomFileCategory.WALKTHROUGH, - "missing_from_fs": False, + + rom_file = db_rom_handler.get_rom_file_by_path( + rom_id=rom.id, file_path=destination.rel_dir, file_name=filename + ) + if rom_file: + db_rom_handler.upsert_doc_meta( + rom_file_id=rom_file.id, + rom_id=rom.id, + values={ + "source": DocSource.UPLOAD, + "author": _decode_header(author), + "title": _decode_header(title), }, ) - rom_file_id = existing.id - else: - created = db_rom_handler.add_rom_file( - RomFile( - rom_id=rom.id, - file_name=safe_filename, - file_path=walkthrough_dir_rel, - file_size_bytes=stat.st_size, - last_modified=stat.st_mtime, - category=RomFileCategory.WALKTHROUGH, - ) - ) - rom_file_id = created.id - - db_rom_handler.upsert_doc_meta( - rom_file_id=rom_file_id, - rom_id=rom.id, - values={ - "source": DocSource.UPLOAD, - "author": _decode_header(author), - "title": _decode_header(title), - }, - ) return Response(status_code=status.HTTP_201_CREATED) @@ -243,7 +168,9 @@ async def add_rom_gamefaqs_walkthrough( status_code=status.HTTP_409_CONFLICT, detail=str(exc) ) from exc - walkthrough_dir_rel = f"{rom.full_path}/{WALKTHROUGH_FOLDER}" + walkthrough_dir_rel = ( + f"{rom.full_path}/{CATEGORY_UPLOAD_FOLDERS[RomFileCategory.WALKTHROUGH]}" + ) base_name = _slugify(guide["title"] or f"gamefaqs-{rom.id}") file_name = f"{base_name}.txt" diff --git a/backend/handler/rom_upload.py b/backend/handler/rom_upload.py new file mode 100644 index 000000000..3625fd68a --- /dev/null +++ b/backend/handler/rom_upload.py @@ -0,0 +1,205 @@ +"""One ingestion path for every file uploaded into a ROM's folder, whether the +bytes arrive in chunks or as a single multipart request.""" + +import os +from dataclasses import dataclass +from pathlib import Path +from uuid import uuid4 + +from config import ROM_UPLOAD_ASSEMBLING_EXT +from handler.filesystem import fs_rom_handler +from handler.rom_conversion import promote_single_file_to_folder +from handler.rom_files import refresh_rom_files +from logger.logger import log +from models.rom import Rom, RomFileCategory + +# The folder each media route uploads into. The scanner maps these names back to +# the category, so a file landing here is registered the same way a scan would. +CATEGORY_UPLOAD_FOLDERS: dict[RomFileCategory, str] = { + RomFileCategory.MANUAL: "manual", + RomFileCategory.WALKTHROUGH: "walkthrough", + RomFileCategory.SCREENSHOT: "screenshots", + RomFileCategory.SOUNDTRACK: "soundtrack", +} + + +class UploadRejectedException(ValueError): + """The upload names a file or folder the ROM's folder cannot take.""" + + +class UploadConflictException(FileExistsError): + """A file of that name is already in the ROM's folder.""" + + +class UploadNotRegisteredException(Exception): + """The file is on disk but the ROM's file rows could not be refreshed.""" + + +@dataclass(frozen=True) +class UploadDestination: + """Where an upload lands: the ROM it belongs to (none for a platform folder + upload), the library-relative directory and the absolute file path.""" + + rom: Rom | None + rel_dir: str + location: Path + + +def sanitize_upload_filename(filename: str) -> str: + """A plain file name, or UploadRejectedException when it carries a path.""" + try: + safe_filename = fs_rom_handler._sanitize_filename(filename) + except ValueError as exc: + raise UploadRejectedException(f"Invalid upload filename: {exc}") from exc + if safe_filename != filename: + raise UploadRejectedException( + "Upload filename must be a plain file name, not a path" + ) + return safe_filename + + +def parse_upload_folder(folder: str) -> str: + """Normalize the target subfolder to a relative path made of plain names.""" + raw = folder.strip() + if raw.startswith("/") or "\\" in raw: + raise UploadRejectedException( + "Upload folder must be a relative, forward-slashed path" + ) + raw = raw.rstrip("/") + if not raw: + return "" + segments = raw.split("/") + for segment in segments: + try: + safe_segment = fs_rom_handler._sanitize_filename(segment) + except ValueError as exc: + raise UploadRejectedException(f"Invalid upload folder: {exc}") from exc + if safe_segment != segment: + raise UploadRejectedException( + "Upload folder must be a relative path inside the game folder" + ) + return "/".join(segments) + + +def resolve_upload_destination( + rom: Rom, folder: str, filename: str, *, overwrite: bool = False +) -> tuple[str, Path]: + """The library-relative directory and absolute file path of an upload into a + ROM, kept inside the folder a lone file gets promoted into. + + Raises: + UploadRejectedException: The destination is unusable or the scanner + would never register the file. + UploadConflictException: A file of that name is already there (or will + be, once promoted), unless `overwrite` allows replacing it. + """ + if fs_rom_handler.is_excluded_multi_part(filename): + raise UploadRejectedException( + f"File {filename} would be ignored by the scanner" + ) + + root = ( + f"{rom.fs_path}/{rom.fs_name_no_ext}" + if rom.has_simple_single_file + else rom.full_path + ) + rel_dir = f"{root}/{folder}" if folder else root + try: + root_location = fs_rom_handler.validate_path(root) + location = fs_rom_handler.validate_path(f"{rel_dir}/{filename}") + except ValueError as exc: + raise UploadRejectedException(str(exc)) from exc + if not location.is_relative_to(root_location): + raise UploadRejectedException( + "Upload destination must be inside the game folder" + ) + + promoted_over_itself = ( + rom.has_simple_single_file and not folder and filename == rom.fs_name + ) + replaceable = overwrite and location.is_file() + if promoted_over_itself or (location.exists() and not replaceable): + raise UploadConflictException( + f"File {filename} already exists in the game folder" + ) + return rel_dir, location + + +async def prepare_upload_destination( + rom: Rom, folder: str, filename: str, *, overwrite: bool = False +) -> UploadDestination: + """Resolve where the file lands, promote a lone file into its folder and + create the target directory. + + Raises the same as `resolve_upload_destination`, plus + RomAlreadyExistsException when the promotion collides with a folder. + """ + rel_dir, location = resolve_upload_destination( + rom, folder, filename, overwrite=overwrite + ) + if rom.has_simple_single_file: + rom = await promote_single_file_to_folder(rom) + await fs_rom_handler.make_directory(rel_dir) + return UploadDestination(rom=rom, rel_dir=rel_dir, location=location) + + +def staging_path(location: Path) -> Path: + """A private sibling of the destination, so the final move is a rename on + the same filesystem.""" + return location.with_name( + f".{location.name}.{uuid4().hex}.{ROM_UPLOAD_ASSEMBLING_EXT}" + ) + + +def claim_destination(location: Path) -> None: + """Create the final path exclusively, so two uploads racing for the same + name cannot overwrite each other's bytes.""" + try: + os.close(os.open(location, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)) + except FileExistsError as exc: + raise UploadConflictException(f"File {location.name} already exists") from exc + + +def _move_into_place(location: Path, staged: Path, *, overwrite: bool) -> None: + claimed = False + try: + if not overwrite: + claim_destination(location) + claimed = True + staged.replace(location) + except BaseException: + staged.unlink(missing_ok=True) + if claimed: + # The claim is an empty placeholder the rename never replaced; + # left behind, a scan would ingest it as a zero-byte ROM. + location.unlink(missing_ok=True) + raise + + +async def commit_upload( + destination: UploadDestination, staged: Path, *, overwrite: bool = False +) -> None: + """Move the staged bytes into place and register the file on its ROM. + + The staged file is removed whatever the outcome. + + Raises: + UploadConflictException: The name got taken while the bytes arrived. + UploadNotRegisteredException: The file is in place but the ROM's rows + could not be refreshed. + """ + _move_into_place(destination.location, staged, overwrite=overwrite) + log.info(f"Upload complete: {destination.location}") + + if destination.rom is None: + return + try: + await refresh_rom_files(destination.rom) + except Exception as exc: + log.error( + f"Error registering uploaded file for ROM {destination.rom.id}", + exc_info=exc, + ) + raise UploadNotRegisteredException( + "File uploaded but not registered yet, run a quick scan" + ) from exc diff --git a/backend/tests/endpoints/roms/conftest.py b/backend/tests/endpoints/roms/conftest.py index ee7c2d0cd..b7d2c67fb 100644 --- a/backend/tests/endpoints/roms/conftest.py +++ b/backend/tests/endpoints/roms/conftest.py @@ -1,11 +1,35 @@ +from pathlib import Path + import pytest from handler.database import db_rom_handler +from handler.filesystem import fs_rom_handler from models.platform import Platform from models.rom import Rom, RomFile, RomFileCategory from models.user import User +@pytest.fixture +def real_library(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Point fs_rom_handler at a real temp library so file moves and listings + actually happen.""" + lib = tmp_path / "library" + lib.mkdir() + monkeypatch.setattr(fs_rom_handler, "base_path", lib.resolve()) + return lib + + +@pytest.fixture +def game_folder_on_disk(real_library: Path, game_folder_rom: Rom) -> Path: + """The folder ROM's directory in the real library, with every file row + written to disk so a refresh keeps them.""" + for rom_file in game_folder_rom.files: + path = real_library / rom_file.full_path + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"\0" * rom_file.file_size_bytes) + return real_library / game_folder_rom.full_path + + @pytest.fixture def game_folder_rom(admin_user: User, platform: Platform) -> Rom: """A folder-based ROM with two top-level files (so has_simple_single_file is False).""" diff --git a/backend/tests/endpoints/roms/test_convert_to_folder.py b/backend/tests/endpoints/roms/test_convert_to_folder.py index 5f4b80450..4743173fa 100644 --- a/backend/tests/endpoints/roms/test_convert_to_folder.py +++ b/backend/tests/endpoints/roms/test_convert_to_folder.py @@ -22,15 +22,6 @@ def _auth(token: str) -> dict[str, str]: return {"Authorization": f"Bearer {token}"} -@pytest.fixture -def real_library(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: - """Point fs_rom_handler at a real temp library so FS moves actually happen.""" - lib = tmp_path / "library" - lib.mkdir() - monkeypatch.setattr(fs_rom_handler, "base_path", lib.resolve()) - return lib - - def _single_file_rom( platform: Platform, admin_user: User, diff --git a/backend/tests/endpoints/roms/test_manual.py b/backend/tests/endpoints/roms/test_manual.py index dd08986a9..bf7de1b99 100644 --- a/backend/tests/endpoints/roms/test_manual.py +++ b/backend/tests/endpoints/roms/test_manual.py @@ -40,33 +40,11 @@ def manual_fs_resources(tmp_path: Path, mocker: MockerFixture): @pytest.fixture -def manual_fs_folder(tmp_path: Path, mocker: MockerFixture): - """Mock fs_rom_handler so /manuals/files (folder path) writes to tmp_path.""" - folder_dir = tmp_path / "library" - folder_dir.mkdir() - - def validate_path(path: str) -> Path: - return folder_dir / Path(path).name - - async def remove_file(path: str) -> None: - target = folder_dir / Path(path).name - if target.exists(): - target.unlink() - else: - raise FileNotFoundError(path) - - mocker.patch.object(manual_endpoint.fs_rom_handler, "validate_path", validate_path) - mocker.patch.object( - manual_endpoint.fs_rom_handler, - "make_directory", - AsyncMock(return_value=None), - ) - mocker.patch.object( - manual_endpoint.fs_rom_handler, - "remove_file", - AsyncMock(side_effect=remove_file), - ) - return folder_dir +def manual_fs_folder(game_folder_on_disk: Path) -> Path: + """The ROM's manual folder inside a real temp library.""" + media_dir = game_folder_on_disk / "manual" + media_dir.mkdir() + return media_dir # ---------- POST /api/roms/{id}/manuals (resources) ---------- diff --git a/backend/tests/endpoints/roms/test_screenshot.py b/backend/tests/endpoints/roms/test_screenshot.py index 1723e29f0..38954203f 100644 --- a/backend/tests/endpoints/roms/test_screenshot.py +++ b/backend/tests/endpoints/roms/test_screenshot.py @@ -1,11 +1,9 @@ from pathlib import Path -from unittest.mock import AsyncMock import pytest from fastapi import status from fastapi.testclient import TestClient -from endpoints.roms import screenshot as screenshot_endpoint from handler.database import db_rom_handler from models.rom import Rom, RomFile, RomFileCategory @@ -17,34 +15,11 @@ def _auth(token: str) -> dict[str, str]: @pytest.fixture -def screenshot_fs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - folder_dir = tmp_path / "library" - folder_dir.mkdir() - - def validate_path(path: str) -> Path: - return folder_dir / Path(path).name - - async def remove_file(path: str) -> None: - target = folder_dir / Path(path).name - if target.exists(): - target.unlink() - else: - raise FileNotFoundError(path) - - monkeypatch.setattr( - screenshot_endpoint.fs_rom_handler, "validate_path", validate_path - ) - monkeypatch.setattr( - screenshot_endpoint.fs_rom_handler, - "make_directory", - AsyncMock(return_value=None), - ) - monkeypatch.setattr( - screenshot_endpoint.fs_rom_handler, - "remove_file", - AsyncMock(side_effect=remove_file), - ) - return folder_dir +def screenshot_fs(game_folder_on_disk: Path) -> Path: + """The ROM's screenshots folder inside a real temp library.""" + media_dir = game_folder_on_disk / "screenshots" + media_dir.mkdir() + return media_dir # ---------- POST /api/roms/{id}/screenshots ---------- diff --git a/backend/tests/endpoints/roms/test_soundtrack.py b/backend/tests/endpoints/roms/test_soundtrack.py index c9149354e..92fb36cc1 100644 --- a/backend/tests/endpoints/roms/test_soundtrack.py +++ b/backend/tests/endpoints/roms/test_soundtrack.py @@ -1,13 +1,14 @@ from pathlib import Path -from unittest.mock import AsyncMock import pytest from fastapi import status from fastapi.testclient import TestClient from endpoints.roms import soundtrack as soundtrack_endpoint +from handler import scan_handler from handler.database import db_rom_handler from models.rom import Rom, RomFile, RomFileCategory, TrackMeta +from utils import audio_tags from utils.audio_tags import AudioTags, track_meta_columns MP3_BYTES = b"ID3\x03\x00\x00\x00\x00\x00\x21fake mp3 payload" @@ -18,34 +19,11 @@ def _auth(token: str) -> dict[str, str]: @pytest.fixture -def soundtrack_fs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - folder_dir = tmp_path / "library" - folder_dir.mkdir() - - def validate_path(path: str) -> Path: - return folder_dir / Path(path).name - - async def remove_file(path: str) -> None: - target = folder_dir / Path(path).name - if target.exists(): - target.unlink() - else: - raise FileNotFoundError(path) - - monkeypatch.setattr( - soundtrack_endpoint.fs_rom_handler, "validate_path", validate_path - ) - monkeypatch.setattr( - soundtrack_endpoint.fs_rom_handler, - "make_directory", - AsyncMock(return_value=None), - ) - monkeypatch.setattr( - soundtrack_endpoint.fs_rom_handler, - "remove_file", - AsyncMock(side_effect=remove_file), - ) - return folder_dir +def soundtrack_fs(game_folder_on_disk: Path) -> Path: + """The ROM's soundtrack folder inside a real temp library.""" + media_dir = game_folder_on_disk / "soundtrack" + media_dir.mkdir() + return media_dir # ---------- POST /api/roms/{id}/soundtracks ---------- @@ -99,6 +77,64 @@ def test_upload_soundtrack_upserts_on_reupload( assert len(soundtracks) == 1 +def test_upload_soundtrack_creates_missing_folder( + client: TestClient, + access_token: str, + game_folder_rom: Rom, + soundtrack_fs: Path, +): + soundtrack_fs.rmdir() + + response = client.post( + f"/api/roms/{game_folder_rom.id}/soundtracks", + headers={**_auth(access_token), "x-upload-filename": "track1.mp3"}, + files={"track1.mp3": ("track1.mp3", MP3_BYTES, "audio/mpeg")}, + ) + + assert response.status_code == status.HTTP_201_CREATED + assert (soundtrack_fs / "track1.mp3").read_bytes() == MP3_BYTES + assert db_rom_handler.get_rom_files_by_category( + game_folder_rom.id, RomFileCategory.SOUNDTRACK + ) + + +def test_upload_soundtrack_keeps_the_other_files( + client: TestClient, + access_token: str, + game_folder_rom: Rom, + soundtrack_fs: Path, +): + before = {f.file_name for f in game_folder_rom.files} + + response = client.post( + f"/api/roms/{game_folder_rom.id}/soundtracks", + headers={**_auth(access_token), "x-upload-filename": "track1.mp3"}, + files={"track1.mp3": ("track1.mp3", MP3_BYTES, "audio/mpeg")}, + ) + + assert response.status_code == status.HTTP_201_CREATED + rom_after = db_rom_handler.get_rom(game_folder_rom.id) + assert {f.file_name for f in rom_after.files} == before | {"track1.mp3"} + assert not list(soundtrack_fs.glob(".*")) + + +def test_upload_soundtrack_without_matching_part_returns_400( + client: TestClient, + access_token: str, + game_folder_rom: Rom, + soundtrack_fs: Path, +): + response = client.post( + f"/api/roms/{game_folder_rom.id}/soundtracks", + headers={**_auth(access_token), "x-upload-filename": "track1.mp3"}, + files={"other.mp3": ("other.mp3", MP3_BYTES, "audio/mpeg")}, + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert "no file part named track1.mp3" in response.json()["detail"] + assert not list(soundtrack_fs.iterdir()) + + # Single-file auto-convert on upload is covered in test_convert_to_folder.py. @@ -220,11 +256,9 @@ def test_upload_soundtrack_extracts_audio_meta( "file_mtime": 1_700_000_000.0, "file_size": len(MP3_BYTES), } + monkeypatch.setattr(audio_tags, "extract_audio_meta", lambda _path: fake_meta) monkeypatch.setattr( - soundtrack_endpoint, "extract_audio_meta", lambda _path: fake_meta - ) - monkeypatch.setattr( - soundtrack_endpoint, + scan_handler, "persist_embedded_cover", lambda **kw: ( f"roms/{kw['platform_id']}/{kw['rom_id']}" @@ -268,18 +302,14 @@ def test_upload_soundtrack_no_cover_leaves_cover_path_unset( monkeypatch: pytest.MonkeyPatch, ): monkeypatch.setattr( - soundtrack_endpoint, - "extract_audio_meta", - lambda _path: {"has_embedded_cover": False}, + audio_tags, "extract_audio_meta", lambda _path: {"has_embedded_cover": False} ) cover_calls: list[dict] = [] def _record_cover_call(**kw: object) -> None: cover_calls.append(kw) - monkeypatch.setattr( - soundtrack_endpoint, "persist_embedded_cover", _record_cover_call - ) + monkeypatch.setattr(scan_handler, "persist_embedded_cover", _record_cover_call) response = client.post( f"/api/roms/{game_folder_rom.id}/soundtracks", @@ -468,7 +498,6 @@ def test_upload_soundtrack_rejects_dotdot_only_filename( files={"..": ("..", MP3_BYTES, "audio/mpeg")}, ) assert response.status_code == status.HTTP_400_BAD_REQUEST - assert "filename" in response.json()["detail"].lower() # ---------- 404 metadata ---------- diff --git a/backend/tests/endpoints/roms/test_upload.py b/backend/tests/endpoints/roms/test_upload.py index e30ad92cc..ec7bd3dda 100644 --- a/backend/tests/endpoints/roms/test_upload.py +++ b/backend/tests/endpoints/roms/test_upload.py @@ -5,10 +5,11 @@ from unittest.mock import AsyncMock from uuid import UUID import pytest -from fastapi import HTTPException, status +from fastapi import status from fastapi.testclient import TestClient from endpoints.roms import upload as upload_endpoint +from handler import rom_upload from handler.database import db_platform_handler, db_rom_handler from models.platform import Platform from models.rom import Rom, RomFile, RomFileCategory @@ -690,12 +691,75 @@ def test_complete_collision_does_not_promote_a_single_file_rom( assert (rom_upload_fs / rom.fs_path / "solo.zip").read_bytes() == b"romdata" +def test_start_takes_the_filename_from_the_body_over_the_header( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + """A browser cannot put a name outside Latin-1 in a header, so the body + names the file and the header only has to be present.""" + rom = _folder_rom(platform, admin_user, rom_upload_fs, {"game.bin": b"game"}) + name = "Relax \uff5c 432Hz.mp3" + + start = client.post( + "/api/roms/upload/start", + headers={ + **_auth_headers(access_token), + "x-upload-platform": str(rom.platform_id), + "x-upload-filename": "Relax%20%EF%BD%9C%20432Hz.mp3", + "x-upload-total-size": "5", + "x-upload-total-chunks": "1", + }, + json={"rom_id": rom.id, "folder": "soundtrack", "filename": name}, + ) + assert start.status_code == status.HTTP_201_CREATED, start.json() + upload_id = start.json()["upload_id"] + client.put( + f"/api/roms/upload/{upload_id}", + headers={**_auth_headers(access_token), "x-chunk-index": "0"}, + content=b"audio", + ) + complete = client.post( + f"/api/roms/upload/{upload_id}/complete", headers=_auth_headers(access_token) + ) + + assert complete.status_code == status.HTTP_201_CREATED, complete.json() + on_disk = rom_upload_fs / rom.fs_path / ROM_FOLDER / "soundtrack" / name + assert on_disk.read_bytes() == b"audio" + track = db_rom_handler.get_rom_files_by_category(rom.id, RomFileCategory.SOUNDTRACK) + assert [f.file_name for f in track] == [name] + + +def test_complete_into_a_category_folder_registers_the_category( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + rom = _folder_rom(platform, admin_user, rom_upload_fs, {"game.bin": b"game"}) + + response = _upload_into_rom( + client, + access_token, + rom, + filename="shot.png", + folder="screenshots", + data=b"\x89PNG", + ) + + assert response.status_code == status.HTTP_201_CREATED, response.json() + shots = db_rom_handler.get_rom_files_by_category(rom.id, RomFileCategory.SCREENSHOT) + assert [f.file_name for f in shots] == ["shot.png"] + + def test_claim_destination_refuses_an_existing_file(tmp_path: Path): target = tmp_path / "game.bin" - upload_endpoint._claim_destination(target) + rom_upload.claim_destination(target) assert target.exists() - with pytest.raises(HTTPException) as excinfo: - upload_endpoint._claim_destination(target) - assert excinfo.value.status_code == status.HTTP_409_CONFLICT + with pytest.raises(rom_upload.UploadConflictException): + rom_upload.claim_destination(target) diff --git a/backend/tests/endpoints/roms/test_walkthrough.py b/backend/tests/endpoints/roms/test_walkthrough.py index 3e5b0e6aa..5de5d5c78 100644 --- a/backend/tests/endpoints/roms/test_walkthrough.py +++ b/backend/tests/endpoints/roms/test_walkthrough.py @@ -18,43 +18,11 @@ def _auth(token: str) -> dict[str, str]: @pytest.fixture -def walkthrough_fs(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): - """Mock fs_rom_handler so walkthrough writes land in tmp_path.""" - folder_dir = tmp_path / "library" - folder_dir.mkdir() - - def validate_path(path: str) -> Path: - return folder_dir / Path(path).name - - async def remove_file(path: str) -> None: - target = folder_dir / Path(path).name - if target.exists(): - target.unlink() - else: - raise FileNotFoundError(path) - - async def write_file(file, path: str, filename: str) -> None: - (folder_dir / filename).write_bytes(file) - - monkeypatch.setattr( - walkthrough_endpoint.fs_rom_handler, "validate_path", validate_path - ) - monkeypatch.setattr( - walkthrough_endpoint.fs_rom_handler, - "make_directory", - AsyncMock(return_value=None), - ) - monkeypatch.setattr( - walkthrough_endpoint.fs_rom_handler, - "remove_file", - AsyncMock(side_effect=remove_file), - ) - monkeypatch.setattr( - walkthrough_endpoint.fs_rom_handler, - "write_file", - AsyncMock(side_effect=write_file), - ) - return folder_dir +def walkthrough_fs(game_folder_on_disk: Path) -> Path: + """The ROM's walkthrough folder inside a real temp library.""" + media_dir = game_folder_on_disk / "walkthrough" + media_dir.mkdir() + return media_dir # ---------- POST /api/roms/{id}/walkthroughs/files ---------- diff --git a/frontend/src/__generated__/models/UploadTargetPayload.ts b/frontend/src/__generated__/models/UploadTargetPayload.ts index 7be852bc9..d579bdf27 100644 --- a/frontend/src/__generated__/models/UploadTargetPayload.ts +++ b/frontend/src/__generated__/models/UploadTargetPayload.ts @@ -4,13 +4,20 @@ /* eslint-disable */ /** * Optional body of `/start`: upload into a ROM's folder instead of the - * platform folder. + * platform folder, and name the file where the header cannot. */ export type UploadTargetPayload = { - rom_id: number; + /** + * Upload into this ROM's folder instead of the platform folder. + */ + rom_id?: (number | null); /** * Subfolder inside the ROM's folder, relative and forward-slashed. Empty for the root. */ folder?: string; + /** + * The file name. Takes precedence over the header, which cannot carry characters outside Latin-1. + */ + filename?: (string | null); }; diff --git a/frontend/src/locales/bg_BG/rom.json b/frontend/src/locales/bg_BG/rom.json index f2210488e..855b868fe 100644 --- a/frontend/src/locales/bg_BG/rom.json +++ b/frontend/src/locales/bg_BG/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Няма намерени бързи записи", "no-states-uploaded": "Не са качени бързи записи.", - "no-tracks-uploaded": "Не са качени песни.", "note-content": "Съдържание на бележката", "note-title": "Заглавие на бележката", "note-title-exists": "Вече съществува бележка с това заглавие", @@ -472,8 +471,6 @@ "title-id": "ID на заглавието", "tracks-n": "{n} песен | {n} песни", "tracks-summary": "{count} песни · {duration}", - "tracks-uploaded-n": "Качена е {n} песен. | Качени са {n} песни.", - "tracks-uploaded-with-failed": "Качена е {n} песен, {failed} неуспешни. | Качени са {n} песни, {failed} неуспешни.", "unmatch": "Премахни разпознаването", "unmatch-success": "Разпознаването на ROM-а е премахнато успешно", "unselect-all": "Премахни избора на всички", diff --git a/frontend/src/locales/cs_CZ/rom.json b/frontend/src/locales/cs_CZ/rom.json index bdbae7be4..55980c3d2 100644 --- a/frontend/src/locales/cs_CZ/rom.json +++ b/frontend/src/locales/cs_CZ/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Nebyly nalezeny žádné stavy", "no-states-uploaded": "Žádné stavy nebyly nahrány.", - "no-tracks-uploaded": "Žádné skladby nebyly nahrány.", "note-content": "Obsah poznámky", "note-title": "Název poznámky", "note-title-exists": "Poznámka s tímto názvem již existuje", @@ -472,8 +471,6 @@ "title-id": "ID titulu", "tracks-n": "{n} skladeb | {n} skladba | {n} skladby | {n} skladeb", "tracks-summary": "{count} skladeb · {duration}", - "tracks-uploaded-n": "Nahráno {n} skladeb. | Nahrána {n} skladba. | Nahrány {n} skladby. | Nahráno {n} skladeb.", - "tracks-uploaded-with-failed": "Nahráno {n} skladeb, {failed} selhalo. | Nahrána {n} skladba, {failed} selhalo. | Nahrány {n} skladby, {failed} selhalo. | Nahráno {n} skladeb, {failed} selhalo.", "unmatch": "Odpojit ROM", "unmatch-success": "ROM úspěšně odpojena", "unselect-all": "Zrušit výběr všeho", diff --git a/frontend/src/locales/de_DE/rom.json b/frontend/src/locales/de_DE/rom.json index 8b4a5331c..e779ccc8d 100644 --- a/frontend/src/locales/de_DE/rom.json +++ b/frontend/src/locales/de_DE/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Keine Spielstände gefunden", "no-states-uploaded": "Keine Zustände wurden hochgeladen.", - "no-tracks-uploaded": "Keine Tracks wurden hochgeladen.", "note-content": "Notiz-Inhalt", "note-title": "Notiz-Titel", "note-title-exists": "Eine Notiz mit diesem Titel existiert bereits", @@ -472,8 +471,6 @@ "title-id": "Titel-ID", "tracks-n": "{n} Track | {n} Tracks", "tracks-summary": "{count} Tracks · {duration}", - "tracks-uploaded-n": "{n} Track hochgeladen. | {n} Tracks hochgeladen.", - "tracks-uploaded-with-failed": "{n} Track hochgeladen, {failed} fehlgeschlagen. | {n} Tracks hochgeladen, {failed} fehlgeschlagen.", "unmatch": "Zuweisung aufheben", "unmatch-success": "ROM-Zuweisung erfolgreich aufgehoben", "unselect-all": "Alles abwählen", diff --git a/frontend/src/locales/en_GB/rom.json b/frontend/src/locales/en_GB/rom.json index ecac5c738..58cd83e93 100644 --- a/frontend/src/locales/en_GB/rom.json +++ b/frontend/src/locales/en_GB/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "No states found", "no-states-uploaded": "No states were uploaded.", - "no-tracks-uploaded": "No tracks were uploaded.", "note-content": "Note Content", "note-title": "Note Title", "note-title-exists": "A note with this title already exists", @@ -472,8 +471,6 @@ "title-id": "Title ID", "tracks-n": "{n} track | {n} tracks", "tracks-summary": "{count} tracks · {duration}", - "tracks-uploaded-n": "Uploaded {n} track. | Uploaded {n} tracks.", - "tracks-uploaded-with-failed": "Uploaded {n} track, {failed} failed. | Uploaded {n} tracks, {failed} failed.", "unmatch": "Unmatch ROM", "unmatch-success": "ROM unmatched successfully", "unselect-all": "Unselect all", diff --git a/frontend/src/locales/en_US/rom.json b/frontend/src/locales/en_US/rom.json index dc514aeb8..82bf9280d 100644 --- a/frontend/src/locales/en_US/rom.json +++ b/frontend/src/locales/en_US/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "No states found", "no-states-uploaded": "No states were uploaded.", - "no-tracks-uploaded": "No tracks were uploaded.", "note-content": "Note Content", "note-title": "Note Title", "note-title-exists": "A note with this title already exists", @@ -472,8 +471,6 @@ "title-id": "Title ID", "tracks-n": "{n} track | {n} tracks", "tracks-summary": "{count} tracks · {duration}", - "tracks-uploaded-n": "Uploaded {n} track. | Uploaded {n} tracks.", - "tracks-uploaded-with-failed": "Uploaded {n} track, {failed} failed. | Uploaded {n} tracks, {failed} failed.", "unmatch": "Unmatch ROM", "unmatch-success": "ROM unmatched successfully", "unselect-all": "Unselect all", diff --git a/frontend/src/locales/es_ES/rom.json b/frontend/src/locales/es_ES/rom.json index bf3c224eb..61983d9f9 100644 --- a/frontend/src/locales/es_ES/rom.json +++ b/frontend/src/locales/es_ES/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "No se encontraron estados", "no-states-uploaded": "Aún no hay estados subidos", - "no-tracks-uploaded": "Aún no hay pistas subidas", "note-content": "Contenido de la Nota", "note-title": "Título de la Nota", "note-title-exists": "Ya existe una nota con este título", @@ -472,8 +471,6 @@ "title-id": "ID del título", "tracks-n": "{n} pista | {n} pistas", "tracks-summary": "{tracks}, {duration}", - "tracks-uploaded-n": "{n} pista subida | {n} pistas subidas", - "tracks-uploaded-with-failed": "{n} pista subida, {failed} con error | {n} pistas subidas, {failed} con error", "unmatch": "Desvincular ROM", "unmatch-success": "ROM desvinculada con éxito", "unselect-all": "Deseleccionar todos", diff --git a/frontend/src/locales/fr_FR/rom.json b/frontend/src/locales/fr_FR/rom.json index 051204882..631532d5b 100644 --- a/frontend/src/locales/fr_FR/rom.json +++ b/frontend/src/locales/fr_FR/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Aucun état trouvé", "no-states-uploaded": "Aucun état n'a été téléversé.", - "no-tracks-uploaded": "Aucune piste n'a été téléversée.", "note-content": "Contenu de la Note", "note-title": "Titre de la Note", "note-title-exists": "Une note avec ce titre existe déjà", @@ -472,8 +471,6 @@ "title-id": "ID du titre", "tracks-n": "{n} piste | {n} pistes", "tracks-summary": "{count} pistes · {duration}", - "tracks-uploaded-n": "{n} piste téléversée. | {n} pistes téléversées.", - "tracks-uploaded-with-failed": "{n} piste téléversée, {failed} en échec. | {n} pistes téléversées, {failed} en échec.", "unmatch": "Dissocier le ROM", "unmatch-success": "ROM dissociée avec succès", "unselect-all": "Désélectionner tous", diff --git a/frontend/src/locales/hu_HU/rom.json b/frontend/src/locales/hu_HU/rom.json index b86b444a7..92f72adf1 100644 --- a/frontend/src/locales/hu_HU/rom.json +++ b/frontend/src/locales/hu_HU/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Nem található állás", "no-states-uploaded": "Egyetlen állás sem lett feltöltve.", - "no-tracks-uploaded": "Egyetlen szám sem lett feltöltve.", "note-content": "Megjegyzés tartalma", "note-title": "Megjegyzés címe", "note-title-exists": "Már létezik egy ilyen címmel ellátott jegyzet", @@ -472,8 +471,6 @@ "title-id": "Cím ID", "tracks-n": "{n} szám | {n} szám", "tracks-summary": "{count} szám · {duration}", - "tracks-uploaded-n": "{n} szám feltöltve. | {n} szám feltöltve.", - "tracks-uploaded-with-failed": "{n} szám feltöltve, {failed} sikertelen. | {n} szám feltöltve, {failed} sikertelen.", "unmatch": "Nem egyező ROM", "unmatch-success": "A ROM sikeresen nem egyeztetettként lett jelölve", "unselect-all": "Minden kijelölés visszavonása", diff --git a/frontend/src/locales/it_IT/rom.json b/frontend/src/locales/it_IT/rom.json index 06253ffc4..3e556fc6b 100644 --- a/frontend/src/locales/it_IT/rom.json +++ b/frontend/src/locales/it_IT/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Nessun stato trovato", "no-states-uploaded": "Nessuno stato caricato.", - "no-tracks-uploaded": "Nessuna traccia caricata.", "note-content": "Contenuto della Nota", "note-title": "Titolo della Nota", "note-title-exists": "Una nota con questo titolo esiste già", @@ -472,8 +471,6 @@ "title-id": "ID titolo", "tracks-n": "{n} traccia | {n} tracce", "tracks-summary": "{count} tracce · {duration}", - "tracks-uploaded-n": "Caricata {n} traccia. | Caricate {n} tracce.", - "tracks-uploaded-with-failed": "Caricata {n} traccia, {failed} fallite. | Caricate {n} tracce, {failed} fallite.", "unmatch": "Rimuovi associazione rom", "unmatch-success": "Associazione ROM rimossa con successo", "unselect-all": "Deseleziona tutto", diff --git a/frontend/src/locales/ja_JP/rom.json b/frontend/src/locales/ja_JP/rom.json index 763b5ab08..8363bc99e 100644 --- a/frontend/src/locales/ja_JP/rom.json +++ b/frontend/src/locales/ja_JP/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "ステートセーブが見つかりません", "no-states-uploaded": "アップロードされたステートセーブはありません。", - "no-tracks-uploaded": "アップロードされたトラックはありません。", "note-content": "ノート内容", "note-title": "ノートタイトル", "note-title-exists": "このタイトルのノートがすでに存在します", @@ -472,8 +471,6 @@ "title-id": "タイトルID", "tracks-n": "{n}件のトラック | {n}件のトラック", "tracks-summary": "{count}件のトラック · {duration}", - "tracks-uploaded-n": "{n}件のトラックをアップロードしました。 | {n}件のトラックをアップロードしました。", - "tracks-uploaded-with-failed": "{n}件のトラックをアップロードしました。{failed}件失敗しました。 | {n}件のトラックをアップロードしました。{failed}件失敗しました。", "unmatch": "検索結果無し", "unmatch-success": "ROMの関連付けが正常に解除されました", "unselect-all": "すべて選択解除", diff --git a/frontend/src/locales/ko_KR/rom.json b/frontend/src/locales/ko_KR/rom.json index 96a08f955..355ce0f10 100644 --- a/frontend/src/locales/ko_KR/rom.json +++ b/frontend/src/locales/ko_KR/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "저장 상태 없음", "no-states-uploaded": "업로드된 상태가 없습니다.", - "no-tracks-uploaded": "업로드된 트랙이 없습니다.", "note-content": "노트 내용", "note-title": "노트 제목", "note-title-exists": "이 제목의 노트가 이미 존재합니다", @@ -472,8 +471,6 @@ "title-id": "타이틀 ID", "tracks-n": "{n}개 트랙 | {n}개 트랙", "tracks-summary": "{count}개 트랙 · {duration}", - "tracks-uploaded-n": "{n}개 트랙을 업로드했습니다. | {n}개 트랙을 업로드했습니다.", - "tracks-uploaded-with-failed": "{n}개 트랙을 업로드했습니다, {failed}개 실패. | {n}개 트랙을 업로드했습니다, {failed}개 실패.", "unmatch": "DB 대응 해제", "unmatch-success": "ROM 연결이 성공적으로 해제되었습니다", "unselect-all": "모두 선택 해제", diff --git a/frontend/src/locales/pl_PL/rom.json b/frontend/src/locales/pl_PL/rom.json index 93b15c6d1..a3bc4ff00 100644 --- a/frontend/src/locales/pl_PL/rom.json +++ b/frontend/src/locales/pl_PL/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Nie znaleziono stanów", "no-states-uploaded": "Nie przesłano żadnych stanów.", - "no-tracks-uploaded": "Nie przesłano żadnych utworów.", "note-content": "Treść Notatki", "note-title": "Tytuł Notatki", "note-title-exists": "Notatka z tym tytułem już istnieje", @@ -472,8 +471,6 @@ "title-id": "ID tytułu", "tracks-n": "{n} utwór | {n} utwory | {n} utworów", "tracks-summary": "{count} utworów · {duration}", - "tracks-uploaded-n": "Przesłano {n} utwór. | Przesłano {n} utwory. | Przesłano {n} utworów.", - "tracks-uploaded-with-failed": "Przesłano {n} utwór, {failed} niepowodzeń. | Przesłano {n} utwory, {failed} niepowodzeń.", "unmatch": "Odłącz ROM", "unmatch-success": "ROM został pomyślnie odłączony", "unselect-all": "Odznacz wszystkie", diff --git a/frontend/src/locales/pt_BR/rom.json b/frontend/src/locales/pt_BR/rom.json index 3a114a473..45460b746 100644 --- a/frontend/src/locales/pt_BR/rom.json +++ b/frontend/src/locales/pt_BR/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "Nenhuma trilha sonora disponível para este jogo.", "no-states-found": "Nenhum estado encontrado", "no-states-uploaded": "Nenhum state foi enviado.", - "no-tracks-uploaded": "Nenhuma faixa foi enviada.", "note-content": "Conteúdo da Nota", "note-title": "Título da Nota", "note-title-exists": "Uma nota com esse título já existe", @@ -472,8 +471,6 @@ "title-id": "ID do título", "tracks-n": "{n} faixa | {n} faixas", "tracks-summary": "{count} faixas · {duration}", - "tracks-uploaded-n": "{n} faixa enviada. | {n} faixas enviadas.", - "tracks-uploaded-with-failed": "{n} faixa enviada, {failed} com falha. | {n} faixas enviadas, {failed} com falha.", "unmatch": "Desvincular ROM", "unmatch-success": "ROM desvinculada com sucesso", "unselect-all": "Desselecionar todos", diff --git a/frontend/src/locales/ro_RO/rom.json b/frontend/src/locales/ro_RO/rom.json index fa93dd3c6..8f9d0c770 100644 --- a/frontend/src/locales/ro_RO/rom.json +++ b/frontend/src/locales/ro_RO/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Niciun stare găsită", "no-states-uploaded": "Nicio stare nu a fost încărcată.", - "no-tracks-uploaded": "Nicio piesă nu a fost încărcată.", "note-content": "Conținutul Notației", "note-title": "Titlul Notației", "note-title-exists": "Există deja o notație cu acest titlu", @@ -472,8 +471,6 @@ "title-id": "ID titlu", "tracks-n": "{n} piesă | {n} piese", "tracks-summary": "{count} piese · {duration}", - "tracks-uploaded-n": "S-a încărcat {n} piesă. | S-au încărcat {n} piese.", - "tracks-uploaded-with-failed": "S-a încărcat {n} piesă, {failed} au eșuat. | S-au încărcat {n} piese, {failed} au eșuat.", "unmatch": "Dissociază ROM-ul", "unmatch-success": "ROM-ul a fost disociat cu succes", "unselect-all": "Deselectează toate", diff --git a/frontend/src/locales/ru_RU/rom.json b/frontend/src/locales/ru_RU/rom.json index 742c9f71c..1f828fb48 100644 --- a/frontend/src/locales/ru_RU/rom.json +++ b/frontend/src/locales/ru_RU/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "Состояний не найдено", "no-states-uploaded": "Состояния не были загружены.", - "no-tracks-uploaded": "Треки не были загружены.", "note-content": "Содержание Заметки", "note-title": "Заголовок Заметки", "note-title-exists": "Заметка с таким заголовком уже существует", @@ -472,8 +471,6 @@ "title-id": "ID тайтла", "tracks-n": "{n} трек | {n} треков", "tracks-summary": "{count} треков · {duration}", - "tracks-uploaded-n": "Загружен {n} трек. | Загружено {n} треков.", - "tracks-uploaded-with-failed": "Загружен {n} трек, {failed} с ошибкой. | Загружено {n} треков, {failed} с ошибкой.", "unmatch": "Отменить совпадение", "unmatch-success": "Связь с ROM успешно отменена", "unselect-all": "Отменить выбор всех", diff --git a/frontend/src/locales/tr_TR/rom.json b/frontend/src/locales/tr_TR/rom.json index 81f205f3b..0689fa1e4 100644 --- a/frontend/src/locales/tr_TR/rom.json +++ b/frontend/src/locales/tr_TR/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "Bu oyun için müzik paketi mevcut değil.", "no-states-found": "Durum kaydı bulunamadı", "no-states-uploaded": "Hiç durum kaydı yüklenmedi.", - "no-tracks-uploaded": "Hiç parça yüklenmedi.", "note-content": "Not İçeriği", "note-title": "Not Başlığı", "note-title-exists": "Bu başlıkta bir not zaten mevcut", @@ -472,8 +471,6 @@ "title-id": "Başlık ID", "tracks-n": "{n} parça | {n} parça", "tracks-summary": "{count} parça · {duration}", - "tracks-uploaded-n": "{n} parça yüklendi. | {n} parça yüklendi.", - "tracks-uploaded-with-failed": "{n} parça yüklendi, {failed} başarısız. | {n} parça yüklendi, {failed} başarısız.", "unmatch": "ROM eşleşmesini kaldır", "unmatch-success": "ROM eşleşmesi başarıyla kaldırıldı", "unselect-all": "Tümünün seçimini kaldır", diff --git a/frontend/src/locales/zh_CN/rom.json b/frontend/src/locales/zh_CN/rom.json index a32f43752..16f714cfc 100644 --- a/frontend/src/locales/zh_CN/rom.json +++ b/frontend/src/locales/zh_CN/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "此游戏暂无原声音乐。", "no-states-found": "未找到状态", "no-states-uploaded": "未上传任何状态。", - "no-tracks-uploaded": "未上传任何曲目。", "note-content": "笔记内容", "note-title": "笔记标题", "note-title-exists": "已存在此标题的笔记", @@ -472,8 +471,6 @@ "title-id": "标题ID", "tracks-n": "{n} 个曲目 | {n} 个曲目", "tracks-summary": "{count} 个曲目 · {duration}", - "tracks-uploaded-n": "已上传 {n} 个曲目。 | 已上传 {n} 个曲目。", - "tracks-uploaded-with-failed": "已上传 {n} 个曲目,{failed} 个失败。 | 已上传 {n} 个曲目,{failed} 个失败。", "unmatch": "未匹配的 ROM", "unmatch-success": "ROM 取消匹配成功", "unselect-all": "取消选择所有", diff --git a/frontend/src/locales/zh_TW/rom.json b/frontend/src/locales/zh_TW/rom.json index 2ce3e2212..eb0830481 100644 --- a/frontend/src/locales/zh_TW/rom.json +++ b/frontend/src/locales/zh_TW/rom.json @@ -264,7 +264,6 @@ "no-soundtrack": "No soundtrack available for this game.", "no-states-found": "未找到即時存檔", "no-states-uploaded": "未上傳任何即時存檔。", - "no-tracks-uploaded": "未上傳任何音軌。", "note-content": "筆記內容", "note-title": "筆記標題", "note-title-exists": "已存在此標題的筆記", @@ -472,8 +471,6 @@ "title-id": "標題ID", "tracks-n": "{n} 個音軌 | {n} 個音軌", "tracks-summary": "{count} 個音軌 · {duration}", - "tracks-uploaded-n": "已上傳 {n} 個音軌。 | 已上傳 {n} 個音軌。", - "tracks-uploaded-with-failed": "已上傳 {n} 個音軌,{failed} 個失敗。 | 已上傳 {n} 個音軌,{failed} 個失敗。", "unmatch": "清除匹配資料", "unmatch-success": "ROM 取消匹配成功", "unselect-all": "取消選擇所有", diff --git a/frontend/src/services/api/rom.test.ts b/frontend/src/services/api/rom.test.ts index a55288121..06d12c375 100644 --- a/frontend/src/services/api/rom.test.ts +++ b/frontend/src/services/api/rom.test.ts @@ -100,7 +100,11 @@ describe("romApi.uploadRoms", () => { "X-Upload-Platform": "3", "X-Upload-Filename": "fix.ips", }); - expect(startCall().body).toEqual({ rom_id: 42, folder: "hack/v2" }); + expect(startCall().body).toEqual({ + filename: "fix.ips", + rom_id: 42, + folder: "hack/v2", + }); expect(post).toHaveBeenCalledWith( "/roms/upload/u-1/complete", null, @@ -108,16 +112,30 @@ describe("romApi.uploadRoms", () => { ); }); - it("sends no body for a platform upload", async () => { + it("names only the file for a platform upload", async () => { await romApi.uploadRoms({ platformId: 3, filesToUpload: [new File(["abc"], "game.zip")], }); - expect(startCall().body).toBeNull(); + expect(startCall().body).toEqual({ filename: "game.zip" }); expect(startCall().headers["X-Upload-Filename"]).toBe("game.zip"); }); + it("keeps a name outside Latin-1 out of the header", async () => { + const name = "Relax \uff5c 432Hz.mp3"; + await romApi.uploadRoms({ + platformId: 3, + romId: 42, + filesToUpload: [new File(["abc"], name)], + }); + + expect(startCall().body).toEqual({ filename: name, rom_id: 42 }); + expect(startCall().headers["X-Upload-Filename"]).toBe( + "Relax%20%EF%BD%9C%20432Hz.mp3", + ); + }); + it("treats an empty folder as the rom root", async () => { await romApi.uploadRoms({ platformId: 3, @@ -126,7 +144,7 @@ describe("romApi.uploadRoms", () => { filesToUpload: [new File(["abc"], "readme.txt")], }); - expect(startCall().body).toEqual({ rom_id: 42 }); + expect(startCall().body).toEqual({ filename: "readme.txt", rom_id: 42 }); }); }); diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index b7bd2998d..e58738890 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -55,12 +55,16 @@ async function uploadRomChunked({ const uploadStore = storeUpload(); const totalChunks = Math.ceil(file.size / UPLOAD_CHUNK_SIZE); - const target: UploadTargetPayload | null = - romId !== undefined ? { rom_id: romId, ...(folder && { folder }) } : null; + // The header cannot carry characters outside Latin-1, so it gets the + // percent-encoded name and the body the real one. + const target: UploadTargetPayload = { + filename: file.name, + ...(romId !== undefined && { rom_id: romId, ...(folder && { folder }) }), + }; const { data: startData } = await api.post("/roms/upload/start", target, { headers: { "X-Upload-Platform": platformId.toString(), - "X-Upload-Filename": file.name, + "X-Upload-Filename": encodeURIComponent(file.name), "X-Upload-Total-Size": file.size.toString(), "X-Upload-Total-Chunks": totalChunks.toString(), }, @@ -820,43 +824,6 @@ async function removeSoundtrack({ return api.delete(`/roms/${romId}/soundtracks/${fileId}`); } -async function uploadScreenshots({ - romId, - filesToUpload, -}: { - romId: number; - filesToUpload: File[]; -}) { - const uploadStore = storeUpload(); - - const promises = filesToUpload.map((file) => { - const formData = new FormData(); - formData.append(file.name, file); - - uploadStore.start(file.name); - return new Promise((resolve, reject) => { - api - .post(`/roms/${romId}/screenshots`, formData, { - headers: { - "Content-Type": "multipart/form-data", - "X-Upload-Filename": file.name, - }, - params: {}, - onUploadProgress: (progressEvent: AxiosProgressEvent) => { - uploadStore.update(file.name, progressEvent); - }, - }) - .then(resolve) - .catch((error) => { - uploadStore.fail(file.name, error.response?.data?.detail); - reject(error); - }); - }); - }); - - return Promise.allSettled(promises); -} - async function removeScreenshot({ romId, fileId, @@ -939,43 +906,6 @@ async function deleteRomFile({ return api.delete(`/roms/${romId}/files/${fileId}`); } -async function uploadWalkthroughFiles({ - romId, - filesToUpload, -}: { - romId: number; - filesToUpload: File[]; -}) { - const uploadStore = storeUpload(); - - const promises = filesToUpload.map((file) => { - const formData = new FormData(); - formData.append(file.name, file); - - uploadStore.start(file.name); - return new Promise((resolve, reject) => { - api - .post(`/roms/${romId}/walkthroughs/files`, formData, { - headers: { - "Content-Type": "multipart/form-data", - "X-Upload-Filename": file.name, - }, - params: {}, - onUploadProgress: (progressEvent: AxiosProgressEvent) => { - uploadStore.update(file.name, progressEvent); - }, - }) - .then(resolve) - .catch((error) => { - uploadStore.fail(file.name, error.response?.data?.detail); - reject(error); - }); - }); - }); - - return Promise.allSettled(promises); -} - async function deleteWalkthroughFile({ romId, fileId, @@ -1148,7 +1078,6 @@ export default { uploadManualFiles, deleteManualFile, deleteRomFile, - uploadWalkthroughFiles, deleteWalkthroughFile, addGamefaqsWalkthrough, getFileProgress, @@ -1156,7 +1085,6 @@ export default { uploadSoundtracks, removeSoundtrack, getSoundtrackMetadata, - uploadScreenshots, removeScreenshot, updateUserRomProps, deleteRoms, diff --git a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.test.ts b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.test.ts index 9b843598c..59db548f2 100644 --- a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.test.ts +++ b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.test.ts @@ -8,9 +8,11 @@ import ManualUploadTargetDialog from "./ManualUploadTargetDialog.vue"; type UploadArgs = { romId: number; filesToUpload: File[] }; -const { uploadManuals, uploadManualFiles, getRom } = vi.hoisted(() => ({ +const { uploadManuals, uploadFiles, getRom } = vi.hoisted(() => ({ uploadManuals: vi.fn((_args: UploadArgs) => Promise.resolve([])), - uploadManualFiles: vi.fn((_args: UploadArgs) => Promise.resolve([])), + uploadFiles: vi.fn((_rom: DetailedRom, _folder: string, _files: File[]) => + Promise.resolve({ uploaded: 1, failed: 0 }), + ), getRom: vi.fn(() => Promise.resolve({ data: {} })), })); @@ -19,7 +21,14 @@ vi.mock("vue-i18n", () => ({ })); vi.mock("@/services/api/rom", () => ({ - default: { uploadManuals, uploadManualFiles, getRom }, + default: { uploadManuals, getRom }, +})); + +vi.mock("@/v2/composables/useRomFileUpload", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("@/v2/composables/useRomFileUpload") + >()), + useRomFileUpload: () => ({ uploadFiles }), })); vi.mock("@/v2/composables/useSnackbar", () => ({ @@ -105,14 +114,17 @@ describe("ManualUploadTargetDialog", () => { const wrapper = await upload(rom({ has_simple_single_file: true })); expect(uploadManuals).toHaveBeenCalledOnce(); - expect(uploadManualFiles).not.toHaveBeenCalled(); + expect(uploadFiles).not.toHaveBeenCalled(); expect(wrapper.find("[data-test-dialog]").exists()).toBe(false); }); it("appends to the ROM folder without asking once it holds a manual", async () => { - const wrapper = await upload(rom({ files: [manualFile()] })); + const target = rom({ files: [manualFile()] }); + const wrapper = await upload(target); - expect(uploadManualFiles).toHaveBeenCalledOnce(); + expect(uploadFiles).toHaveBeenCalledWith(target, "manual", [ + expect.objectContaining({ name: "manual.pdf" }), + ]); expect(uploadManuals).not.toHaveBeenCalled(); expect(wrapper.find("[data-test-dialog]").exists()).toBe(false); }); @@ -150,7 +162,7 @@ describe("ManualUploadTargetDialog", () => { const wrapper = await upload(rom()); expect(uploadManuals).not.toHaveBeenCalled(); - expect(uploadManualFiles).not.toHaveBeenCalled(); + expect(uploadFiles).not.toHaveBeenCalled(); expect(wrapper.find("[data-test-dialog]").exists()).toBe(true); }); }); diff --git a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue index f6ee5266f..b47c2c6d1 100644 --- a/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue +++ b/frontend/src/v2/components/Dialogs/ManualUploadTargetDialog.vue @@ -10,6 +10,10 @@ import romApi from "@/services/api/rom"; import type { DetailedRom } from "@/stores/roms"; import storeUpload from "@/stores/upload"; import type { Events } from "@/types/emitter"; +import { + ROM_UPLOAD_FOLDERS, + useRomFileUpload, +} from "@/v2/composables/useRomFileUpload"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; @@ -19,22 +23,12 @@ const { t } = useI18n(); const emitter = inject>("emitter"); const snackbar = useSnackbar(); const { refetchRom } = useRomSync(); +const { uploadFiles } = useRomFileUpload(); const uploadStore = storeUpload(); -const TARGETS = { - resources: { - upload: romApi.uploadManuals, - successKey: "rom.manuals-upload-success", - skippedKey: "rom.manuals-upload-skipped", - }, - folder: { - upload: romApi.uploadManualFiles, - successKey: "rom.manual-files-upload-success", - skippedKey: "rom.manual-files-upload-skipped", - }, -} as const; - -type UploadTarget = keyof typeof TARGETS; +// The resources copy replaces the scraped manual on the ROM record; the folder +// copy is a ROM file like any other upload. +type UploadTarget = "resources" | "folder"; const show = ref(false); const rom = ref(null); @@ -57,25 +51,24 @@ const handleShow = (payload: Events["showManualUploadTargetDialog"]) => { emitter?.on("showManualUploadTargetDialog", handleShow); onBeforeUnmount(() => emitter?.off("showManualUploadTargetDialog", handleShow)); -async function handleUploadResult( - responses: PromiseSettledResult[], - successKey: string, - skippedKey: string, - target: DetailedRom, -) { +async function uploadToResources(targetRom: DetailedRom, targetFiles: File[]) { + const responses = await romApi.uploadManuals({ + romId: targetRom.id, + filesToUpload: targetFiles, + }); const successful = responses.filter((r) => r.status === "fulfilled").length; const failed = responses.length - successful; if (failed === 0) uploadStore.reset(); if (successful > 0) { - snackbar.success(t(successKey, { count: successful, failed }), { - icon: "mdi-check-bold", - timeout: 3000, - }); - await refetchRom(target.id); + snackbar.success( + t("rom.manuals-upload-success", { count: successful, failed }), + { icon: "mdi-check-bold", timeout: 3000 }, + ); + await refetchRom(targetRom.id); } else { - snackbar.warning(t(skippedKey), { + snackbar.warning(t("rom.manuals-upload-skipped"), { icon: "mdi-close-circle", timeout: 5000, }); @@ -87,12 +80,11 @@ async function uploadTo( targetRom: DetailedRom, targetFiles: File[], ) { - const { upload, successKey, skippedKey } = TARGETS[target]; - const responses = await upload({ - romId: targetRom.id, - filesToUpload: targetFiles, - }); - await handleUploadResult(responses, successKey, skippedKey, targetRom); + if (target === "folder") { + await uploadFiles(targetRom, ROM_UPLOAD_FOLDERS.manual, targetFiles); + return; + } + await uploadToResources(targetRom, targetFiles); } // Serialized so a drop mid-upload waits rather than replacing the one running. diff --git a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue index 379fd34f9..31c54a744 100644 --- a/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue +++ b/frontend/src/v2/components/GameDetails/FilesTab/FilesTab.vue @@ -36,7 +36,6 @@ // `rom.delete` permission. Each file is removed from disk and the DB // row is dropped via `DELETE /roms/{rom_id}/files/{file_id}`. import { RBtn, RCheckbox, REmptyState, RIcon, RTooltip } from "@v2/lib"; -import axios from "axios"; import { computed, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; import { useRoute, useRouter } from "vue-router"; @@ -47,11 +46,11 @@ import type { } from "@/__generated__"; import romApi from "@/services/api/rom"; import storeRoms from "@/stores/roms"; -import storeUpload from "@/stores/upload"; import { getDownloadLink } from "@/utils"; import { useCan } from "@/v2/composables/useCan"; import { useConfirm } from "@/v2/composables/useConfirm"; import { useIsAlive } from "@/v2/composables/useIsAlive"; +import { useRomFileUpload } from "@/v2/composables/useRomFileUpload"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { errorMessage } from "@/v2/utils/errorMessage"; @@ -546,9 +545,8 @@ async function deleteSelectedFiles() { // One hidden `` serves every folder: the active subtab decides // the destination, and the dialog covers "All files" or a new folder. const fileInput = ref(null); -const uploading = ref(false); +const { uploading, uploadFiles: uploadRomFiles } = useRomFileUpload(); const uploadDialogOpen = ref(false); -const uploadStore = storeUpload(); const alive = useIsAlive(); const uploadFolders = computed(() => @@ -584,69 +582,12 @@ function onDialogSubmit(payload: { folder: string; files: File[] }) { void uploadFiles(payload.folder, payload.files); } -function uploadErrorMessage(name: string, reason: unknown): string { - const status = axios.isAxiosError(reason) - ? reason.response?.status - : undefined; - if (status === 409) return t("rom.upload-file-exists", { name }); - const error = errorMessage(reason); - if (status === 400) return t("rom.upload-file-rejected", { name, error }); - return t("rom.upload-file-failed", { name, error }); -} - async function uploadFiles(folder: string, picked: File[]) { if (uploading.value) return; - if (props.rom.has_simple_single_file) { - const ok = await confirm({ - title: t("rom.convert-to-folder-title"), - body: t("rom.convert-to-folder-body"), - tone: "warning", - }); - if (!ok) return; - } - - uploading.value = true; - try { - const results = await romApi.uploadRoms({ - platformId: props.rom.platform_id, - romId: props.rom.id, - folder, - filesToUpload: picked, - }); - const ok = results.filter((r) => r.status === "fulfilled").length; - const failed = results.length - ok; - if (ok > 0) { - snackbar.success( - failed - ? t("rom.files-uploaded-with-failed", ok, { - named: { n: ok, failed }, - }) - : t("rom.files-uploaded-n", ok, { named: { n: ok } }), - { icon: "mdi-check-bold" }, - ); - } else { - snackbar.warning(t("rom.no-files-uploaded"), { - icon: "mdi-close-circle", - }); - } - // allSettled keeps the input order, so the index maps back to the file. - const firstFailed = results.findIndex((r) => r.status === "rejected"); - if (firstFailed >= 0) { - const rejected = results[firstFailed] as PromiseRejectedResult; - snackbar.error( - uploadErrorMessage(picked[firstFailed].name, rejected.reason), - ); - } - if (failed === 0) uploadStore.reset(); - if (!alive.value || ok === 0) return; - await refreshRom(); - const landed = folder.split("/")[0]; - if (alive.value && landed && validSubtabIds.value.has(landed)) { - subTab.value = landed; - } - } finally { - uploading.value = false; - } + const { uploaded } = await uploadRomFiles(props.rom, folder, picked); + if (!alive.value || uploaded === 0) return; + const landed = folder.split("/")[0]; + if (landed && validSubtabIds.value.has(landed)) subTab.value = landed; } async function refreshRom() { diff --git a/frontend/src/v2/components/GameDetails/MediaTab.vue b/frontend/src/v2/components/GameDetails/MediaTab.vue index e3558614a..cac190673 100644 --- a/frontend/src/v2/components/GameDetails/MediaTab.vue +++ b/frontend/src/v2/components/GameDetails/MediaTab.vue @@ -8,21 +8,21 @@ // * Subtab always rendered; the empty state drives the upload CTA // * The panel doubles as a drag-and-drop target (same affordance as the // Upload / Patcher views): drop files anywhere over it to upload -// * Upload goes through `romApi.uploadSoundtracks` +// * Upload goes through `useRomFileUpload`, into the soundtrack/ folder // // The soundtrack player is reused from v1 for now. import { RBtn, RDropzone, REmptyState, RIcon } from "@v2/lib"; import { computed, defineAsyncComponent, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; import { useRoute, useRouter } from "vue-router"; -import romApi from "@/services/api/rom"; import type { DetailedRom } from "@/stores/roms"; -import storeUpload from "@/stores/upload"; import { useCan } from "@/v2/composables/useCan"; -import { useConfirm } from "@/v2/composables/useConfirm"; +import { + ROM_UPLOAD_FOLDERS, + useRomFileUpload, +} from "@/v2/composables/useRomFileUpload"; import { useRomSoundtrack } from "@/v2/composables/useRomSoundtrack"; import { useRomSync } from "@/v2/composables/useRomSync"; -import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useSoundtrackActions } from "@/v2/composables/useSoundtrackActions"; const ManualSubtab = defineAsyncComponent( @@ -42,16 +42,14 @@ const ArtworkSubtab = defineAsyncComponent( ); const props = defineProps<{ rom: DetailedRom }>(); -const snackbar = useSnackbar(); -const confirm = useConfirm(); const soundtrackActions = useSoundtrackActions(); +const { uploadFiles } = useRomFileUpload(); const { tracks: soundtrackTracks, loading: soundtrackLoading, fallbackArtUrl: soundtrackArtUrl, } = useRomSoundtrack(() => props.rom); const { refetchRom } = useRomSync(); -const uploadStore = storeUpload(); const { t } = useI18n(); // Soundtrack upload / delete both gate on the ROM write grant, so read-only @@ -110,19 +108,6 @@ watch( }, ); -// ---------- Single-file -> folder conversion ---------- -// Soundtracks live inside the ROM folder, so uploading one to a single-file -// ROM promotes it to a folder ROM in place (the backend does this -// automatically on upload). Warn first since it is not reversible. -async function confirmFolderConversionIfNeeded(): Promise { - if (!props.rom.has_simple_single_file) return true; - return confirm({ - title: t("rom.convert-to-folder-title"), - body: t("rom.convert-to-folder-body"), - tone: "warning", - }); -} - // ---------- Subtab nav ---------- // We render the subtab list manually (not via RTabNav) because each // subtab's content panel owns its own section header with title + @@ -169,37 +154,7 @@ async function refreshRom() { // ---------- File handlers (shared by file input + drag-and-drop) ---------- async function handleSoundtrackFiles(files: File[]) { - if (files.length === 0) return; - if (!(await confirmFolderConversionIfNeeded())) return; - - const responses = await romApi.uploadSoundtracks({ - romId: props.rom.id, - filesToUpload: files, - }); - - const successful = responses.filter((r) => r.status === "fulfilled").length; - const failed = responses.length - successful; - - if (failed === 0) uploadStore.reset(); - - if (successful > 0) { - snackbar.success( - failed - ? t("rom.tracks-uploaded-with-failed", successful, { - named: { n: successful, failed }, - }) - : t("rom.tracks-uploaded-n", successful, { - named: { n: successful }, - }), - { icon: "mdi-check-bold", timeout: 3000 }, - ); - await refreshRom(); - } else { - snackbar.warning(t("rom.no-tracks-uploaded"), { - icon: "mdi-close-circle", - timeout: 5000, - }); - } + await uploadFiles(props.rom, ROM_UPLOAD_FOLDERS.soundtrack, files); } async function deleteSoundtrack(fileId: number) { diff --git a/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue b/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue index cc6052b85..787fb8d11 100644 --- a/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue +++ b/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue @@ -4,7 +4,7 @@ // * ROM — shared library screenshots stored in the ROM's // `screenshots/` folder (RomFile, category SCREENSHOT). Only // folder-based multi-file ROMs can host them. Public to every -// user who can see the ROM. Upload → `romApi.uploadScreenshots`. +// user who can see the ROM. Upload → `useRomFileUpload`. // * Mine — per-user screenshots stored under the user's asset folder. // Private by default, with a per-item public/private toggle. // Any ROM. Upload → `screenshotApi.uploadGalleryScreenshots`. @@ -24,6 +24,10 @@ import storeUpload from "@/stores/upload"; import type { ScreenshotItem } from "@/v2/components/GameDetails/ScreenshotsTab.vue"; import { useCan } from "@/v2/composables/useCan"; import { useConfirm } from "@/v2/composables/useConfirm"; +import { + ROM_UPLOAD_FOLDERS, + useRomFileUpload, +} from "@/v2/composables/useRomFileUpload"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { errorMessage } from "@/v2/utils/errorMessage"; @@ -50,6 +54,7 @@ const { t } = useI18n(); const snackbar = useSnackbar(); const confirm = useConfirm(); const { refetchRom } = useRomSync(); +const { uploadFiles } = useRomFileUpload(); const uploadStore = storeUpload(); const authStore = storeAuth(); const { user } = storeToRefs(authStore); @@ -58,17 +63,6 @@ const { user } = storeToRefs(authStore); // section writes per-user assets and stays available to everyone. const canEditRom = useCan("rom.edit"); -// Uploading per-ROM screenshots to a single-file ROM promotes it to a folder -// ROM in place (the backend converts on upload); warn before that happens. -async function confirmFolderConversionIfNeeded(): Promise { - if (!props.rom.has_simple_single_file) return true; - return confirm({ - title: t("rom.convert-to-folder-title"), - body: t("rom.convert-to-folder-body"), - tone: "warning", - }); -} - // ---------- ROM (shared) screenshots — RomFile-backed ---------- const romScreenshots = computed(() => { const cacheBust = encodeURIComponent(props.rom.updated_at); @@ -126,7 +120,7 @@ async function refreshRom() { await refetchRom(props.rom.id); } -// ---------- Upload result toast (shared by both upload paths) ---------- +// ---------- Upload result toast for the per-user gallery ---------- function reportUpload(responses: PromiseSettledResult[]) { const successful = responses.filter((r) => r.status === "fulfilled").length; const failed = responses.length - successful; @@ -155,14 +149,7 @@ const romDz = ref | null>(null); const myDz = ref | null>(null); async function handleRomFiles(files: File[]) { - if (files.length === 0) return; - if (!(await confirmFolderConversionIfNeeded())) return; - const responses = await romApi.uploadScreenshots({ - romId: props.rom.id, - filesToUpload: files, - }); - reportUpload(responses); - if (responses.some((r) => r.status === "fulfilled")) await refreshRom(); + await uploadFiles(props.rom, ROM_UPLOAD_FOLDERS.screenshots, files); } async function handleMyFiles(files: File[]) { diff --git a/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue b/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue index dda63f53f..d9feb8f44 100644 --- a/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue +++ b/frontend/src/v2/components/GameDetails/WalkthroughSubtab.vue @@ -11,6 +11,10 @@ import romApi from "@/services/api/rom"; import type { DetailedRom } from "@/stores/roms"; import { useCan } from "@/v2/composables/useCan"; import { useConfirm } from "@/v2/composables/useConfirm"; +import { + ROM_UPLOAD_FOLDERS, + useRomFileUpload, +} from "@/v2/composables/useRomFileUpload"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; @@ -46,6 +50,7 @@ const props = defineProps<{ rom: DetailedRom }>(); const snackbar = useSnackbar(); const confirm = useConfirm(); const { refetchRom } = useRomSync(); +const { uploadFiles } = useRomFileUpload(); const { t } = useI18n(); // Adding and removing walkthroughs both ride the ROMS write grant, matching @@ -124,22 +129,7 @@ async function confirmFolderConversionIfNeeded(): Promise { const walkthroughDz = ref | null>(null); async function handleFiles(files: File[]) { - if (files.length === 0) return; - if (!(await confirmFolderConversionIfNeeded())) return; - const responses = await romApi.uploadWalkthroughFiles({ - romId: props.rom.id, - filesToUpload: files, - }); - const ok = responses.filter((r) => r.status === "fulfilled").length; - if (ok > 0) { - await refreshRom(); - snackbar.success(t("rom.walkthrough-added"), { icon: "mdi-check-bold" }); - } else { - snackbar.error( - t("rom.walkthrough-add-failed", { error: t("common.unknown-error") }), - { icon: "mdi-close-circle" }, - ); - } + await uploadFiles(props.rom, ROM_UPLOAD_FOLDERS.walkthrough, files); } // ---------- Add from GameFAQs URL ---------- diff --git a/frontend/src/v2/composables/useRomFileUpload/index.test.ts b/frontend/src/v2/composables/useRomFileUpload/index.test.ts new file mode 100644 index 000000000..1272dc185 --- /dev/null +++ b/frontend/src/v2/composables/useRomFileUpload/index.test.ts @@ -0,0 +1,120 @@ +import { createPinia, setActivePinia } from "pinia"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import storeUpload from "@/stores/upload"; +import { ROM_UPLOAD_FOLDERS, useRomFileUpload } from "./index"; + +const { uploadRoms, refetchRom, confirmFn, snackbar } = vi.hoisted(() => ({ + uploadRoms: vi.fn(), + refetchRom: vi.fn(), + confirmFn: vi.fn(), + snackbar: { + success: vi.fn(), + error: vi.fn(), + warning: vi.fn(), + info: vi.fn(), + }, +})); + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ t: (key: string) => key }), +})); +vi.mock("@/services/api/rom", () => ({ + default: { uploadRoms }, +})); +vi.mock("@/v2/composables/useConfirm", () => ({ + useConfirm: () => confirmFn, +})); +vi.mock("@/v2/composables/useRomSync", () => ({ + useRomSync: () => ({ refetchRom }), +})); +vi.mock("@/v2/composables/useSnackbar", () => ({ + useSnackbar: () => snackbar, +})); + +const folderRom = { id: 1, platform_id: 7, has_simple_single_file: false }; +const singleFileRom = { ...folderRom, has_simple_single_file: true }; +const files = [new File(["x"], "track.mp3")]; + +describe("useRomFileUpload", () => { + beforeEach(() => { + setActivePinia(createPinia()); + vi.clearAllMocks(); + uploadRoms.mockResolvedValue([{ status: "fulfilled", value: null }]); + confirmFn.mockResolvedValue(true); + }); + + it("uploads into the folder, reports and refetches the rom", async () => { + const { uploadFiles } = useRomFileUpload(); + + const outcome = await uploadFiles( + folderRom, + ROM_UPLOAD_FOLDERS.soundtrack, + files, + ); + + expect(outcome).toEqual({ uploaded: 1, failed: 0 }); + expect(uploadRoms).toHaveBeenCalledWith({ + platformId: 7, + romId: 1, + folder: "soundtrack", + filesToUpload: files, + }); + expect(confirmFn).not.toHaveBeenCalled(); + expect(snackbar.success).toHaveBeenCalledWith( + "rom.files-uploaded-n", + expect.anything(), + ); + expect(refetchRom).toHaveBeenCalledWith(1); + }); + + it("asks before promoting a single-file rom and respects a no", async () => { + confirmFn.mockResolvedValue(false); + const { uploadFiles } = useRomFileUpload(); + + const outcome = await uploadFiles(singleFileRom, "", files); + + expect(outcome).toEqual({ uploaded: 0, failed: 0 }); + expect(confirmFn).toHaveBeenCalledWith( + expect.objectContaining({ tone: "warning" }), + ); + expect(uploadRoms).not.toHaveBeenCalled(); + }); + + it("explains a duplicate and keeps the failed entry in the upload toast", async () => { + uploadRoms.mockResolvedValue([ + { + status: "rejected", + reason: { isAxiosError: true, response: { status: 409 } }, + }, + ]); + const uploadStore = storeUpload(); + uploadStore.start("track.mp3"); + const { uploadFiles } = useRomFileUpload(); + + const outcome = await uploadFiles(folderRom, "soundtrack", files); + + expect(outcome).toEqual({ uploaded: 0, failed: 1 }); + expect(snackbar.error).toHaveBeenCalledWith("rom.upload-file-exists"); + expect(snackbar.warning).toHaveBeenCalledWith( + "rom.no-files-uploaded", + expect.anything(), + ); + expect(refetchRom).not.toHaveBeenCalled(); + expect(uploadStore.files).toHaveLength(1); + }); + + it("tracks in-flight uploads", async () => { + let release: (() => void) | undefined; + uploadRoms.mockImplementationOnce( + () => new Promise((resolve) => (release = () => resolve([]))), + ); + const { uploading, uploadFiles } = useRomFileUpload(); + + const pending = uploadFiles(folderRom, "", files); + expect(uploading.value).toBe(true); + + release?.(); + await pending; + expect(uploading.value).toBe(false); + }); +}); diff --git a/frontend/src/v2/composables/useRomFileUpload/index.ts b/frontend/src/v2/composables/useRomFileUpload/index.ts new file mode 100644 index 000000000..fe8dd5178 --- /dev/null +++ b/frontend/src/v2/composables/useRomFileUpload/index.ts @@ -0,0 +1,119 @@ +// useRomFileUpload: the one way a v2 tab puts files into a ROM's folder. +// +// The Files tab targets any subfolder and the Media subtabs target the folder +// the scanner maps to their category, but the upload itself is the same: +// confirm the single-file promotion, stream through the chunked upload, +// report the outcome and refetch the ROM. +import axios from "axios"; +import { computed, ref } from "vue"; +import { useI18n } from "vue-i18n"; +import type { DetailedRomSchema } from "@/__generated__"; +import romApi from "@/services/api/rom"; +import storeUpload from "@/stores/upload"; +import { useConfirm } from "@/v2/composables/useConfirm"; +import { useIsAlive } from "@/v2/composables/useIsAlive"; +import { useRomSync } from "@/v2/composables/useRomSync"; +import { useSnackbar } from "@/v2/composables/useSnackbar"; +import { errorMessage } from "@/v2/utils/errorMessage"; + +/** The subfolder each Media subtab uploads into. The scanner maps these + * names to the file category, so the file registers as the tab expects. */ +export const ROM_UPLOAD_FOLDERS = { + manual: "manual", + walkthrough: "walkthrough", + screenshots: "screenshots", + soundtrack: "soundtrack", +} as const; + +export type UploadableRom = Pick< + DetailedRomSchema, + "id" | "platform_id" | "has_simple_single_file" +>; + +export interface RomFileUploadOutcome { + uploaded: number; + failed: number; +} + +const NOTHING_UPLOADED: RomFileUploadOutcome = { uploaded: 0, failed: 0 }; + +export function useRomFileUpload() { + const { t } = useI18n(); + const snackbar = useSnackbar(); + const confirm = useConfirm(); + const uploadStore = storeUpload(); + const { refetchRom } = useRomSync(); + const alive = useIsAlive(); + + const inFlight = ref(0); + const uploading = computed(() => inFlight.value > 0); + + function failureMessage(name: string, reason: unknown): string { + const status = axios.isAxiosError(reason) + ? reason.response?.status + : undefined; + if (status === 409) return t("rom.upload-file-exists", { name }); + const error = errorMessage(reason); + if (status === 400) return t("rom.upload-file-rejected", { name, error }); + return t("rom.upload-file-failed", { name, error }); + } + + /** Upload `files` into `folder` inside the ROM ("" for its root). A lone + * file ROM is promoted to a folder first, after the user agrees. */ + async function uploadFiles( + rom: UploadableRom, + folder: string, + files: File[], + ): Promise { + if (files.length === 0) return NOTHING_UPLOADED; + if (rom.has_simple_single_file) { + const ok = await confirm({ + title: t("rom.convert-to-folder-title"), + body: t("rom.convert-to-folder-body"), + tone: "warning", + }); + if (!ok) return NOTHING_UPLOADED; + } + + inFlight.value += 1; + try { + const results = await romApi.uploadRoms({ + platformId: rom.platform_id, + romId: rom.id, + folder, + filesToUpload: files, + }); + const uploaded = results.filter((r) => r.status === "fulfilled").length; + const failed = results.length - uploaded; + if (uploaded > 0) { + snackbar.success( + failed + ? t("rom.files-uploaded-with-failed", uploaded, { + named: { n: uploaded, failed }, + }) + : t("rom.files-uploaded-n", uploaded, { named: { n: uploaded } }), + { icon: "mdi-check-bold" }, + ); + } else { + snackbar.warning(t("rom.no-files-uploaded"), { + icon: "mdi-close-circle", + }); + } + // allSettled keeps the input order, so the index maps back to the file. + const firstFailed = results.findIndex((r) => r.status === "rejected"); + if (firstFailed >= 0) { + const rejected = results[firstFailed] as PromiseRejectedResult; + snackbar.error( + failureMessage(files[firstFailed].name, rejected.reason), + ); + } + if (failed === 0) uploadStore.reset(); + if (alive.value && uploaded > 0) await refetchRom(rom.id); + return { uploaded, failed }; + } finally { + inFlight.value -= 1; + } + } + + return { uploading, uploadFiles }; +} From 83569d6678b6c2e7a78675a5ba71e77ac6833dd2 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 15:57:59 +0200 Subject: [PATCH 09/28] fix(tasks): read older cleanup stats, and check the worker where it enqueues Follow-up to #4548 from the code-review pass. Stats a 5.2.0 release stored under `platform_id` are widened to `platform_ids` when a job is reported, so listing old finished cleanups validates again. The live worker check moves next to the queues as `has_live_worker`, with its own tests, and the endpoint names the queue it enqueues on so the check and the enqueue cannot drift apart. The cleanup tasks return the typed stats the response schemas declare. The developer setup points the RQ commands at the backend's own Redis settings through `-c config`, and the architecture doc mentions the 503. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01F9ta8rXUTP9aMdatPYKX4K --- DEVELOPER_SETUP.md | 10 +- backend/endpoints/tasks.py | 39 ++--- backend/handler/redis_handler.py | 18 +++ .../tasks/manual/cleanup_missing_firmware.py | 19 ++- backend/tasks/manual/cleanup_missing_roms.py | 19 ++- backend/tests/endpoints/test_tasks.py | 147 ++++++------------ backend/tests/handler/test_redis_handler.py | 35 ++++- docs/BACKEND_ARCHITECTURE.md | 2 +- .../Settings/MissingFirmwareSection.test.ts | 29 +--- .../Settings/MissingGamesSection.test.ts | 34 ++-- 10 files changed, 173 insertions(+), 179 deletions(-) diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index 6b0518c13..0712adc68 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -128,23 +128,23 @@ uv run python3 main.py #### - Run the task workers -Manual tasks (the missing ROMs and firmware cleanups, folder sync) and every scheduled job run on RQ workers, and scans on a worker of their own. Without them a task stays queued. Each command is a foreground process, so run them in separate terminals. The Redis URL below matches the `REDIS_*` defaults in `.env`; adjust it if you changed them. +A manual task run is refused, and a scheduled job stays queued, until an RQ worker listens on its queue; scans have a worker of their own. Each command is a foreground process, so run them in separate terminals. `-c config` reads the Redis connection from the same `REDIS_*` settings in `.env` the backend uses. ```sh cd backend -uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker --with-scheduler high default low +uv run rq worker -c config --worker-class handler.rq_worker.RomMWorker --with-scheduler high default low ``` ```sh cd backend -uv run rq worker --url redis://127.0.0.1:6379/0 --worker-class handler.rq_worker.RomMWorker scans +uv run rq worker -c config --worker-class handler.rq_worker.RomMWorker --with-scheduler scans ``` -`--with-scheduler` only releases delayed jobs. The recurring schedule itself is registered by the RQ cron process, which the workers then execute: +`--with-scheduler` releases delayed jobs, such as the rescans the filesystem watcher waits out, so each worker needs it. The recurring schedule is registered by the RQ cron process, which the workers then execute: ```sh cd backend -RQ_REDIS_URL=redis://127.0.0.1:6379/0 uv run rq cron tasks.cron_config +uv run rq cron -c config tasks.cron_config ``` ### Setting up the frontend diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index 119957b14..133558924 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -2,15 +2,15 @@ from datetime import datetime, timezone from typing import Any, Final, Mapping, cast from fastapi import Body, HTTPException, Request, status -from rq import Queue, Worker +from rq import Worker from rq.exceptions import NoSuchJobError from rq.job import Job, JobStatus from rq.registry import FailedJobRegistry, FinishedJobRegistry -from rq.worker import WorkerStatus from config import ENABLE_RESCAN_ON_FILESYSTEM_CHANGE, RESCAN_ON_FILESYSTEM_CHANGE_DELAY from decorators.auth import protected_route from endpoints.responses import ( + CleanupStats, CleanupTaskStatusResponse, ConversionTaskStatusResponse, GenericTaskStatusResponse, @@ -28,6 +28,7 @@ from handler.redis_handler import ( ALL_QUEUES, get_job_func_name, get_worker_current_job, + has_live_worker, low_prio_queue, redis_client, ) @@ -88,6 +89,17 @@ def _fill_scan_stats(stats: Mapping[str, Any] | None) -> ScanStats | None: return cast(ScanStats, {**_EMPTY_SCAN_STATS, **stats}) +def _fill_cleanup_stats(stats: Mapping[str, Any] | None) -> CleanupStats | None: + """Widen the single platform an older release's stored stats named.""" + if stats is None or "platform_id" not in stats: + return cast(CleanupStats | None, stats) + + legacy = {**stats} + platform_id = legacy.pop("platform_id") + legacy["platform_ids"] = [platform_id] if platform_id is not None else None + return cast(CleanupStats, legacy) + + def _build_task_status_response( job: Job, ) -> TaskStatusResponse: @@ -142,7 +154,9 @@ def _build_task_status_response( case TaskType.CLEANUP: return CleanupTaskStatusResponse( task_type=TaskType.CLEANUP, - meta={"cleanup_stats": job_meta.get("cleanup_stats")}, + meta={ + "cleanup_stats": _fill_cleanup_stats(job_meta.get("cleanup_stats")) + }, **common_data, # trunk-ignore(mypy/typeddict-item) ) case TaskType.SYNC: @@ -275,19 +289,6 @@ async def get_task_by_id(request: Request, task_id: str) -> TaskStatusResponse: TASK_KWARGS = Body(default=None) -def _listening_workers(queue: Queue) -> list[Worker]: - """Registered workers of ``queue`` that are alive and not suspended. - - A crashed worker stays registered until its TTL expires, which RQ's own - maintenance sweep bounds; this filters the ones that told us they left. - """ - return [ - worker - for worker in Worker.all(queue=queue, connection=redis_client) - if worker.death_date is None and worker.get_state() != WorkerStatus.SUSPENDED - ] - - @protected_route(router.post, "/run/{task_name}", [Scope.TASKS_RUN]) async def run_single_task( request: Request, @@ -317,15 +318,15 @@ async def run_single_task( ) # Without a worker the job would sit queued while the UI waits on it. - if not _listening_workers(low_prio_queue): + if not has_live_worker(low_prio_queue): raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="No task worker is running, so the task cannot be queued", + detail="No task worker is listening, so the task cannot be queued", ) # The caller's arguments are nested rather than spread, so a body cannot # name a different task than the one this route just authorized. - job = enqueue_task(task_name, task_kwargs=task_kwargs or {}) + job = enqueue_task(task_name, queue=low_prio_queue, task_kwargs=task_kwargs or {}) return { "task_key": task_name, diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index 7ae82a13c..66898a730 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -8,6 +8,7 @@ from redis.asyncio import Redis as AsyncRedis from rq import Queue, Worker from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobError from rq.job import Job, JobStatus +from rq.worker import WorkerStatus from config import IS_PYTEST_RUN, REDIS_URL from logger.logger import log @@ -161,3 +162,20 @@ def get_worker_current_job(worker: Worker) -> Job | None: return worker.get_current_job() except NoSuchJobError: return None + + +def has_live_worker(queue: Queue) -> bool: + """Whether a worker registered on ``queue`` is alive and not suspended. + + Args: + queue: The RQ Queue whose worker set to read + + Returns: + Whether a job enqueued on it would be picked up + """ + # A crashed worker stays registered until its key TTL lapses, so this can + # still say yes for a few minutes after a kill. + return any( + worker.get_state() != WorkerStatus.SUSPENDED + for worker in Worker.all(queue=queue) + ) diff --git a/backend/tasks/manual/cleanup_missing_firmware.py b/backend/tasks/manual/cleanup_missing_firmware.py index afa7a3a76..3d869833c 100644 --- a/backend/tasks/manual/cleanup_missing_firmware.py +++ b/backend/tasks/manual/cleanup_missing_firmware.py @@ -1,5 +1,6 @@ from dataclasses import dataclass +from endpoints.responses import MissingFirmwareCleanupStats from handler.database import db_firmware_handler from logger.logger import log from tasks.tasks import Task, TaskType, update_job_meta @@ -22,13 +23,13 @@ class CleanupMissingFirmwareStats: update_job_meta({"cleanup_stats": self.to_dict()}) - def to_dict(self) -> dict: - return { - "platform_ids": self.platform_ids, - "firmware_found": self.firmware_found, - "firmware_deleted": self.firmware_deleted, - "errors": self.errors, - } + def to_dict(self) -> MissingFirmwareCleanupStats: + return MissingFirmwareCleanupStats( + platform_ids=self.platform_ids, + firmware_found=self.firmware_found, + firmware_deleted=self.firmware_deleted, + errors=self.errors, + ) class CleanupMissingFirmwareTask(Task): @@ -43,7 +44,9 @@ class CleanupMissingFirmwareTask(Task): ) @initialize_context() - async def run(self, platform_ids: list[int] | None = None) -> dict: + async def run( + self, platform_ids: list[int] | None = None + ) -> MissingFirmwareCleanupStats: """Clean up firmware that is flagged as missing from the filesystem.""" log.info(f"Starting {self.title} task...") diff --git a/backend/tasks/manual/cleanup_missing_roms.py b/backend/tasks/manual/cleanup_missing_roms.py index e4f2b2fbd..525d560fd 100644 --- a/backend/tasks/manual/cleanup_missing_roms.py +++ b/backend/tasks/manual/cleanup_missing_roms.py @@ -1,6 +1,7 @@ from dataclasses import dataclass from typing import Any +from endpoints.responses import MissingRomsCleanupStats from handler.database import db_rom_handler from handler.filesystem import fs_resource_handler from logger.logger import log @@ -24,13 +25,13 @@ class CleanupMissingRomsStats: update_job_meta({"cleanup_stats": self.to_dict()}) - def to_dict(self) -> dict: - return { - "platform_ids": self.platform_ids, - "roms_found": self.roms_found, - "roms_deleted": self.roms_deleted, - "errors": self.errors, - } + def to_dict(self) -> MissingRomsCleanupStats: + return MissingRomsCleanupStats( + platform_ids=self.platform_ids, + roms_found=self.roms_found, + roms_deleted=self.roms_deleted, + errors=self.errors, + ) class CleanupMissingRomsTask(Task): @@ -45,7 +46,9 @@ class CleanupMissingRomsTask(Task): ) @initialize_context() - async def run(self, platform_ids: list[int] | None = None) -> dict: + async def run( + self, platform_ids: list[int] | None = None + ) -> MissingRomsCleanupStats: """Clean up ROMs that are flagged as missing from the filesystem.""" log.info(f"Starting {self.title} task...") diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index dd73d6f0f..416b002c2 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -5,31 +5,12 @@ import pytest from fastapi import status from rq.exceptions import NoSuchJobError -from handler.redis_handler import low_prio_queue, redis_client, scan_queue +from handler.redis_handler import low_prio_queue, redis_client from tasks.manual.cleanup_missing_firmware import CleanupMissingFirmwareStats from tasks.manual.cleanup_missing_roms import CleanupMissingRomsStats from tasks.tasks import Task, TaskType -def _live_worker() -> Mock: - worker = Mock(death_date=None) - worker.get_state.return_value = "idle" - return worker - - -@pytest.fixture(autouse=True) -def task_queue_worker(): - """A live worker on the task queue, so a run is accepted unless a test - takes it away.""" - worker = _live_worker() - - def workers_for(connection=None, queue=None, **_kwargs): - return [worker] if queue is low_prio_queue else [] - - with patch("endpoints.tasks.Worker.all", side_effect=workers_for) as mocked: - yield mocked - - def _job_with_meta(meta: dict[str, Any]) -> Mock: """A finished job carrying `meta`, for asserting on what the response reports.""" job = Mock() @@ -256,6 +237,12 @@ class TestListTasks: class TestRunSingleTask: """Test suite for the run_single_task endpoint""" + @pytest.fixture(autouse=True) + def task_worker_listening(self): + """A live task worker, so a run is accepted unless a test takes it away.""" + with patch("endpoints.tasks.has_live_worker", return_value=True) as mocked: + yield mocked + @patch("endpoints.tasks.enqueue_task", return_value=create_mock_job()) @patch( "endpoints.tasks.RUNNABLE_TASKS", @@ -273,7 +260,9 @@ class TestRunSingleTask: ), }, ) - def test_run_single_task_success(self, mock_enqueue, client, access_token): + def test_run_single_task_success( + self, mock_enqueue, client, access_token, task_worker_listening + ): """Test successful running of a single task""" response = client.post( "/api/tasks/run/test_task", @@ -290,27 +279,18 @@ class TestRunSingleTask: assert "created_at" in data assert "enqueued_at" in data - mock_enqueue.assert_called_once() + # The worker check and the enqueue must name the same queue. + task_worker_listening.assert_called_once_with(low_prio_queue) + mock_enqueue.assert_called_once_with( + "test_task", queue=low_prio_queue, task_kwargs={} + ) @patch("endpoints.tasks.enqueue_task") - @patch( - "endpoints.tasks.RUNNABLE_TASKS", - { - "test_task": Mock( - spec=Task, - task_type=TaskType.CLEANUP, - title="Test Task", - enabled=True, - manual_run=True, - can_run_manually=True, - run=Mock(), - ), - }, - ) def test_run_single_task_without_a_worker_is_refused( - self, mock_enqueue, client, access_token + self, mock_enqueue, client, access_token, mock_task, task_worker_listening ): - with patch("endpoints.tasks.Worker.all", return_value=[]): + task_worker_listening.return_value = False + with patch("endpoints.tasks.RUNNABLE_TASKS", {"test_task": mock_task}): response = client.post( "/api/tasks/run/test_task", headers={"Authorization": f"Bearer {access_token}"}, @@ -320,48 +300,6 @@ class TestRunSingleTask: assert "worker" in response.json()["detail"] mock_enqueue.assert_not_called() - @pytest.mark.parametrize( - "workers_for", - [ - # A scan worker does not serve the task queue. - lambda connection=None, queue=None, **_: ( - [_live_worker()] if queue is scan_queue else [] - ), - # One that announced its death or was suspended does not count. - lambda connection=None, queue=None, **_: [Mock(death_date="gone")], - lambda connection=None, queue=None, **_: [ - Mock(death_date=None, **{"get_state.return_value": "suspended"}) - ], - ], - ids=["scan-worker-only", "dead-worker", "suspended-worker"], - ) - @patch("endpoints.tasks.enqueue_task") - @patch( - "endpoints.tasks.RUNNABLE_TASKS", - { - "test_task": Mock( - spec=Task, - task_type=TaskType.CLEANUP, - title="Test Task", - enabled=True, - manual_run=True, - can_run_manually=True, - run=Mock(), - ), - }, - ) - def test_only_a_live_worker_on_the_task_queue_counts( - self, mock_enqueue, client, access_token, workers_for - ): - with patch("endpoints.tasks.Worker.all", side_effect=workers_for): - response = client.post( - "/api/tasks/run/test_task", - headers={"Authorization": f"Bearer {access_token}"}, - ) - - assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE - mock_enqueue.assert_not_called() - @patch("endpoints.tasks.RUNNABLE_TASKS", {}) def test_run_single_task_not_found(self, client, access_token): """Test running a non-existent task""" @@ -484,30 +422,47 @@ class TestGetTaskById: def test_a_finished_cleanup_reports_its_stats( self, mock_job_fetch, client, access_token, stats ): - mock_job = Mock() - for field in ("enqueued_at", "created_at", "started_at", "ended_at"): - setattr(mock_job, field, Mock()) - getattr(mock_job, field).isoformat.return_value = "2023-01-01T00:00:00" - mock_job.get_meta.return_value = { - "task_key": "cleanup_missing_roms", - "task_type": TaskType.CLEANUP, - "cleanup_stats": stats.to_dict(), - } - mock_job.func_name = "tasks.tasks.run_task_by_name" - mock_job.kwargs = {"name": "cleanup_missing_roms"} - mock_job.get_status.return_value = "finished" - mock_job.id = "cleanup-job" - mock_job.result = stats.to_dict() - mock_job_fetch.return_value = mock_job + mock_job_fetch.return_value = _job_with_meta({"cleanup_stats": stats.to_dict()}) response = client.get( - "/api/tasks/cleanup-job", + "/api/tasks/test-job-id-123", headers={"Authorization": f"Bearer {access_token}"}, ) assert response.status_code == status.HTTP_200_OK assert response.json()["meta"]["cleanup_stats"] == stats.to_dict() + @pytest.mark.parametrize(("platform_id", "platform_ids"), [(3, [3]), (None, None)]) + @patch("endpoints.tasks.Job.fetch") + def test_a_cleanup_predating_platform_ids_reports_them( + self, mock_job_fetch, client, access_token, platform_id, platform_ids + ): + """Stats stored by an older release name a single platform.""" + mock_job_fetch.return_value = _job_with_meta( + { + # The shape 5.2.0 stored. + "cleanup_stats": { + "platform_id": platform_id, + "roms_found": 2, + "roms_deleted": 2, + "errors": 0, + }, + } + ) + + response = client.get( + "/api/tasks/test-job-id-123", + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json()["meta"]["cleanup_stats"] == { + "platform_ids": platform_ids, + "roms_found": 2, + "roms_deleted": 2, + "errors": 0, + } + @patch("endpoints.tasks.Job.fetch") def test_get_task_by_id_success(self, mock_job_fetch, client, access_token): """Test successful retrieval of a task by job ID""" diff --git a/backend/tests/handler/test_redis_handler.py b/backend/tests/handler/test_redis_handler.py index 8ccecde33..3912f7984 100644 --- a/backend/tests/handler/test_redis_handler.py +++ b/backend/tests/handler/test_redis_handler.py @@ -1,5 +1,6 @@ -from unittest.mock import MagicMock, PropertyMock +from unittest.mock import MagicMock, PropertyMock, patch +import pytest from rq import Worker from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobError from rq.job import Job, JobStatus @@ -10,6 +11,8 @@ from handler.redis_handler import ( get_job_kwargs, get_job_status, get_worker_current_job, + has_live_worker, + low_prio_queue, ) @@ -112,3 +115,33 @@ class TestGetWorkerCurrentJob: worker = self._worker(side_effect=NoSuchJobError) assert get_worker_current_job(worker) is None + + +class TestHasLiveWorker: + @staticmethod + def _worker(state: str) -> MagicMock: + worker = MagicMock(spec=Worker) + worker.get_state.return_value = state + return worker + + @pytest.mark.parametrize( + ("states", "expected"), + [ + ([], False), + (["suspended"], False), + (["suspended", "idle"], True), + (["busy"], True), + ], + ids=["none-registered", "suspended", "one-live", "busy"], + ) + def test_counts_only_workers_that_would_take_a_job( + self, states: list[str], expected: bool + ): + workers = [self._worker(state) for state in states] + + with patch( + "handler.redis_handler.Worker.all", return_value=workers + ) as mock_all: + assert has_live_worker(low_prio_queue) is expected + + mock_all.assert_called_once_with(queue=low_prio_queue) diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index 9039f40c7..765294970 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -1416,7 +1416,7 @@ Toggled via environment variables: ### Manual Tasks -Triggered via `POST /api/tasks/run/{task_name}`: +Triggered via `POST /api/tasks/run/{task_name}`, which enqueues on `low_prio_queue` and answers 503 when no live worker is listening on it: | Task | Description | | ---------------------- | --------------------------------------------- | diff --git a/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts b/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts index c20a8a93a..3b4174363 100644 --- a/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts +++ b/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts @@ -17,12 +17,10 @@ const { getFirmware, runTask, getTaskById, confirm, snackbarError } = vi.mock("@/services/api/firmware", () => ({ default: { getFirmware } })); vi.mock("@/services/api/task", () => ({ default: { runTask, getTaskById } })); -// Error messages keep their `error` parameter so the tests can see what -// reached the snackbar. vi.mock("vue-i18n", () => ({ useI18n: () => ({ - t: (key: string, params?: { error?: string }) => - params?.error ? `${key}: ${params.error}` : key, + t: (key: string, params?: Record) => + params ? `${key}::${JSON.stringify(params)}` : key, }), })); @@ -33,21 +31,10 @@ vi.mock("@/v2/composables/useSnackbar", () => ({ useSnackbar: () => ({ success: vi.fn(), error: snackbarError }), })); -// The server's reason for a refused request, as axios delivers it. function serverError(detail: string) { - return new AxiosError( - "Request failed with status code 503", - "ERR_BAD_RESPONSE", - undefined, - undefined, - { - status: 503, - statusText: "Service Unavailable", - data: { detail }, - headers: {}, - config: {} as never, - }, - ); + return Object.assign(new AxiosError("HTTP 503"), { + response: { data: { detail } }, + }); } const PS1 = { @@ -266,7 +253,7 @@ describe("MissingFirmwareSection", () => { }); it("tells why the server refused the cleanup", async () => { - runTask.mockRejectedValue(serverError("No task worker is running")); + runTask.mockRejectedValue(serverError("No task worker is listening")); const wrapper = mountSection(); await flushPromises(); @@ -274,7 +261,7 @@ describe("MissingFirmwareSection", () => { await flushPromises(); expect(snackbarError).toHaveBeenCalledWith( - "settings.couldnt-queue-cleanup: No task worker is running", + 'settings.couldnt-queue-cleanup::{"error":"No task worker is listening"}', ); }); @@ -284,7 +271,7 @@ describe("MissingFirmwareSection", () => { await flushPromises(); expect(snackbarError).toHaveBeenCalledWith( - "settings.couldnt-fetch-missing-firmware: Database unavailable", + 'settings.couldnt-fetch-missing-firmware::{"error":"Database unavailable"}', ); }); }); diff --git a/frontend/src/v2/components/Settings/MissingGamesSection.test.ts b/frontend/src/v2/components/Settings/MissingGamesSection.test.ts index 44a7c5c0a..b317dcae8 100644 --- a/frontend/src/v2/components/Settings/MissingGamesSection.test.ts +++ b/frontend/src/v2/components/Settings/MissingGamesSection.test.ts @@ -22,12 +22,10 @@ vi.mock("@/services/api/task", () => ({ default: { runTask, getTaskById }, })); -// Error messages keep their `error` parameter so the tests can see what -// reached the snackbar. vi.mock("vue-i18n", () => ({ useI18n: () => ({ - t: (key: string, params?: { error?: string }) => - params?.error ? `${key}: ${params.error}` : key, + t: (key: string, params?: Record) => + params ? `${key}::${JSON.stringify(params)}` : key, }), })); @@ -48,6 +46,12 @@ vi.mock("@/v2/composables/useWebpSupport", () => ({ useWebpSupport: () => ({ supportsWebp: { value: true } }), })); +function serverError(detail: string) { + return Object.assign(new AxiosError("HTTP 503"), { + response: { data: { detail } }, + }); +} + function mountSection() { return mount(MissingGamesSection, { global: { @@ -117,22 +121,12 @@ describe("MissingGamesSection", () => { }); it("tells why the server refused the cleanup", async () => { + // The action is disabled while the list is empty. + getRoms.mockResolvedValue({ + data: { total: 1, items: [], char_index: {}, rom_id_index: [] }, + }); confirm.mockResolvedValue(true); - runTask.mockRejectedValue( - new AxiosError( - "Request failed with status code 503", - "ERR_BAD_RESPONSE", - undefined, - undefined, - { - status: 503, - statusText: "Service Unavailable", - data: { detail: "No task worker is running" }, - headers: {}, - config: {} as never, - }, - ), - ); + runTask.mockRejectedValue(serverError("No task worker is listening")); const wrapper = mountSection(); await flushPromises(); @@ -140,7 +134,7 @@ describe("MissingGamesSection", () => { await flushPromises(); expect(snackbarError).toHaveBeenCalledWith( - "settings.couldnt-queue-cleanup: No task worker is running", + 'settings.couldnt-queue-cleanup::{"error":"No task worker is listening"}', ); }); From dafccf55fd08cf8633172f966a588feddc165a32 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 16:13:34 +0200 Subject: [PATCH 10/28] Ask before replacing a file the ROM folder already holds A name the folder already has is refused by /roms/upload/start with a 409, and the tabs used to surface that as a plain error. useRomFileUpload now collects the refused files, asks once in a danger-toned confirm dialog and retries them with the new optional overwrite body field, which lets the chunked flow replace the file instead of claiming the name exclusively. A declined file is dropped without a toast. The strings ship in all locales. Co-Authored-By: Claude Fable 5.1 --- backend/endpoints/roms/upload.py | 14 +++- backend/tests/endpoints/roms/test_upload.py | 48 +++++++++++- .../models/UploadTargetPayload.ts | 4 + frontend/src/locales/bg_BG/common.json | 1 + frontend/src/locales/bg_BG/rom.json | 2 + frontend/src/locales/cs_CZ/common.json | 1 + frontend/src/locales/cs_CZ/rom.json | 2 + frontend/src/locales/de_DE/common.json | 1 + frontend/src/locales/de_DE/rom.json | 2 + frontend/src/locales/en_GB/common.json | 1 + frontend/src/locales/en_GB/rom.json | 2 + frontend/src/locales/en_US/common.json | 1 + frontend/src/locales/en_US/rom.json | 2 + frontend/src/locales/es_ES/common.json | 1 + frontend/src/locales/es_ES/rom.json | 2 + frontend/src/locales/fr_FR/common.json | 1 + frontend/src/locales/fr_FR/rom.json | 2 + frontend/src/locales/hu_HU/common.json | 1 + frontend/src/locales/hu_HU/rom.json | 2 + frontend/src/locales/it_IT/common.json | 1 + frontend/src/locales/it_IT/rom.json | 2 + frontend/src/locales/ja_JP/common.json | 1 + frontend/src/locales/ja_JP/rom.json | 2 + frontend/src/locales/ko_KR/common.json | 1 + frontend/src/locales/ko_KR/rom.json | 2 + frontend/src/locales/pl_PL/common.json | 1 + frontend/src/locales/pl_PL/rom.json | 2 + frontend/src/locales/pt_BR/common.json | 1 + frontend/src/locales/pt_BR/rom.json | 2 + frontend/src/locales/ro_RO/common.json | 1 + frontend/src/locales/ro_RO/rom.json | 2 + frontend/src/locales/ru_RU/common.json | 1 + frontend/src/locales/ru_RU/rom.json | 2 + frontend/src/locales/tr_TR/common.json | 1 + frontend/src/locales/tr_TR/rom.json | 2 + frontend/src/locales/zh_CN/common.json | 1 + frontend/src/locales/zh_CN/rom.json | 2 + frontend/src/locales/zh_TW/common.json | 1 + frontend/src/locales/zh_TW/rom.json | 2 + frontend/src/services/api/rom.test.ts | 17 +++++ frontend/src/services/api/rom.ts | 13 +++- .../useRomFileUpload/index.test.ts | 53 ++++++++++++- .../v2/composables/useRomFileUpload/index.ts | 76 +++++++++++++++---- 43 files changed, 253 insertions(+), 26 deletions(-) diff --git a/backend/endpoints/roms/upload.py b/backend/endpoints/roms/upload.py index f48fb1517..8c75c9ef7 100644 --- a/backend/endpoints/roms/upload.py +++ b/backend/endpoints/roms/upload.py @@ -221,7 +221,7 @@ async def _resolve_destination(request: Request, session: dict) -> UploadDestina rom = _get_upload_rom(request, rom_id, session["platform_id"]) return await _prepare_rom_destination( - rom, session["folder"], filename, overwrite=False + rom, session["folder"], filename, overwrite=session["overwrite"] ) @@ -242,6 +242,10 @@ class UploadTargetPayload(BaseModel): default=None, description="The file name. Takes precedence over the header, which cannot carry characters outside Latin-1.", ) + overwrite: bool = Field( + default=False, + description="Replace a file of the same name in the ROM's folder instead of refusing the upload.", + ) @protected_route( @@ -284,6 +288,7 @@ async def start_chunked_upload( filename = target.filename safe_filename = _sanitized_filename(filename) rom_id = target.rom_id if target else None + overwrite = bool(target and target.overwrite and rom_id is not None) rel_folder = "" if rom_id is None: @@ -302,7 +307,9 @@ async def start_chunked_upload( rom = _get_upload_rom(request, rom_id, platform_id) try: rel_folder = parse_upload_folder(target.folder if target else "") - resolve_upload_destination(rom, rel_folder, safe_filename) + resolve_upload_destination( + rom, rel_folder, safe_filename, overwrite=overwrite + ) except UploadRejectedException as exc: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc) @@ -326,6 +333,7 @@ async def start_chunked_upload( "user_id": request.user.id, "rom_id": rom_id, "folder": rel_folder, + "overwrite": overwrite, } await _save_session(upload_id, session) @@ -503,7 +511,7 @@ async def complete_chunked_upload( destination = await _resolve_destination(request, session) staged = staging_path(destination.location) await _assemble_chunks(upload_id, session, staged) - await _commit(destination, staged, overwrite=False) + await _commit(destination, staged, overwrite=session["overwrite"]) finally: await _cleanup_upload_state(upload_id) diff --git a/backend/tests/endpoints/roms/test_upload.py b/backend/tests/endpoints/roms/test_upload.py index ec7bd3dda..10a41f54a 100644 --- a/backend/tests/endpoints/roms/test_upload.py +++ b/backend/tests/endpoints/roms/test_upload.py @@ -365,10 +365,13 @@ def _start_into_rom( folder: str | None, total_size: int, platform_id: int | None = None, + overwrite: bool = False, ): - target: dict[str, int | str] = {"rom_id": rom.id} + target: dict[str, int | str | bool] = {"rom_id": rom.id} if folder is not None: target["folder"] = folder + if overwrite: + target["overwrite"] = True return client.post( "/api/roms/upload/start", headers={ @@ -390,9 +393,16 @@ def _upload_into_rom( filename: str, folder: str | None, data: bytes, + overwrite: bool = False, ): start = _start_into_rom( - client, token, rom, filename=filename, folder=folder, total_size=len(data) + client, + token, + rom, + filename=filename, + folder=folder, + total_size=len(data), + overwrite=overwrite, ) assert start.status_code == status.HTTP_201_CREATED, start.json() upload_id = start.json()["upload_id"] @@ -524,6 +534,40 @@ def test_start_into_rom_rejects_existing_destination( assert response.status_code == status.HTTP_409_CONFLICT +def test_overwrite_replaces_an_existing_file( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + rom = _folder_rom( + platform, admin_user, rom_upload_fs, {"game.bin": b"game", "hack/x.ips": b"old"} + ) + + refused = _start_into_rom( + client, access_token, rom, filename="x.ips", folder="hack", total_size=3 + ) + assert refused.status_code == status.HTTP_409_CONFLICT + + response = _upload_into_rom( + client, + access_token, + rom, + filename="x.ips", + folder="hack", + data=b"new", + overwrite=True, + ) + + assert response.status_code == status.HTTP_201_CREATED, response.json() + on_disk = rom_upload_fs / rom.fs_path / ROM_FOLDER / "hack" / "x.ips" + assert on_disk.read_bytes() == b"new" + rows = [f for f in db_rom_handler.get_rom(rom.id).files if f.file_name == "x.ips"] + assert len(rows) == 1 + assert rows[0].file_size_bytes == 3 + + def test_complete_registers_nested_file( client: TestClient, access_token: str, diff --git a/frontend/src/__generated__/models/UploadTargetPayload.ts b/frontend/src/__generated__/models/UploadTargetPayload.ts index d579bdf27..a4b24158f 100644 --- a/frontend/src/__generated__/models/UploadTargetPayload.ts +++ b/frontend/src/__generated__/models/UploadTargetPayload.ts @@ -19,5 +19,9 @@ export type UploadTargetPayload = { * The file name. Takes precedence over the header, which cannot carry characters outside Latin-1. */ filename?: (string | null); + /** + * Replace a file of the same name in the ROM's folder instead of refusing the upload. + */ + overwrite?: boolean; }; diff --git a/frontend/src/locales/bg_BG/common.json b/frontend/src/locales/bg_BG/common.json index 38045fe4f..2b3797aa9 100644 --- a/frontend/src/locales/bg_BG/common.json +++ b/frontend/src/locales/bg_BG/common.json @@ -100,6 +100,7 @@ "not-linked": "Не е свързано", "offline": "Офлайн", "online": "Онлайн", + "overwrite": "Презапиши", "owned": "Притежавани", "page": "Страница", "password-length": "Паролата трябва да е между 6 и 255 символа", diff --git a/frontend/src/locales/bg_BG/rom.json b/frontend/src/locales/bg_BG/rom.json index 855b868fe..4d5fba7ba 100644 --- a/frontend/src/locales/bg_BG/rom.json +++ b/frontend/src/locales/bg_BG/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Нова папка…", "upload-new-folder-hint": "Спрямо папката на играта, напр. hack/v2", + "upload-overwrite-body": "{names} вече съществува в тази папка и ще бъде заменен от новото качване. | {names} вече съществуват в тази папка и ще бъдат заменени от новите качвания.", + "upload-overwrite-title": "Презаписване на {n} съществуващ файл? | Презаписване на {n} съществуващи файла?", "upload-saves": "Качи записи", "upload-screenshots": "Качи екранни снимки", "upload-slot-hint": "Записите в слот се синхронизират с устройствата; без слот файлът остава ръчен архив.", diff --git a/frontend/src/locales/cs_CZ/common.json b/frontend/src/locales/cs_CZ/common.json index c5a9c5179..c5ec0b811 100644 --- a/frontend/src/locales/cs_CZ/common.json +++ b/frontend/src/locales/cs_CZ/common.json @@ -100,6 +100,7 @@ "not-linked": "Nepropojeno", "offline": "Offline", "online": "Online", + "overwrite": "Přepsat", "owned": "Vlastněno", "page": "Stránka", "password-length": "Heslo musí mít 6 až 255 znaků", diff --git a/frontend/src/locales/cs_CZ/rom.json b/frontend/src/locales/cs_CZ/rom.json index 55980c3d2..7ec6c40c1 100644 --- a/frontend/src/locales/cs_CZ/rom.json +++ b/frontend/src/locales/cs_CZ/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Nová složka…", "upload-new-folder-hint": "Relativně ke složce hry, např. hack/v2", + "upload-overwrite-body": "{names} v této složce již existuje a bude nahrazen novým nahráním. | {names} v této složce již existují a budou nahrazeny novými nahráními.", + "upload-overwrite-title": "Přepsat {n} existující soubor? | Přepsat {n} existující soubory?", "upload-saves": "Nahrát uložené pozice", "upload-screenshots": "Nahrát screenshoty", "upload-slot-hint": "Uložené pozice ve slotu se synchronizují se zařízeními; bez slotu zůstává soubor ručním archivem.", diff --git a/frontend/src/locales/de_DE/common.json b/frontend/src/locales/de_DE/common.json index b9440ff09..791856f4c 100644 --- a/frontend/src/locales/de_DE/common.json +++ b/frontend/src/locales/de_DE/common.json @@ -100,6 +100,7 @@ "not-linked": "Nicht verknüpft", "offline": "Offline", "online": "Online", + "overwrite": "Überschreiben", "owned": "Besitz", "page": "Seite", "password-length": "Passwort muss zwischen 6 und 255 Zeichen lang sein", diff --git a/frontend/src/locales/de_DE/rom.json b/frontend/src/locales/de_DE/rom.json index e779ccc8d..a695a2f06 100644 --- a/frontend/src/locales/de_DE/rom.json +++ b/frontend/src/locales/de_DE/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Neuer Ordner…", "upload-new-folder-hint": "Relativ zum Spielordner, z. B. hack/v2", + "upload-overwrite-body": "{names} existiert bereits in diesem Ordner und wird durch den neuen Upload ersetzt. | {names} existieren bereits in diesem Ordner und werden durch die neuen Uploads ersetzt.", + "upload-overwrite-title": "{n} vorhandene Datei überschreiben? | {n} vorhandene Dateien überschreiben?", "upload-saves": "Spielstände hochladen", "upload-screenshots": "Screenshots hochladen", "upload-slot-hint": "Spielstände in einem Slot nehmen an der Gerätesynchronisierung teil; ohne Slot bleibt die Datei ein manuelles Archiv.", diff --git a/frontend/src/locales/en_GB/common.json b/frontend/src/locales/en_GB/common.json index 182d59172..a5bfc1bd9 100644 --- a/frontend/src/locales/en_GB/common.json +++ b/frontend/src/locales/en_GB/common.json @@ -100,6 +100,7 @@ "not-linked": "Not linked", "offline": "Offline", "online": "Online", + "overwrite": "Overwrite", "owned": "Owned", "page": "Page", "password-length": "Password must be between 6 and 255 characters", diff --git a/frontend/src/locales/en_GB/rom.json b/frontend/src/locales/en_GB/rom.json index 58cd83e93..e18833362 100644 --- a/frontend/src/locales/en_GB/rom.json +++ b/frontend/src/locales/en_GB/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "New folder…", "upload-new-folder-hint": "Relative to the game folder, e.g. hack/v2", + "upload-overwrite-body": "{names} already exists in this folder and will be replaced by the new upload. | {names} already exist in this folder and will be replaced by the new uploads.", + "upload-overwrite-title": "Overwrite {n} existing file? | Overwrite {n} existing files?", "upload-saves": "Upload saves", "upload-screenshots": "Upload screenshots", "upload-slot-hint": "Slotted saves join device sync; without a slot the file stays a manual archive.", diff --git a/frontend/src/locales/en_US/common.json b/frontend/src/locales/en_US/common.json index 182d59172..a5bfc1bd9 100644 --- a/frontend/src/locales/en_US/common.json +++ b/frontend/src/locales/en_US/common.json @@ -100,6 +100,7 @@ "not-linked": "Not linked", "offline": "Offline", "online": "Online", + "overwrite": "Overwrite", "owned": "Owned", "page": "Page", "password-length": "Password must be between 6 and 255 characters", diff --git a/frontend/src/locales/en_US/rom.json b/frontend/src/locales/en_US/rom.json index 82bf9280d..8c49a65a9 100644 --- a/frontend/src/locales/en_US/rom.json +++ b/frontend/src/locales/en_US/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "New folder…", "upload-new-folder-hint": "Relative to the game folder, e.g. hack/v2", + "upload-overwrite-body": "{names} already exists in this folder and will be replaced by the new upload. | {names} already exist in this folder and will be replaced by the new uploads.", + "upload-overwrite-title": "Overwrite {n} existing file? | Overwrite {n} existing files?", "upload-saves": "Upload saves", "upload-screenshots": "Upload screenshots", "upload-slot-hint": "Slotted saves join device sync; without a slot the file stays a manual archive.", diff --git a/frontend/src/locales/es_ES/common.json b/frontend/src/locales/es_ES/common.json index 2f3e8c7ce..ce0fa4ed8 100644 --- a/frontend/src/locales/es_ES/common.json +++ b/frontend/src/locales/es_ES/common.json @@ -100,6 +100,7 @@ "not-linked": "Sin vincular", "offline": "Sin conexión", "online": "En línea", + "overwrite": "Sobrescribir", "owned": "En propiedad", "page": "Página", "password-length": "La contraseña debe tener entre 6 y 255 caracteres", diff --git a/frontend/src/locales/es_ES/rom.json b/frontend/src/locales/es_ES/rom.json index 61983d9f9..f5b9e8ef0 100644 --- a/frontend/src/locales/es_ES/rom.json +++ b/frontend/src/locales/es_ES/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Nueva carpeta…", "upload-new-folder-hint": "Relativa a la carpeta del juego, p. ej. hack/v2", + "upload-overwrite-body": "{names} ya existe en esta carpeta y se reemplazará con la nueva subida. | {names} ya existen en esta carpeta y se reemplazarán con las nuevas subidas.", + "upload-overwrite-title": "¿Sobrescribir {n} archivo existente? | ¿Sobrescribir {n} archivos existentes?", "upload-saves": "Subir partidas", "upload-screenshots": "Subir capturas", "upload-slot-hint": "Las partidas con ranura entran en la sincronización de dispositivos; sin ranura el archivo queda como copia manual.", diff --git a/frontend/src/locales/fr_FR/common.json b/frontend/src/locales/fr_FR/common.json index c6843a9c4..ebc316d6f 100644 --- a/frontend/src/locales/fr_FR/common.json +++ b/frontend/src/locales/fr_FR/common.json @@ -100,6 +100,7 @@ "not-linked": "Non associé", "offline": "Hors ligne", "online": "En ligne", + "overwrite": "Écraser", "owned": "Possédé", "page": "Page", "password-length": "Le mot de passe doit contenir entre 6 et 255 caractères", diff --git a/frontend/src/locales/fr_FR/rom.json b/frontend/src/locales/fr_FR/rom.json index 631532d5b..e3a9dea68 100644 --- a/frontend/src/locales/fr_FR/rom.json +++ b/frontend/src/locales/fr_FR/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Nouveau dossier…", "upload-new-folder-hint": "Relatif au dossier du jeu, par ex. hack/v2", + "upload-overwrite-body": "{names} existe déjà dans ce dossier et sera remplacé par le nouvel envoi. | {names} existent déjà dans ce dossier et seront remplacés par les nouveaux envois.", + "upload-overwrite-title": "Écraser {n} fichier existant ? | Écraser {n} fichiers existants ?", "upload-saves": "Téléverser des sauvegardes", "upload-screenshots": "Téléverser des captures d'écran", "upload-slot-hint": "Les sauvegardes dans un emplacement rejoignent la synchronisation des appareils ; sans emplacement, le fichier reste une archive manuelle.", diff --git a/frontend/src/locales/hu_HU/common.json b/frontend/src/locales/hu_HU/common.json index 1658cd48f..3eb6def12 100644 --- a/frontend/src/locales/hu_HU/common.json +++ b/frontend/src/locales/hu_HU/common.json @@ -100,6 +100,7 @@ "not-linked": "Nincs összekötve", "offline": "Offline", "online": "Online", + "overwrite": "Felülírás", "owned": "Tulajdonolt", "page": "Oldal", "password-length": "A jelszó hossza 6 és 255 karakter hosszú lehet", diff --git a/frontend/src/locales/hu_HU/rom.json b/frontend/src/locales/hu_HU/rom.json index 92f72adf1..41ca20502 100644 --- a/frontend/src/locales/hu_HU/rom.json +++ b/frontend/src/locales/hu_HU/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Új mappa…", "upload-new-folder-hint": "A játék mappájához képest, pl. hack/v2", + "upload-overwrite-body": "{names} már létezik ebben a mappában, és az új feltöltés felülírja. | {names} már léteznek ebben a mappában, és az új feltöltések felülírják.", + "upload-overwrite-title": "Felülírja a(z) {n} meglévő fájlt? | Felülírja a(z) {n} meglévő fájlt?", "upload-saves": "Mentések feltöltése", "upload-screenshots": "Képernyőképek feltöltése", "upload-slot-hint": "A helyre tett mentések részt vesznek az eszközszinkronban; hely nélkül a fájl kézi archívum marad.", diff --git a/frontend/src/locales/it_IT/common.json b/frontend/src/locales/it_IT/common.json index 02ae92876..d200eec8c 100644 --- a/frontend/src/locales/it_IT/common.json +++ b/frontend/src/locales/it_IT/common.json @@ -100,6 +100,7 @@ "not-linked": "Non collegato", "offline": "Offline", "online": "Online", + "overwrite": "Sovrascrivi", "owned": "Posseduti", "page": "Pagina", "password-length": "La password deve essere compresa tra 6 e 255 caratteri", diff --git a/frontend/src/locales/it_IT/rom.json b/frontend/src/locales/it_IT/rom.json index 3e556fc6b..6f77c6e1e 100644 --- a/frontend/src/locales/it_IT/rom.json +++ b/frontend/src/locales/it_IT/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Nuova cartella…", "upload-new-folder-hint": "Relativo alla cartella del gioco, es. hack/v2", + "upload-overwrite-body": "{names} esiste già in questa cartella e verrà sostituito dal nuovo caricamento. | {names} esistono già in questa cartella e verranno sostituiti dai nuovi caricamenti.", + "upload-overwrite-title": "Sovrascrivere {n} file esistente? | Sovrascrivere {n} file esistenti?", "upload-saves": "Carica salvataggi", "upload-screenshots": "Carica screenshot", "upload-slot-hint": "I salvataggi in uno slot entrano nella sincronizzazione dei dispositivi; senza slot il file resta un archivio manuale.", diff --git a/frontend/src/locales/ja_JP/common.json b/frontend/src/locales/ja_JP/common.json index c7248684c..d1b2a925e 100644 --- a/frontend/src/locales/ja_JP/common.json +++ b/frontend/src/locales/ja_JP/common.json @@ -100,6 +100,7 @@ "not-linked": "未連携", "offline": "オフライン", "online": "オンライン", + "overwrite": "上書き", "owned": "所有", "page": "ページ", "password-length": "パスワードは6文字から255文字の間である必要があります", diff --git a/frontend/src/locales/ja_JP/rom.json b/frontend/src/locales/ja_JP/rom.json index 8363bc99e..bb520ecfd 100644 --- a/frontend/src/locales/ja_JP/rom.json +++ b/frontend/src/locales/ja_JP/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "新しいフォルダ…", "upload-new-folder-hint": "ゲームフォルダからの相対パス (例: hack/v2)", + "upload-overwrite-body": "{names} はこのフォルダにすでに存在し、新しいアップロードで置き換えられます。 | {names} はこのフォルダにすでに存在し、新しいアップロードで置き換えられます。", + "upload-overwrite-title": "既存の {n} 件のファイルを上書きしますか? | 既存の {n} 件のファイルを上書きしますか?", "upload-saves": "セーブをアップロード", "upload-screenshots": "スクリーンショットをアップロード", "upload-slot-hint": "スロット付きのセーブは端末間で同期されます。スロットなしのファイルは手動のアーカイブとして保持されます。", diff --git a/frontend/src/locales/ko_KR/common.json b/frontend/src/locales/ko_KR/common.json index 4b1f6dab5..9d337814f 100644 --- a/frontend/src/locales/ko_KR/common.json +++ b/frontend/src/locales/ko_KR/common.json @@ -100,6 +100,7 @@ "not-linked": "연결되지 않음", "offline": "오프라인", "online": "온라인", + "overwrite": "덮어쓰기", "owned": "보유 중", "page": "페이지", "password-length": "비밀번호는 6자에서 255자 사이여야 합니다", diff --git a/frontend/src/locales/ko_KR/rom.json b/frontend/src/locales/ko_KR/rom.json index 355ce0f10..e060b2245 100644 --- a/frontend/src/locales/ko_KR/rom.json +++ b/frontend/src/locales/ko_KR/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "새 폴더…", "upload-new-folder-hint": "게임 폴더 기준 상대 경로, 예: hack/v2", + "upload-overwrite-body": "{names}은(는) 이 폴더에 이미 존재하며 새 업로드로 대체됩니다. | {names}은(는) 이 폴더에 이미 존재하며 새 업로드로 대체됩니다.", + "upload-overwrite-title": "기존 파일 {n}개를 덮어쓸까요? | 기존 파일 {n}개를 덮어쓸까요?", "upload-saves": "세이브 업로드", "upload-screenshots": "스크린샷 업로드", "upload-slot-hint": "슬롯이 있는 세이브는 기기 동기화에 포함됩니다. 슬롯이 없으면 파일은 수동 보관본으로 남습니다.", diff --git a/frontend/src/locales/pl_PL/common.json b/frontend/src/locales/pl_PL/common.json index 82e2560a5..79cc045d0 100644 --- a/frontend/src/locales/pl_PL/common.json +++ b/frontend/src/locales/pl_PL/common.json @@ -100,6 +100,7 @@ "not-linked": "Niepowiązane", "offline": "Offline", "online": "Online", + "overwrite": "Nadpisz", "owned": "Posiadane", "page": "Strona", "password-length": "Hasło musi mieć od 6 do 255 znaków", diff --git a/frontend/src/locales/pl_PL/rom.json b/frontend/src/locales/pl_PL/rom.json index a3bc4ff00..36709b802 100644 --- a/frontend/src/locales/pl_PL/rom.json +++ b/frontend/src/locales/pl_PL/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Nowy folder…", "upload-new-folder-hint": "Względem folderu gry, np. hack/v2", + "upload-overwrite-body": "{names} już istnieje w tym folderze i zostanie zastąpiony nowym plikiem. | {names} już istnieją w tym folderze i zostaną zastąpione nowymi plikami.", + "upload-overwrite-title": "Nadpisać {n} istniejący plik? | Nadpisać {n} istniejące pliki?", "upload-saves": "Prześlij zapisy", "upload-screenshots": "Prześlij zrzuty ekranu", "upload-slot-hint": "Zapisy w slocie biorą udział w synchronizacji urządzeń; bez slotu plik pozostaje ręcznym archiwum.", diff --git a/frontend/src/locales/pt_BR/common.json b/frontend/src/locales/pt_BR/common.json index 79edf22bf..f4e940bc2 100644 --- a/frontend/src/locales/pt_BR/common.json +++ b/frontend/src/locales/pt_BR/common.json @@ -100,6 +100,7 @@ "not-linked": "Não vinculado", "offline": "Offline", "online": "Online", + "overwrite": "Sobrescrever", "owned": "Possuído", "page": "Página", "password-length": "Senha deve ter entre 6 e 255 caracteres", diff --git a/frontend/src/locales/pt_BR/rom.json b/frontend/src/locales/pt_BR/rom.json index 45460b746..d695fe14d 100644 --- a/frontend/src/locales/pt_BR/rom.json +++ b/frontend/src/locales/pt_BR/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Enviar manual", "upload-new-folder": "Nova pasta…", "upload-new-folder-hint": "Relativo à pasta do jogo, ex.: hack/v2", + "upload-overwrite-body": "{names} já existe nesta pasta e será substituído pelo novo envio. | {names} já existem nesta pasta e serão substituídos pelos novos envios.", + "upload-overwrite-title": "Sobrescrever {n} arquivo existente? | Sobrescrever {n} arquivos existentes?", "upload-saves": "Enviar saves", "upload-screenshots": "Enviar capturas de tela", "upload-slot-hint": "Saves em um slot entram na sincronização de dispositivos; sem slot o arquivo fica como cópia manual.", diff --git a/frontend/src/locales/ro_RO/common.json b/frontend/src/locales/ro_RO/common.json index 108ff7ecd..eb1b5435e 100644 --- a/frontend/src/locales/ro_RO/common.json +++ b/frontend/src/locales/ro_RO/common.json @@ -100,6 +100,7 @@ "not-linked": "Neasociat", "offline": "Offline", "online": "Online", + "overwrite": "Suprascrie", "owned": "Deținut", "page": "Pagină", "password-length": "Parola trebuie să conțină între 6 și 255 de caractere", diff --git a/frontend/src/locales/ro_RO/rom.json b/frontend/src/locales/ro_RO/rom.json index 8f9d0c770..305fe9ac3 100644 --- a/frontend/src/locales/ro_RO/rom.json +++ b/frontend/src/locales/ro_RO/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Folder nou…", "upload-new-folder-hint": "Relativ la folderul jocului, de ex. hack/v2", + "upload-overwrite-body": "{names} există deja în acest folder și va fi înlocuit de noua încărcare. | {names} există deja în acest folder și vor fi înlocuite de noile încărcări.", + "upload-overwrite-title": "Suprascrii {n} fișier existent? | Suprascrii {n} fișiere existente?", "upload-saves": "Încarcă salvări", "upload-screenshots": "Încarcă capturi de ecran", "upload-slot-hint": "Salvările dintr-un slot intră în sincronizarea dispozitivelor; fără slot fișierul rămâne o arhivă manuală.", diff --git a/frontend/src/locales/ru_RU/common.json b/frontend/src/locales/ru_RU/common.json index fffa8623d..e9625bb78 100644 --- a/frontend/src/locales/ru_RU/common.json +++ b/frontend/src/locales/ru_RU/common.json @@ -100,6 +100,7 @@ "not-linked": "Не привязано", "offline": "Не в сети", "online": "В сети", + "overwrite": "Перезаписать", "owned": "В наличии", "page": "Страница", "password-length": "Пароль должен содержать от 6 до 255 символов", diff --git a/frontend/src/locales/ru_RU/rom.json b/frontend/src/locales/ru_RU/rom.json index 1f828fb48..43c61c191 100644 --- a/frontend/src/locales/ru_RU/rom.json +++ b/frontend/src/locales/ru_RU/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "Новая папка…", "upload-new-folder-hint": "Относительно папки игры, например hack/v2", + "upload-overwrite-body": "{names} уже существует в этой папке и будет заменён новой загрузкой. | {names} уже существуют в этой папке и будут заменены новыми загрузками.", + "upload-overwrite-title": "Перезаписать {n} существующий файл? | Перезаписать {n} существующих файлов?", "upload-saves": "Загрузить сохранения", "upload-screenshots": "Загрузить скриншоты", "upload-slot-hint": "Сохранения в слоте участвуют в синхронизации устройств; без слота файл остаётся ручным архивом.", diff --git a/frontend/src/locales/tr_TR/common.json b/frontend/src/locales/tr_TR/common.json index a8a48e5f0..8e6f97ba9 100644 --- a/frontend/src/locales/tr_TR/common.json +++ b/frontend/src/locales/tr_TR/common.json @@ -100,6 +100,7 @@ "not-linked": "Bağlı değil", "offline": "Çevrimdışı", "online": "Çevrimiçi", + "overwrite": "Üzerine yaz", "owned": "Sahip olunan", "page": "Sayfa", "password-length": "Şifre 6 ile 255 karakter arasında olmalıdır", diff --git a/frontend/src/locales/tr_TR/rom.json b/frontend/src/locales/tr_TR/rom.json index 0689fa1e4..48c43899f 100644 --- a/frontend/src/locales/tr_TR/rom.json +++ b/frontend/src/locales/tr_TR/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Kılavuz yükle", "upload-new-folder": "Yeni klasör…", "upload-new-folder-hint": "Oyun klasörüne göre, örn. hack/v2", + "upload-overwrite-body": "{names} bu klasörde zaten mevcut ve yeni yüklemeyle değiştirilecek. | {names} bu klasörde zaten mevcut ve yeni yüklemelerle değiştirilecek.", + "upload-overwrite-title": "{n} mevcut dosyanın üzerine yazılsın mı? | {n} mevcut dosyanın üzerine yazılsın mı?", "upload-saves": "Kayıt yükle", "upload-screenshots": "Ekran görüntüsü yükle", "upload-slot-hint": "Yuvadaki kayıtlar cihaz eşitlemesine katılır; yuva yoksa dosya elle alınmış bir arşiv olarak kalır.", diff --git a/frontend/src/locales/zh_CN/common.json b/frontend/src/locales/zh_CN/common.json index c45621e78..cfbcefb53 100644 --- a/frontend/src/locales/zh_CN/common.json +++ b/frontend/src/locales/zh_CN/common.json @@ -100,6 +100,7 @@ "not-linked": "未关联", "offline": "离线", "online": "在线", + "overwrite": "覆盖", "owned": "已拥有", "page": "页", "password-length": "密码必须介于6到255个字符之间", diff --git a/frontend/src/locales/zh_CN/rom.json b/frontend/src/locales/zh_CN/rom.json index 16f714cfc..4881fa163 100644 --- a/frontend/src/locales/zh_CN/rom.json +++ b/frontend/src/locales/zh_CN/rom.json @@ -488,6 +488,8 @@ "upload-manual": "上传手册", "upload-new-folder": "新建文件夹…", "upload-new-folder-hint": "相对于游戏文件夹,例如 hack/v2", + "upload-overwrite-body": "{names} 已存在于此文件夹中,将被新上传的文件替换。 | {names} 已存在于此文件夹中,将被新上传的文件替换。", + "upload-overwrite-title": "覆盖 {n} 个已有文件? | 覆盖 {n} 个已有文件?", "upload-saves": "上传存档", "upload-screenshots": "上传截图", "upload-slot-hint": "带存档位的存档会参与设备同步;没有存档位的文件将作为手动存档保留。", diff --git a/frontend/src/locales/zh_TW/common.json b/frontend/src/locales/zh_TW/common.json index 489992272..37b0c53bf 100644 --- a/frontend/src/locales/zh_TW/common.json +++ b/frontend/src/locales/zh_TW/common.json @@ -100,6 +100,7 @@ "not-linked": "未連結", "offline": "離線", "online": "線上", + "overwrite": "覆蓋", "owned": "已擁有", "page": "頁面", "password-length": "密碼必須介於 6 到 255 個字元之間", diff --git a/frontend/src/locales/zh_TW/rom.json b/frontend/src/locales/zh_TW/rom.json index eb0830481..61cbad50d 100644 --- a/frontend/src/locales/zh_TW/rom.json +++ b/frontend/src/locales/zh_TW/rom.json @@ -488,6 +488,8 @@ "upload-manual": "Upload manual", "upload-new-folder": "新增資料夾…", "upload-new-folder-hint": "相對於遊戲資料夾,例如 hack/v2", + "upload-overwrite-body": "{names} 已存在於此資料夾中,將被新上傳的檔案取代。 | {names} 已存在於此資料夾中,將被新上傳的檔案取代。", + "upload-overwrite-title": "覆蓋 {n} 個現有檔案? | 覆蓋 {n} 個現有檔案?", "upload-saves": "上傳存檔", "upload-screenshots": "上傳截圖", "upload-slot-hint": "有存檔槽的存檔會參與裝置同步;沒有存檔槽的檔案將作為手動存檔保留。", diff --git a/frontend/src/services/api/rom.test.ts b/frontend/src/services/api/rom.test.ts index 06d12c375..b215c99af 100644 --- a/frontend/src/services/api/rom.test.ts +++ b/frontend/src/services/api/rom.test.ts @@ -136,6 +136,23 @@ describe("romApi.uploadRoms", () => { ); }); + it("asks the server to replace an existing file only when told to", async () => { + await romApi.uploadRoms({ + platformId: 3, + romId: 42, + folder: "hack", + overwrite: true, + filesToUpload: [new File(["abc"], "fix.ips")], + }); + + expect(startCall().body).toEqual({ + filename: "fix.ips", + rom_id: 42, + folder: "hack", + overwrite: true, + }); + }); + it("treats an empty folder as the rom root", async () => { await romApi.uploadRoms({ platformId: 3, diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index e58738890..7020d3561 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -44,6 +44,7 @@ async function uploadRomChunked({ file, romId, folder, + overwrite = false, }: { platformId: number; file: File; @@ -51,6 +52,8 @@ async function uploadRomChunked({ romId?: number; /** Subfolder inside the ROM folder; empty or omitted for the root. */ folder?: string; + /** Replace a file of the same name in the ROM folder. */ + overwrite?: boolean; }): Promise { const uploadStore = storeUpload(); const totalChunks = Math.ceil(file.size / UPLOAD_CHUNK_SIZE); @@ -59,7 +62,11 @@ async function uploadRomChunked({ // percent-encoded name and the body the real one. const target: UploadTargetPayload = { filename: file.name, - ...(romId !== undefined && { rom_id: romId, ...(folder && { folder }) }), + ...(romId !== undefined && { + rom_id: romId, + ...(folder && { folder }), + ...(overwrite && { overwrite }), + }), }; const { data: startData } = await api.post("/roms/upload/start", target, { headers: { @@ -133,11 +140,13 @@ async function uploadRoms({ filesToUpload, romId, folder, + overwrite, }: { platformId: number; filesToUpload: File[]; romId?: number; folder?: string; + overwrite?: boolean; }) { if (!socket.connected) socket.connect(); const uploadStore = storeUpload(); @@ -145,7 +154,7 @@ async function uploadRoms({ const promises = filesToUpload.map((file) => { uploadStore.start(file.name); - return uploadRomChunked({ platformId, file, romId, folder }) + return uploadRomChunked({ platformId, file, romId, folder, overwrite }) .then(() => null as null) .catch((error) => { uploadStore.fail( diff --git a/frontend/src/v2/composables/useRomFileUpload/index.test.ts b/frontend/src/v2/composables/useRomFileUpload/index.test.ts index 1272dc185..7a8dfa59c 100644 --- a/frontend/src/v2/composables/useRomFileUpload/index.test.ts +++ b/frontend/src/v2/composables/useRomFileUpload/index.test.ts @@ -34,6 +34,7 @@ vi.mock("@/v2/composables/useSnackbar", () => ({ const folderRom = { id: 1, platform_id: 7, has_simple_single_file: false }; const singleFileRom = { ...folderRom, has_simple_single_file: true }; const files = [new File(["x"], "track.mp3")]; +const exists = { isAxiosError: true, response: { status: 409 } }; describe("useRomFileUpload", () => { beforeEach(() => { @@ -80,11 +81,52 @@ describe("useRomFileUpload", () => { expect(uploadRoms).not.toHaveBeenCalled(); }); - it("explains a duplicate and keeps the failed entry in the upload toast", async () => { + it("asks before replacing an existing file and retries with overwrite", async () => { + const both = [new File(["x"], "track.mp3"), new File(["y"], "b.mp3")]; + uploadRoms + .mockResolvedValueOnce([ + { status: "fulfilled", value: null }, + { status: "rejected", reason: exists }, + ]) + .mockResolvedValueOnce([{ status: "fulfilled", value: null }]); + const { uploadFiles } = useRomFileUpload(); + + const outcome = await uploadFiles(folderRom, "soundtrack", both); + + expect(outcome).toEqual({ uploaded: 2, failed: 0 }); + expect(confirmFn).toHaveBeenCalledWith( + expect.objectContaining({ + title: "rom.upload-overwrite-title", + confirmText: "common.overwrite", + tone: "danger", + }), + ); + expect(uploadRoms).toHaveBeenLastCalledWith( + expect.objectContaining({ filesToUpload: [both[1]], overwrite: true }), + ); + expect(snackbar.error).not.toHaveBeenCalled(); + expect(refetchRom).toHaveBeenCalledWith(1); + }); + + it("drops a file the user declines to overwrite without complaint", async () => { + uploadRoms.mockResolvedValue([{ status: "rejected", reason: exists }]); + confirmFn.mockResolvedValue(false); + const { uploadFiles } = useRomFileUpload(); + + const outcome = await uploadFiles(folderRom, "soundtrack", files); + + expect(outcome).toEqual({ uploaded: 0, failed: 0 }); + expect(uploadRoms).toHaveBeenCalledOnce(); + expect(snackbar.error).not.toHaveBeenCalled(); + expect(snackbar.warning).not.toHaveBeenCalled(); + expect(refetchRom).not.toHaveBeenCalled(); + }); + + it("explains a rejected file and keeps the failed entry in the upload toast", async () => { uploadRoms.mockResolvedValue([ { status: "rejected", - reason: { isAxiosError: true, response: { status: 409 } }, + reason: { isAxiosError: true, response: { status: 400 } }, }, ]); const uploadStore = storeUpload(); @@ -94,7 +136,7 @@ describe("useRomFileUpload", () => { const outcome = await uploadFiles(folderRom, "soundtrack", files); expect(outcome).toEqual({ uploaded: 0, failed: 1 }); - expect(snackbar.error).toHaveBeenCalledWith("rom.upload-file-exists"); + expect(snackbar.error).toHaveBeenCalledWith("rom.upload-file-rejected"); expect(snackbar.warning).toHaveBeenCalledWith( "rom.no-files-uploaded", expect.anything(), @@ -106,7 +148,10 @@ describe("useRomFileUpload", () => { it("tracks in-flight uploads", async () => { let release: (() => void) | undefined; uploadRoms.mockImplementationOnce( - () => new Promise((resolve) => (release = () => resolve([]))), + () => + new Promise((resolve) => { + release = () => resolve([{ status: "fulfilled", value: null }]); + }), ); const { uploading, uploadFiles } = useRomFileUpload(); diff --git a/frontend/src/v2/composables/useRomFileUpload/index.ts b/frontend/src/v2/composables/useRomFileUpload/index.ts index fe8dd5178..3813a2222 100644 --- a/frontend/src/v2/composables/useRomFileUpload/index.ts +++ b/frontend/src/v2/composables/useRomFileUpload/index.ts @@ -2,8 +2,9 @@ // // The Files tab targets any subfolder and the Media subtabs target the folder // the scanner maps to their category, but the upload itself is the same: -// confirm the single-file promotion, stream through the chunked upload, -// report the outcome and refetch the ROM. +// confirm the single-file promotion, stream through the chunked upload, ask +// before replacing a file the folder already holds, report the outcome and +// refetch the ROM. import axios from "axios"; import { computed, ref } from "vue"; import { useI18n } from "vue-i18n"; @@ -37,6 +38,17 @@ export interface RomFileUploadOutcome { const NOTHING_UPLOADED: RomFileUploadOutcome = { uploaded: 0, failed: 0 }; +type Attempt = { file: File; result: PromiseSettledResult }; + +/** The server refuses a name the folder already holds with a 409. */ +function isExisting({ result }: Attempt): boolean { + return ( + result.status === "rejected" && + axios.isAxiosError(result.reason) && + result.reason.response?.status === 409 + ); +} + export function useRomFileUpload() { const { t } = useI18n(); const snackbar = useSnackbar(); @@ -77,12 +89,47 @@ export function useRomFileUpload() { inFlight.value += 1; try { - const results = await romApi.uploadRoms({ - platformId: rom.platform_id, - romId: rom.id, - folder, - filesToUpload: files, - }); + const send = async (batch: File[], overwrite = false) => { + const results = await romApi.uploadRoms({ + platformId: rom.platform_id, + romId: rom.id, + folder, + filesToUpload: batch, + ...(overwrite && { overwrite }), + }); + return batch.map((file, i) => ({ file, result: results[i] })); + }; + + let attempts = await send(files); + const existing = attempts.filter(isExisting); + if (existing.length > 0) { + attempts = attempts.filter((attempt) => !isExisting(attempt)); + const names = existing.map(({ file }) => file.name).join(", "); + const ok = await confirm({ + title: t("rom.upload-overwrite-title", existing.length, { + named: { n: existing.length }, + }), + body: t("rom.upload-overwrite-body", existing.length, { + named: { names }, + }), + confirmText: t("common.overwrite"), + tone: "danger", + }); + if (ok) { + // The refused entries are still in the toast; the retry re-adds them. + uploadStore.clearFinished(); + attempts = [ + ...attempts, + ...(await send( + existing.map(({ file }) => file), + true, + )), + ]; + } + } + if (attempts.length === 0) return NOTHING_UPLOADED; + + const results = attempts.map(({ result }) => result); const uploaded = results.filter((r) => r.status === "fulfilled").length; const failed = results.length - uploaded; if (uploaded > 0) { @@ -99,13 +146,12 @@ export function useRomFileUpload() { icon: "mdi-close-circle", }); } - // allSettled keeps the input order, so the index maps back to the file. - const firstFailed = results.findIndex((r) => r.status === "rejected"); - if (firstFailed >= 0) { - const rejected = results[firstFailed] as PromiseRejectedResult; - snackbar.error( - failureMessage(files[firstFailed].name, rejected.reason), - ); + const firstFailed = attempts.find( + ({ result }) => result.status === "rejected", + ); + if (firstFailed) { + const rejected = firstFailed.result as PromiseRejectedResult; + snackbar.error(failureMessage(firstFailed.file.name, rejected.reason)); } if (failed === 0) uploadStore.reset(); if (alive.value && uploaded > 0) await refetchRom(rom.id); From be81b1c89b9a9e7ee67da17111380eee4fc3f564 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 16:16:00 +0200 Subject: [PATCH 11/28] refactor(tasks): apply the simplify pass `has_live_worker` asks RQ for the worker count and the suspension flag, two constant-cost reads, instead of hydrating every registered worker. The cleanup stats serialize through `dataclasses.asdict`, so a new counter is declared in two places rather than three. The task endpoint test takes the shared task fixture, the legacy-stats shim says when it can go, and the two Settings specs share one axios-error helper under `src/test-utils` while the games spec starts from a non-empty list. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01F9ta8rXUTP9aMdatPYKX4K --- backend/endpoints/tasks.py | 4 ++- backend/handler/redis_handler.py | 16 ++-------- .../tasks/manual/cleanup_missing_firmware.py | 10 ++---- backend/tasks/manual/cleanup_missing_roms.py | 11 ++----- backend/tests/endpoints/test_tasks.py | 27 ++++------------ backend/tests/handler/test_redis_handler.py | 31 +++++-------------- frontend/src/test-utils/serverError.ts | 8 +++++ .../Settings/MissingFirmwareSection.test.ts | 8 +---- .../Settings/MissingGamesSection.test.ts | 14 ++------- 9 files changed, 37 insertions(+), 92 deletions(-) create mode 100644 frontend/src/test-utils/serverError.ts diff --git a/backend/endpoints/tasks.py b/backend/endpoints/tasks.py index 133558924..898a944bb 100644 --- a/backend/endpoints/tasks.py +++ b/backend/endpoints/tasks.py @@ -90,7 +90,9 @@ def _fill_scan_stats(stats: Mapping[str, Any] | None) -> ScanStats | None: def _fill_cleanup_stats(stats: Mapping[str, Any] | None) -> CleanupStats | None: - """Widen the single platform an older release's stored stats named.""" + """Widen the single platform a 5.2.0 job's stored stats named.""" + # Job meta lives for TASK_RESULT_TTL, so this only ever meets jobs that + # finished just before an upgrade. if stats is None or "platform_id" not in stats: return cast(CleanupStats | None, stats) diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index 66898a730..2ef409dfe 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -8,7 +8,7 @@ from redis.asyncio import Redis as AsyncRedis from rq import Queue, Worker from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobError from rq.job import Job, JobStatus -from rq.worker import WorkerStatus +from rq.suspension import is_suspended from config import IS_PYTEST_RUN, REDIS_URL from logger.logger import log @@ -165,17 +165,7 @@ def get_worker_current_job(worker: Worker) -> Job | None: def has_live_worker(queue: Queue) -> bool: - """Whether a worker registered on ``queue`` is alive and not suspended. - - Args: - queue: The RQ Queue whose worker set to read - - Returns: - Whether a job enqueued on it would be picked up - """ + """Whether a job enqueued on ``queue`` would be picked up.""" # A crashed worker stays registered until its key TTL lapses, so this can # still say yes for a few minutes after a kill. - return any( - worker.get_state() != WorkerStatus.SUSPENDED - for worker in Worker.all(queue=queue) - ) + return Worker.count(queue=queue) > 0 and not is_suspended(redis_client) diff --git a/backend/tasks/manual/cleanup_missing_firmware.py b/backend/tasks/manual/cleanup_missing_firmware.py index 3d869833c..7d3aaa677 100644 --- a/backend/tasks/manual/cleanup_missing_firmware.py +++ b/backend/tasks/manual/cleanup_missing_firmware.py @@ -1,4 +1,5 @@ -from dataclasses import dataclass +from dataclasses import asdict, dataclass +from typing import cast from endpoints.responses import MissingFirmwareCleanupStats from handler.database import db_firmware_handler @@ -24,12 +25,7 @@ class CleanupMissingFirmwareStats: update_job_meta({"cleanup_stats": self.to_dict()}) def to_dict(self) -> MissingFirmwareCleanupStats: - return MissingFirmwareCleanupStats( - platform_ids=self.platform_ids, - firmware_found=self.firmware_found, - firmware_deleted=self.firmware_deleted, - errors=self.errors, - ) + return cast(MissingFirmwareCleanupStats, asdict(self)) class CleanupMissingFirmwareTask(Task): diff --git a/backend/tasks/manual/cleanup_missing_roms.py b/backend/tasks/manual/cleanup_missing_roms.py index 525d560fd..7dabc7b29 100644 --- a/backend/tasks/manual/cleanup_missing_roms.py +++ b/backend/tasks/manual/cleanup_missing_roms.py @@ -1,5 +1,5 @@ -from dataclasses import dataclass -from typing import Any +from dataclasses import asdict, dataclass +from typing import Any, cast from endpoints.responses import MissingRomsCleanupStats from handler.database import db_rom_handler @@ -26,12 +26,7 @@ class CleanupMissingRomsStats: update_job_meta({"cleanup_stats": self.to_dict()}) def to_dict(self) -> MissingRomsCleanupStats: - return MissingRomsCleanupStats( - platform_ids=self.platform_ids, - roms_found=self.roms_found, - roms_deleted=self.roms_deleted, - errors=self.errors, - ) + return cast(MissingRomsCleanupStats, asdict(self)) class CleanupMissingRomsTask(Task): diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index 416b002c2..6b9fc90ba 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -244,30 +244,15 @@ class TestRunSingleTask: yield mocked @patch("endpoints.tasks.enqueue_task", return_value=create_mock_job()) - @patch( - "endpoints.tasks.RUNNABLE_TASKS", - { - "test_task": Mock( - spec=Task, - task_type=TaskType.CLEANUP, - title="Test Task", - description="Test Description", - enabled=True, - manual_run=True, - can_run_manually=True, - timeout=300, - run=Mock(), - ), - }, - ) def test_run_single_task_success( - self, mock_enqueue, client, access_token, task_worker_listening + self, mock_enqueue, client, access_token, mock_task, task_worker_listening ): """Test successful running of a single task""" - response = client.post( - "/api/tasks/run/test_task", - headers={"Authorization": f"Bearer {access_token}"}, - ) + with patch("endpoints.tasks.RUNNABLE_TASKS", {"test_task": mock_task}): + response = client.post( + "/api/tasks/run/test_task", + headers={"Authorization": f"Bearer {access_token}"}, + ) assert response.status_code == status.HTTP_200_OK data = response.json() diff --git a/backend/tests/handler/test_redis_handler.py b/backend/tests/handler/test_redis_handler.py index 3912f7984..a08f3ef70 100644 --- a/backend/tests/handler/test_redis_handler.py +++ b/backend/tests/handler/test_redis_handler.py @@ -118,30 +118,15 @@ class TestGetWorkerCurrentJob: class TestHasLiveWorker: - @staticmethod - def _worker(state: str) -> MagicMock: - worker = MagicMock(spec=Worker) - worker.get_state.return_value = state - return worker - @pytest.mark.parametrize( - ("states", "expected"), - [ - ([], False), - (["suspended"], False), - (["suspended", "idle"], True), - (["busy"], True), - ], - ids=["none-registered", "suspended", "one-live", "busy"], + ("registered", "suspended", "expected"), + [(0, False, False), (1, True, False), (1, False, True), (2, False, True)], ) - def test_counts_only_workers_that_would_take_a_job( - self, states: list[str], expected: bool + def test_needs_a_registered_worker_that_is_not_suspended( + self, registered: int, suspended: bool, expected: bool ): - workers = [self._worker(state) for state in states] - - with patch( - "handler.redis_handler.Worker.all", return_value=workers - ) as mock_all: + with ( + patch("handler.redis_handler.Worker.count", return_value=registered), + patch("handler.redis_handler.is_suspended", return_value=suspended), + ): assert has_live_worker(low_prio_queue) is expected - - mock_all.assert_called_once_with(queue=low_prio_queue) diff --git a/frontend/src/test-utils/serverError.ts b/frontend/src/test-utils/serverError.ts new file mode 100644 index 000000000..00bef7986 --- /dev/null +++ b/frontend/src/test-utils/serverError.ts @@ -0,0 +1,8 @@ +import { AxiosError } from "axios"; + +/** A refused request as axios rejects it, carrying FastAPI's `detail`. */ +export function serverError(detail: string, status = 503): AxiosError { + return Object.assign(new AxiosError(`HTTP ${status}`), { + response: { status, data: { detail } }, + }); +} diff --git a/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts b/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts index 3b4174363..cdfb13717 100644 --- a/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts +++ b/frontend/src/v2/components/Settings/MissingFirmwareSection.test.ts @@ -1,8 +1,8 @@ import { flushPromises, mount } from "@vue/test-utils"; -import { AxiosError } from "axios"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import storePlatforms from "@/stores/platforms"; +import { serverError } from "@/test-utils/serverError"; import MissingFirmwareSection from "./MissingFirmwareSection.vue"; const { getFirmware, runTask, getTaskById, confirm, snackbarError } = @@ -31,12 +31,6 @@ vi.mock("@/v2/composables/useSnackbar", () => ({ useSnackbar: () => ({ success: vi.fn(), error: snackbarError }), })); -function serverError(detail: string) { - return Object.assign(new AxiosError("HTTP 503"), { - response: { data: { detail } }, - }); -} - const PS1 = { id: 1, slug: "ps", diff --git a/frontend/src/v2/components/Settings/MissingGamesSection.test.ts b/frontend/src/v2/components/Settings/MissingGamesSection.test.ts index b317dcae8..aa2619591 100644 --- a/frontend/src/v2/components/Settings/MissingGamesSection.test.ts +++ b/frontend/src/v2/components/Settings/MissingGamesSection.test.ts @@ -1,9 +1,9 @@ import { flushPromises, mount } from "@vue/test-utils"; -import { AxiosError } from "axios"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { nextTick } from "vue"; import type { SimpleRom } from "@/stores/roms"; +import { serverError } from "@/test-utils/serverError"; import storeGallerySelection from "@/v2/stores/gallerySelection"; import MissingGamesSection from "./MissingGamesSection.vue"; @@ -46,12 +46,6 @@ vi.mock("@/v2/composables/useWebpSupport", () => ({ useWebpSupport: () => ({ supportsWebp: { value: true } }), })); -function serverError(detail: string) { - return Object.assign(new AxiosError("HTTP 503"), { - response: { data: { detail } }, - }); -} - function mountSection() { return mount(MissingGamesSection, { global: { @@ -77,7 +71,7 @@ describe("MissingGamesSection", () => { setActivePinia(createPinia()); getRoms.mockReset(); getRoms.mockResolvedValue({ - data: { total: 0, items: [], char_index: {}, rom_id_index: [] }, + data: { total: 1, items: [], char_index: {}, rom_id_index: [] }, }); runTask.mockReset(); runTask.mockResolvedValue({ data: { task_id: "job-1" } }); @@ -121,10 +115,6 @@ describe("MissingGamesSection", () => { }); it("tells why the server refused the cleanup", async () => { - // The action is disabled while the list is empty. - getRoms.mockResolvedValue({ - data: { total: 1, items: [], char_index: {}, rom_id_index: [] }, - }); confirm.mockResolvedValue(true); runTask.mockRejectedValue(serverError("No task worker is listening")); const wrapper = mountSection(); From 73d5789da46b25d8a42f1b872b4b20b9656aa623 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 16:22:37 +0200 Subject: [PATCH 12/28] test(tasks): give every successful-run test a live worker The fixture that stubs a listening worker was scoped to one class, so the integration and argument-handling runs answered 503 in CI, where no worker is registered. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01F9ta8rXUTP9aMdatPYKX4K --- backend/tests/endpoints/test_tasks.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/backend/tests/endpoints/test_tasks.py b/backend/tests/endpoints/test_tasks.py index 6b9fc90ba..ae92101c2 100644 --- a/backend/tests/endpoints/test_tasks.py +++ b/backend/tests/endpoints/test_tasks.py @@ -25,6 +25,13 @@ def _job_with_meta(meta: dict[str, Any]) -> Mock: return job +@pytest.fixture(autouse=True) +def task_worker_listening(): + """A live task worker, so a run is accepted unless a test takes it away.""" + with patch("endpoints.tasks.has_live_worker", return_value=True) as mocked: + yield mocked + + @pytest.fixture def mock_task(): """Create a mock task for testing""" @@ -237,12 +244,6 @@ class TestListTasks: class TestRunSingleTask: """Test suite for the run_single_task endpoint""" - @pytest.fixture(autouse=True) - def task_worker_listening(self): - """A live task worker, so a run is accepted unless a test takes it away.""" - with patch("endpoints.tasks.has_live_worker", return_value=True) as mocked: - yield mocked - @patch("endpoints.tasks.enqueue_task", return_value=create_mock_job()) def test_run_single_task_success( self, mock_enqueue, client, access_token, mock_task, task_worker_listening From e8d2e26cfff11c55d57eb06edf0312e37258f19b Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 16:25:13 +0200 Subject: [PATCH 13/28] fix(tasks): a worker that announced its death is not live `has_live_worker` reads each registered worker again and skips the ones carrying a death date as well as the suspended ones, with both states covered in the handler test. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01F9ta8rXUTP9aMdatPYKX4K --- backend/handler/redis_handler.py | 11 ++++--- backend/tests/handler/test_redis_handler.py | 33 ++++++++++++++++----- 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index 2ef409dfe..ec2ca9f16 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -8,7 +8,7 @@ from redis.asyncio import Redis as AsyncRedis from rq import Queue, Worker from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobError from rq.job import Job, JobStatus -from rq.suspension import is_suspended +from rq.worker import WorkerStatus from config import IS_PYTEST_RUN, REDIS_URL from logger.logger import log @@ -166,6 +166,9 @@ def get_worker_current_job(worker: Worker) -> Job | None: def has_live_worker(queue: Queue) -> bool: """Whether a job enqueued on ``queue`` would be picked up.""" - # A crashed worker stays registered until its key TTL lapses, so this can - # still say yes for a few minutes after a kill. - return Worker.count(queue=queue) > 0 and not is_suspended(redis_client) + # A worker that crashed without announcing it stays registered until its + # key TTL lapses, so this can still say yes for a few minutes after a kill. + return any( + worker.death_date is None and worker.get_state() != WorkerStatus.SUSPENDED + for worker in Worker.all(queue=queue) + ) diff --git a/backend/tests/handler/test_redis_handler.py b/backend/tests/handler/test_redis_handler.py index a08f3ef70..3e2dc0804 100644 --- a/backend/tests/handler/test_redis_handler.py +++ b/backend/tests/handler/test_redis_handler.py @@ -118,15 +118,32 @@ class TestGetWorkerCurrentJob: class TestHasLiveWorker: + @staticmethod + def _worker(state: str, death_date: str | None = None) -> MagicMock: + worker = MagicMock(spec=Worker) + worker.get_state.return_value = state + worker.death_date = death_date + return worker + @pytest.mark.parametrize( - ("registered", "suspended", "expected"), - [(0, False, False), (1, True, False), (1, False, True), (2, False, True)], + ("workers", "expected"), + [ + ([], False), + ([("suspended", None)], False), + ([("idle", "2026-09-16T10:00:00")], False), + ([("suspended", None), ("idle", None)], True), + ([("busy", None)], True), + ], + ids=["none-registered", "suspended", "announced-dead", "one-live", "busy"], ) - def test_needs_a_registered_worker_that_is_not_suspended( - self, registered: int, suspended: bool, expected: bool + def test_counts_only_workers_that_would_take_a_job( + self, workers: list[tuple[str, str | None]], expected: bool ): - with ( - patch("handler.redis_handler.Worker.count", return_value=registered), - patch("handler.redis_handler.is_suspended", return_value=suspended), - ): + registered = [self._worker(state, death) for state, death in workers] + + with patch( + "handler.redis_handler.Worker.all", return_value=registered + ) as mock_all: assert has_live_worker(low_prio_queue) is expected + + mock_all.assert_called_once_with(queue=low_prio_queue) From e869ecb6b671175bd365cab6c842e9caf5284bba Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 16:27:38 +0200 Subject: [PATCH 14/28] Enforce media allowlists and walkthrough provenance in the shared upload path A folder the scanner maps to a media category now refuses files that category cannot hold inside resolve_upload_destination, so the chunked flow the v2 tabs use gets the same allowlist the media routes had, and those routes drop their own copies. commit_upload records an upload provenance for walkthrough files that arrive without one and returns the registered row, which the walkthrough route uses for author and title. The refresh lock moves to Redis so uploads landing on different gunicorn workers cannot drop each other rows. An empty body filename is rejected instead of falling back to the header. Co-Authored-By: Claude Fable 5.1 --- backend/endpoints/roms/manual.py | 9 --- backend/endpoints/roms/screenshot.py | 13 ---- backend/endpoints/roms/soundtrack.py | 15 +--- backend/endpoints/roms/upload.py | 19 +++-- backend/endpoints/roms/walkthrough.py | 22 +----- backend/handler/filesystem/roms_handler.py | 22 ++++-- backend/handler/rom_files.py | 20 +++-- backend/handler/rom_upload.py | 66 +++++++++++++--- backend/tests/endpoints/roms/test_upload.py | 76 ++++++++++++++++++- .../GameDetails/ScreenshotsSubtab.vue | 6 +- 10 files changed, 169 insertions(+), 99 deletions(-) diff --git a/backend/endpoints/roms/manual.py b/backend/endpoints/roms/manual.py index f016074d0..916cbb45d 100644 --- a/backend/endpoints/roms/manual.py +++ b/backend/endpoints/roms/manual.py @@ -215,15 +215,6 @@ async def add_rom_manual_file( assert_rom_visible(request, rom) - if not _is_allowed_manual_file(filename): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=( - f"Unsupported manual file type. Allowed: " - f"{', '.join(sorted(ALLOWED_MANUAL_EXTENSIONS))}" - ), - ) - await receive_rom_file( request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.MANUAL], filename ) diff --git a/backend/endpoints/roms/screenshot.py b/backend/endpoints/roms/screenshot.py index 90af9c3b8..996f3c125 100644 --- a/backend/endpoints/roms/screenshot.py +++ b/backend/endpoints/roms/screenshot.py @@ -17,10 +17,6 @@ from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log from models.rom import RomFileCategory -from utils.media_types import ( - ALLOWED_IMAGE_EXTENSIONS, - is_allowed_image_file, -) from utils.router import APIRouter router = APIRouter() @@ -52,15 +48,6 @@ async def add_rom_screenshots( assert_rom_visible(request, rom) - if not is_allowed_image_file(filename): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=( - f"Unsupported image file type. Allowed: " - f"{', '.join(sorted(ALLOWED_IMAGE_EXTENSIONS))}" - ), - ) - await receive_rom_file( request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.SCREENSHOT], filename ) diff --git a/backend/endpoints/roms/soundtrack.py b/backend/endpoints/roms/soundtrack.py index 38740b31b..69ae52757 100644 --- a/backend/endpoints/roms/soundtrack.py +++ b/backend/endpoints/roms/soundtrack.py @@ -18,11 +18,7 @@ from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log from models.rom import RomFileCategory -from utils.audio_tags import ( - ALLOWED_AUDIO_EXTENSIONS, - is_allowed_audio_file, - remove_persisted_cover, -) +from utils.audio_tags import remove_persisted_cover from utils.router import APIRouter router = APIRouter() @@ -89,15 +85,6 @@ async def add_rom_soundtracks( assert_rom_visible(request, rom) - if not is_allowed_audio_file(filename): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=( - f"Unsupported audio file type. Allowed: " - f"{', '.join(sorted(ALLOWED_AUDIO_EXTENSIONS))}" - ), - ) - await receive_rom_file( request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.SOUNDTRACK], filename ) diff --git a/backend/endpoints/roms/upload.py b/backend/endpoints/roms/upload.py index 8c75c9ef7..58c09c83c 100644 --- a/backend/endpoints/roms/upload.py +++ b/backend/endpoints/roms/upload.py @@ -35,7 +35,7 @@ from handler.rom_upload import ( staging_path, ) from logger.logger import log -from models.rom import Rom +from models.rom import Rom, RomFile from utils.router import APIRouter router = APIRouter( @@ -149,9 +149,9 @@ async def _prepare_rom_destination( async def _commit( destination: UploadDestination, staged: Path, *, overwrite: bool -) -> None: +) -> RomFile | None: try: - await commit_upload(destination, staged, overwrite=overwrite) + return await commit_upload(destination, staged, overwrite=overwrite) except UploadConflictException as exc: raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail=str(exc) @@ -164,9 +164,13 @@ async def _commit( async def receive_rom_file( request: Request, rom: Rom, folder: str, filename: str -) -> UploadDestination: +) -> RomFile | None: """Stream a single-file multipart body into a subfolder of the ROM and - register it the way a chunked upload is, replacing a file of the same name.""" + register it the way a chunked upload is, replacing a file of the same name. + + Returns: + The registered file row, or None when the scanner did not list it. + """ safe_filename = _sanitized_filename(filename) destination = await _prepare_rom_destination( rom, folder, safe_filename, overwrite=True @@ -200,8 +204,7 @@ async def receive_rom_file( detail=f"The upload body has no file part named {safe_filename}", ) - await _commit(destination, staged, overwrite=True) - return destination + return await _commit(destination, staged, overwrite=True) async def _resolve_destination(request: Request, session: dict) -> UploadDestination: @@ -284,7 +287,7 @@ async def start_chunked_upload( ) platform_fs_slug = db_platform.fs_slug - if target and target.filename: + if target and target.filename is not None: filename = target.filename safe_filename = _sanitized_filename(filename) rom_id = target.rom_id if target else None diff --git a/backend/endpoints/roms/walkthrough.py b/backend/endpoints/roms/walkthrough.py index ffa193a0c..9207c35d3 100644 --- a/backend/endpoints/roms/walkthrough.py +++ b/backend/endpoints/roms/walkthrough.py @@ -25,7 +25,6 @@ from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log from models.rom import DocSource, RomFile, RomFileCategory -from utils.media_types import ALLOWED_DOCUMENT_EXTENSIONS from utils.router import APIRouter router = APIRouter() @@ -33,11 +32,6 @@ router = APIRouter() _SLUG_RE = re.compile(r"[^a-z0-9]+") -def _is_allowed_walkthrough_file(file_name: str) -> bool: - _, ext = os.path.splitext(file_name) - return ext.lower() in ALLOWED_DOCUMENT_EXTENSIONS - - def _slugify(value: str, fallback: str = "walkthrough") -> str: slug = _SLUG_RE.sub("-", value.lower()).strip("-") return (slug[:80] or fallback).strip("-") or fallback @@ -88,28 +82,14 @@ async def add_rom_walkthrough_file( assert_rom_visible(request, rom) - if not _is_allowed_walkthrough_file(filename): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=( - f"Unsupported walkthrough file type. Allowed: " - f"{', '.join(sorted(ALLOWED_DOCUMENT_EXTENSIONS))}" - ), - ) - - destination = await receive_rom_file( + rom_file = await receive_rom_file( request, rom, CATEGORY_UPLOAD_FOLDERS[RomFileCategory.WALKTHROUGH], filename ) - - rom_file = db_rom_handler.get_rom_file_by_path( - rom_id=rom.id, file_path=destination.rel_dir, file_name=filename - ) if rom_file: db_rom_handler.upsert_doc_meta( rom_file_id=rom_file.id, rom_id=rom.id, values={ - "source": DocSource.UPLOAD, "author": _decode_header(author), "title": _decode_header(title), }, diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index deda91132..6f6fbc437 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -147,6 +147,18 @@ def category_matches(category: str, path_parts: list[str]) -> bool: ) +def category_for_path_parts(path_parts_lower: list[str]) -> RomFileCategory | None: + """The file category a folder path implies, from its lowercased parts.""" + return next( + ( + category + for category in RomFileCategory + if category_matches(category.value, path_parts_lower) + ), + None, + ) + + DEFAULT_CRC_C = 0 DEFAULT_MD5_H_DIGEST = hashlib.md5(usedforsecurity=False).digest() DEFAULT_SHA1_H_DIGEST = hashlib.sha1(usedforsecurity=False).digest() @@ -462,14 +474,8 @@ class FSRomsHandler(FSHandler): ) -> RomFile: abs_file_path = Path(self.base_path, rom_path, file_name) - path_parts_lower = list(map(str.lower, rom_path.parts)) - matching_category = next( - ( - category - for category in RomFileCategory - if category_matches(category.value, path_parts_lower) - ), - None, + matching_category = category_for_path_parts( + list(map(str.lower, rom_path.parts)) ) track_meta = None diff --git a/backend/handler/rom_files.py b/backend/handler/rom_files.py index 6925b24e2..fea002ce1 100644 --- a/backend/handler/rom_files.py +++ b/backend/handler/rom_files.py @@ -1,14 +1,14 @@ -import asyncio -import weakref from dataclasses import dataclass from typing import Any +from redis.asyncio.lock import Lock from sqlalchemy import inspect as sa_inspect from config.config_manager import config_manager as cm from handler.database import db_rom_handler from handler.filesystem import fs_rom_handler from handler.filesystem.roms_handler import RomFileKey, rom_file_key +from handler.redis_handler import async_cache from handler.scan_handler import persist_soundtrack_cover from logger.formatter import highlight as hl from logger.logger import log @@ -19,17 +19,15 @@ ROM_LEVEL_HASH_COLUMNS = ("crc_hash", "md5_hash", "sha1_hash", "ra_hash") # A refresh lists the folder and then deletes every row the listing missed, so # two of them running for the same rom (parallel uploads into one folder) would -# let the slower listing drop what the faster one just registered. -_refresh_locks: weakref.WeakValueDictionary[int, asyncio.Lock] = ( - weakref.WeakValueDictionary() -) +# let the slower listing drop what the faster one just registered. The lock +# lives in Redis because the uploads may land on different gunicorn workers. +REFRESH_LOCK_TIMEOUT_SECONDS = 600 -def _refresh_lock(rom_id: int) -> asyncio.Lock: - lock = _refresh_locks.get(rom_id) - if lock is None: - lock = _refresh_locks[rom_id] = asyncio.Lock() - return lock +def _refresh_lock(rom_id: int) -> Lock: + return async_cache.lock( + f"rom_files_refresh:{rom_id}", timeout=REFRESH_LOCK_TIMEOUT_SECONDS + ) @dataclass(frozen=True) diff --git a/backend/handler/rom_upload.py b/backend/handler/rom_upload.py index 3625fd68a..cd03f636e 100644 --- a/backend/handler/rom_upload.py +++ b/backend/handler/rom_upload.py @@ -7,11 +7,16 @@ from pathlib import Path from uuid import uuid4 from config import ROM_UPLOAD_ASSEMBLING_EXT +from handler.database import db_rom_handler from handler.filesystem import fs_rom_handler +from handler.filesystem.resources_handler import ALLOWED_MANUAL_EXTENSIONS +from handler.filesystem.roms_handler import category_for_path_parts from handler.rom_conversion import promote_single_file_to_folder from handler.rom_files import refresh_rom_files from logger.logger import log -from models.rom import Rom, RomFileCategory +from models.rom import DocSource, Rom, RomFile, RomFileCategory +from utils.audio_tags import ALLOWED_AUDIO_EXTENSIONS +from utils.media_types import ALLOWED_DOCUMENT_EXTENSIONS, ALLOWED_IMAGE_EXTENSIONS # The folder each media route uploads into. The scanner maps these names back to # the category, so a file landing here is registered the same way a scan would. @@ -23,6 +28,16 @@ CATEGORY_UPLOAD_FOLDERS: dict[RomFileCategory, str] = { } +# What a folder the scanner maps to a media category may receive, so a file the +# tab could never show is refused before it lands. +CATEGORY_FILE_TYPES: dict[RomFileCategory, tuple[str, frozenset[str]]] = { + RomFileCategory.MANUAL: ("manual", ALLOWED_MANUAL_EXTENSIONS), + RomFileCategory.WALKTHROUGH: ("walkthrough", ALLOWED_DOCUMENT_EXTENSIONS), + RomFileCategory.SCREENSHOT: ("image", ALLOWED_IMAGE_EXTENSIONS), + RomFileCategory.SOUNDTRACK: ("audio", ALLOWED_AUDIO_EXTENSIONS), +} + + class UploadRejectedException(ValueError): """The upload names a file or folder the ROM's folder cannot take.""" @@ -81,6 +96,18 @@ def parse_upload_folder(folder: str) -> str: return "/".join(segments) +def assert_allowed_in_folder(folder: str, filename: str) -> None: + """Refuse a file the category the folder maps to cannot hold.""" + category = category_for_path_parts(folder.lower().split("/")) + if category is None or category not in CATEGORY_FILE_TYPES: + return + label, extensions = CATEGORY_FILE_TYPES[category] + if os.path.splitext(filename)[1].lower() not in extensions: + raise UploadRejectedException( + f"Unsupported {label} file type. Allowed: {', '.join(sorted(extensions))}" + ) + + def resolve_upload_destination( rom: Rom, folder: str, filename: str, *, overwrite: bool = False ) -> tuple[str, Path]: @@ -88,11 +115,12 @@ def resolve_upload_destination( ROM, kept inside the folder a lone file gets promoted into. Raises: - UploadRejectedException: The destination is unusable or the scanner - would never register the file. + UploadRejectedException: The destination is unusable, the folder's + category cannot hold the file, or the scanner would never register it. UploadConflictException: A file of that name is already there (or will be, once promoted), unless `overwrite` allows replacing it. """ + assert_allowed_in_folder(folder, filename) if fs_rom_handler.is_excluded_multi_part(filename): raise UploadRejectedException( f"File {filename} would be ignored by the scanner" @@ -178,11 +206,13 @@ def _move_into_place(location: Path, staged: Path, *, overwrite: bool) -> None: async def commit_upload( destination: UploadDestination, staged: Path, *, overwrite: bool = False -) -> None: +) -> RomFile | None: """Move the staged bytes into place and register the file on its ROM. The staged file is removed whatever the outcome. + Returns: + The registered file row, or None for a platform folder upload. Raises: UploadConflictException: The name got taken while the bytes arrived. UploadNotRegisteredException: The file is in place but the ROM's rows @@ -191,15 +221,29 @@ async def commit_upload( _move_into_place(destination.location, staged, overwrite=overwrite) log.info(f"Upload complete: {destination.location}") - if destination.rom is None: - return + rom = destination.rom + if rom is None: + return None try: - await refresh_rom_files(destination.rom) + await refresh_rom_files(rom) except Exception as exc: - log.error( - f"Error registering uploaded file for ROM {destination.rom.id}", - exc_info=exc, - ) + log.error(f"Error registering uploaded file for ROM {rom.id}", exc_info=exc) raise UploadNotRegisteredException( "File uploaded but not registered yet, run a quick scan" ) from exc + + rom_file = db_rom_handler.get_rom_file_by_path( + rom_id=rom.id, + file_path=destination.rel_dir, + file_name=destination.location.name, + ) + # A scan records no provenance; an upload is one, whichever route took it. + if ( + rom_file + and rom_file.category == RomFileCategory.WALKTHROUGH + and rom_file.doc_meta is None + ): + db_rom_handler.upsert_doc_meta( + rom_file_id=rom_file.id, rom_id=rom.id, values={"source": DocSource.UPLOAD} + ) + return rom_file diff --git a/backend/tests/endpoints/roms/test_upload.py b/backend/tests/endpoints/roms/test_upload.py index 10a41f54a..a51c834bb 100644 --- a/backend/tests/endpoints/roms/test_upload.py +++ b/backend/tests/endpoints/roms/test_upload.py @@ -12,7 +12,7 @@ from endpoints.roms import upload as upload_endpoint from handler import rom_upload from handler.database import db_platform_handler, db_rom_handler from models.platform import Platform -from models.rom import Rom, RomFile, RomFileCategory +from models.rom import DocSource, Rom, RomFile, RomFileCategory from models.user import User @@ -776,6 +776,80 @@ def test_start_takes_the_filename_from_the_body_over_the_header( assert [f.file_name for f in track] == [name] +def test_start_refuses_a_file_the_folder_category_cannot_hold( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + rom = _folder_rom(platform, admin_user, rom_upload_fs, {"game.bin": b"game"}) + + response = _start_into_rom( + client, + access_token, + rom, + filename="notes.txt", + folder="screenshots", + total_size=3, + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert "Unsupported image file type" in response.json()["detail"] + + +def test_start_rejects_an_empty_body_filename( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + rom = _folder_rom(platform, admin_user, rom_upload_fs, {"game.bin": b"game"}) + + response = client.post( + "/api/roms/upload/start", + headers={ + **_auth_headers(access_token), + "x-upload-platform": str(rom.platform_id), + "x-upload-filename": "fallback.bin", + "x-upload-total-size": "3", + "x-upload-total-chunks": "1", + }, + json={"rom_id": rom.id, "filename": ""}, + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert "filename" in response.json()["detail"].lower() + + +def test_complete_into_the_walkthrough_folder_records_the_upload_source( + client: TestClient, + access_token: str, + platform: Platform, + admin_user: User, + rom_upload_fs: Path, +): + rom = _folder_rom(platform, admin_user, rom_upload_fs, {"game.bin": b"game"}) + + response = _upload_into_rom( + client, + access_token, + rom, + filename="guide.txt", + folder="walkthrough", + data=b"Step 1: leave home.", + ) + + assert response.status_code == status.HTTP_201_CREATED, response.json() + guides = db_rom_handler.get_rom_files_by_category( + rom.id, RomFileCategory.WALKTHROUGH + ) + assert [f.file_name for f in guides] == ["guide.txt"] + assert guides[0].doc_meta is not None + assert guides[0].doc_meta.source == DocSource.UPLOAD + + def test_complete_into_a_category_folder_registers_the_category( client: TestClient, access_token: str, diff --git a/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue b/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue index 787fb8d11..fdb0a7375 100644 --- a/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue +++ b/frontend/src/v2/components/GameDetails/ScreenshotsSubtab.vue @@ -2,9 +2,9 @@ // ScreenshotsSubtab — the Media tab's Screenshots panel. Three sections: // // * ROM — shared library screenshots stored in the ROM's -// `screenshots/` folder (RomFile, category SCREENSHOT). Only -// folder-based multi-file ROMs can host them. Public to every -// user who can see the ROM. Upload → `useRomFileUpload`. +// `screenshots/` folder (RomFile, category SCREENSHOT). A +// single-file ROM is promoted to a folder on upload. Public to +// every user who can see the ROM. Upload → `useRomFileUpload`. // * Mine — per-user screenshots stored under the user's asset folder. // Private by default, with a per-item public/private toggle. // Any ROM. Upload → `screenshotApi.uploadGalleryScreenshots`. From 071787311d46565966680fcb127667c240181c5f Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 17:03:59 +0200 Subject: [PATCH 15/28] Take the refresh lock with SET NX instead of a Lua-backed Lock redis-py releases its Lock through a Lua script, which the fakeredis CI runs without, so every registration failed there with an unknown evalsha command. The lock is now a SET NX EX with an owner token, released only by its owner, the same shape the log forwarder already uses. Co-Authored-By: Claude Fable 5.1 --- backend/handler/rom_files.py | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/backend/handler/rom_files.py b/backend/handler/rom_files.py index fea002ce1..cb4fbd116 100644 --- a/backend/handler/rom_files.py +++ b/backend/handler/rom_files.py @@ -1,7 +1,10 @@ +import asyncio +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager from dataclasses import dataclass from typing import Any +from uuid import uuid4 -from redis.asyncio.lock import Lock from sqlalchemy import inspect as sa_inspect from config.config_manager import config_manager as cm @@ -20,14 +23,27 @@ ROM_LEVEL_HASH_COLUMNS = ("crc_hash", "md5_hash", "sha1_hash", "ra_hash") # A refresh lists the folder and then deletes every row the listing missed, so # two of them running for the same rom (parallel uploads into one folder) would # let the slower listing drop what the faster one just registered. The lock -# lives in Redis because the uploads may land on different gunicorn workers. +# lives in Redis because the uploads may land on different gunicorn workers, +# and is a plain SET NX so it also works without Lua scripting. REFRESH_LOCK_TIMEOUT_SECONDS = 600 +REFRESH_LOCK_POLL_SECONDS = 0.1 -def _refresh_lock(rom_id: int) -> Lock: - return async_cache.lock( - f"rom_files_refresh:{rom_id}", timeout=REFRESH_LOCK_TIMEOUT_SECONDS - ) +@asynccontextmanager +async def _refresh_lock(rom_id: int) -> AsyncIterator[None]: + key = f"rom_files_refresh:{rom_id}" + token = uuid4().hex + while not await async_cache.set( + key, token, nx=True, ex=REFRESH_LOCK_TIMEOUT_SECONDS + ): + await asyncio.sleep(REFRESH_LOCK_POLL_SECONDS) + try: + yield + finally: + # Only the owner releases; an expired lock may belong to someone else. + held = await async_cache.get(key) + if held in (token, token.encode()): + await async_cache.delete(key) @dataclass(frozen=True) From 1f631e79629a18318c3e27d1966099abfac10487 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 17:09:54 +0200 Subject: [PATCH 16/28] Bound the refresh lock wait instead of spinning on sleep ruff ASYNC110 flags a while loop whose body is only an await sleep. The wait is now a bounded poll that gives up with a TimeoutError once the lock expiry has elapsed, so a stuck holder cannot hang the upload. Co-Authored-By: Claude Fable 5.1 --- backend/handler/rom_files.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/backend/handler/rom_files.py b/backend/handler/rom_files.py index cb4fbd116..ea1011901 100644 --- a/backend/handler/rom_files.py +++ b/backend/handler/rom_files.py @@ -33,10 +33,12 @@ REFRESH_LOCK_POLL_SECONDS = 0.1 async def _refresh_lock(rom_id: int) -> AsyncIterator[None]: key = f"rom_files_refresh:{rom_id}" token = uuid4().hex - while not await async_cache.set( - key, token, nx=True, ex=REFRESH_LOCK_TIMEOUT_SECONDS - ): + for _ in range(int(REFRESH_LOCK_TIMEOUT_SECONDS / REFRESH_LOCK_POLL_SECONDS)): + if await async_cache.set(key, token, nx=True, ex=REFRESH_LOCK_TIMEOUT_SECONDS): + break await asyncio.sleep(REFRESH_LOCK_POLL_SECONDS) + else: + raise TimeoutError(f"Timed out waiting to refresh the files of ROM {rom_id}") try: yield finally: From 14fc8d9930540d7d03d3588f7466ebca06805ed6 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Wed, 16 Sep 2026 11:05:03 -0500 Subject: [PATCH 17/28] fix: treat every disc descriptor as a disc, not just .cue (#4532) * Treat every disc descriptor as a disc, not just .cue playlist_files keyed on .cue alone, so a Dreamcast .gdi set, a CloneCD .ccd set and an Alcohol .mds set all fell through to "every file is a disc" -- the descriptor and the raw tracks it cannot boot without were listed side by side. The three readers of the rule each got that wrong in their own way: the playlist shipped inside the download zip named non-bootable tracks, and the in-browser disc swapper offered them as discs. Key on a set of descriptor extensions instead, so no one sheet format is privileged over the others. The shape is unchanged -- descriptors if any, else everything -- and so is the download zip, which lists every file regardless. Co-Authored-By: Claude Opus 5 * Keep a disc that stands on its own beside a descriptor Selecting descriptors and discarding everything else assumed a multi-file ROM is all one format. It is not: a .chd sitting beside a .gdi boots on its own, and returning only the .gdi dropped it from the playlist and from the swapper's targets. Exclude the raw tracks a sheet points at instead of keeping only sheets. The tracks are still not discs, so every case the previous commit fixed stays fixed, and a disc no sheet describes now survives. This also settles the same bug on the .cue path, which predates this branch: disc1.cue + disc1.bin + disc2.chd used to list the cue alone. Co-Authored-By: Claude Opus 5 * Count a sheet's audio tracks as tracks A .cue names its CDDA tracks the same way it names its data track, so a .wav or .flac beside one is data, not a disc. The playlist listed them. Brings the list in step with the shell's own in src/main/discs/m3u.ts, which has carried the audio formats since it was written. Co-Authored-By: Claude Opus 5 --------- Co-authored-by: Claude Opus 5 --- backend/tests/utils/test_m3u.py | 110 ++++++++++++++++++++++++++++++-- backend/utils/m3u.py | 28 ++++++-- 2 files changed, 128 insertions(+), 10 deletions(-) diff --git a/backend/tests/utils/test_m3u.py b/backend/tests/utils/test_m3u.py index 9abe4454e..34f417d16 100644 --- a/backend/tests/utils/test_m3u.py +++ b/backend/tests/utils/test_m3u.py @@ -1,6 +1,6 @@ from unittest.mock import MagicMock -from utils.m3u import generate_m3u_content +from utils.m3u import generate_m3u_content, playlist_files def _make_file(name: str, extension: str, download_name: str | None = None): @@ -49,11 +49,113 @@ class TestGenerateM3uContent: assert result == b".hidden/game.chd" files[0].file_name_for_download.assert_called_once_with(True) - def test_no_cue_files_lists_all(self): + def test_no_descriptor_files_lists_all(self): files = [ _make_file("disc1.chd", "chd"), _make_file("disc2.chd", "chd"), ] result = generate_m3u_content(files, hidden_folder=False) - lines = result.decode().split("\n") - assert len(lines) == 2 + assert result == b"disc1.chd\ndisc2.chd" + + def test_gdi_preferred_over_raw_tracks(self): + files = [ + _make_file("track01.bin", "bin"), + _make_file("track02.raw", "raw"), + _make_file("game.gdi", "gdi"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"game.gdi" + + def test_ccd_preferred_over_img_and_sub(self): + files = [ + _make_file("game.img", "img"), + _make_file("game.sub", "sub"), + _make_file("game.ccd", "ccd"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"game.ccd" + + def test_mds_preferred_over_mdf(self): + files = [ + _make_file("game.mdf", "mdf"), + _make_file("game.mds", "mds"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"game.mds" + + def test_descriptor_case_insensitive(self): + files = [ + _make_file("track01.bin", "bin"), + _make_file("game.GDI", "GDI", download_name="game.GDI"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"game.GDI" + + def test_every_disc_descriptor_listed(self): + files = [ + _make_file("disc1/track01.bin", "bin"), + _make_file("disc1.gdi", "gdi"), + _make_file("disc2/track01.bin", "bin"), + _make_file("disc2.gdi", "gdi"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"disc1.gdi\ndisc2.gdi" + + def test_standalone_disc_kept_beside_a_descriptor(self): + # A set is not required to be all one format. The .gdi's tracks are + # data, but the .chd is a disc that boots on its own. + files = [ + _make_file("disc1.gdi", "gdi"), + _make_file("track01.bin", "bin"), + _make_file("disc2.chd", "chd"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"disc1.gdi\ndisc2.chd" + + def test_standalone_disc_kept_beside_a_cue(self): + files = [ + _make_file("disc1.cue", "cue"), + _make_file("disc1.bin", "bin"), + _make_file("disc2.chd", "chd"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"disc1.cue\ndisc2.chd" + + def test_audio_tracks_are_not_discs(self): + # A cue's CDDA tracks are data the sheet names, not discs beside it. + files = [ + _make_file("game.cue", "cue"), + _make_file("track01.bin", "bin"), + _make_file("track02.wav", "wav"), + ] + result = generate_m3u_content(files, hidden_folder=False) + assert result == b"game.cue" + + +class TestPlaylistFiles: + """The disc swapper reads this directly, so the files themselves matter.""" + + def test_m3u_is_never_a_disc(self): + m3u = _make_file("game.m3u", "m3u") + disc = _make_file("game.chd", "chd") + assert playlist_files([m3u, disc]) == [disc] + + def test_raw_tracks_are_not_discs(self): + track = _make_file("track01.bin", "bin") + gdi = _make_file("game.gdi", "gdi") + assert playlist_files([track, gdi]) == [gdi] + + def test_bare_files_are_all_discs(self): + discs = [_make_file("disc1.chd", "chd"), _make_file("disc2.chd", "chd")] + assert playlist_files(discs) == discs + + def test_standalone_disc_survives_a_descriptor(self): + gdi = _make_file("disc1.gdi", "gdi") + track = _make_file("track01.bin", "bin") + chd = _make_file("disc2.chd", "chd") + assert playlist_files([gdi, track, chd]) == [gdi, chd] + + def test_bare_tracks_without_a_descriptor_are_discs(self): + # Nothing describes them, so they are all there is to play. + tracks = [_make_file("track01.bin", "bin"), _make_file("track02.bin", "bin")] + assert playlist_files(tracks) == tracks diff --git a/backend/utils/m3u.py b/backend/utils/m3u.py index 45428f19d..3fe33e46b 100644 --- a/backend/utils/m3u.py +++ b/backend/utils/m3u.py @@ -5,18 +5,34 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from models.rom import RomFile +# Sheet formats that describe a disc by pointing at raw track files: .cue for +# BIN/CUE, .gdi for Dreamcast, .ccd for CloneCD and .mds for Alcohol. No one +# format is privileged over the others. +DESCRIPTOR_EXTENSIONS = frozenset({"cue", "gdi", "ccd", "mds"}) + +# The raw tracks those sheets point at, data and CDDA audio alike. None of them +# is loadable on its own, so a sheet in the set means its tracks are data rather +# than discs -- but only those tracks. Anything else present stays a disc in its +# own right. Kept in step with the shell's own list in src/main/discs/m3u.ts. +COMPANION_EXTENSIONS = frozenset( + {"bin", "raw", "img", "sub", "mdf", "wav", "ogg", "flac", "mp3"} +) + def playlist_files(files: list[RomFile]) -> list[RomFile]: """The files of a multi-file ROM that name a playable disc. - The .m3u itself is never one, and where .cue files are present only those - are, since the raw .bin tracks they reference are not loadable on their own. - One home for the rule: the playlist, the download endpoint and the disc - swapper all have to agree on which files are discs. + The .m3u itself is never one. Where a descriptor is present the raw tracks + it references are not discs either, since they are not loadable alone -- + but a set is not required to be all one format, so a disc that stands on + its own (a .chd beside a .gdi) is kept. One home for the rule: the + playlist, the download endpoint and the disc swapper all have to agree on + which files are discs. """ discs = [f for f in files if f.file_extension.lower() != "m3u"] - cue_files = [f for f in discs if f.file_extension.lower() == "cue"] - return cue_files or discs + if not any(f.file_extension.lower() in DESCRIPTOR_EXTENSIONS for f in discs): + return discs + return [f for f in discs if f.file_extension.lower() not in COMPANION_EXTENSIONS] def generate_m3u_content( From 42f27f1b863a40da4037513137f916be0a1fe626 Mon Sep 17 00:00:00 2001 From: zurdi Date: Wed, 16 Sep 2026 19:02:34 +0200 Subject: [PATCH 18/28] fix(v2): jukebox in the settings sidebar, launch-view titles, match overlay Add the Jukebox entry to the settings sidebar's Tools group, above Controller debug, so the in-page navigator mirrors the user menu. Keep the "All saves" / "All states" title rendered when the list is empty. In the split states layout both columns subgrid their title and content rows, so a missing title dropped the empty box into the title row and pushed the resume preview far down the panel. Anchor the match dialog's saving overlay to the dialog body instead of an inner wrapper, so the blur reaches the body's padding edges, and lighten its tint from 65% to 30% of the background color. Co-Authored-By: Claude Fable 5.1 --- .../v2/components/Dialogs/MatchRomDialog.vue | 73 ++++++++----------- .../components/Settings/SettingsSidebar.vue | 11 ++- frontend/src/v2/views/Player/EmulatorJS.vue | 6 +- 3 files changed, 42 insertions(+), 48 deletions(-) diff --git a/frontend/src/v2/components/Dialogs/MatchRomDialog.vue b/frontend/src/v2/components/Dialogs/MatchRomDialog.vue index 3f673e76e..4e9d88a0c 100644 --- a/frontend/src/v2/components/Dialogs/MatchRomDialog.vue +++ b/frontend/src/v2/components/Dialogs/MatchRomDialog.vue @@ -296,6 +296,7 @@ function closeDialog() { - - +