diff --git a/backend/config/__init__.py b/backend/config/__init__.py index efedee835..2d9f6cbc5 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -22,6 +22,7 @@ DEV_SQL_ECHO: Final = str_to_bool(os.environ.get("DEV_SQL_ECHO", "false")) # PATHS ROMM_BASE_PATH: Final = os.environ.get("ROMM_BASE_PATH", "/romm") +ROMM_TMP_PATH: Final = os.environ.get("ROMM_TMP_PATH", None) LIBRARY_BASE_PATH: Final = f"{ROMM_BASE_PATH}/library" RESOURCES_BASE_PATH: Final = f"{ROMM_BASE_PATH}/resources" ASSETS_BASE_PATH: Final = f"{ROMM_BASE_PATH}/assets" diff --git a/backend/decorators/auth.py b/backend/decorators/auth.py index 689423c5f..1baf15adc 100644 --- a/backend/decorators/auth.py +++ b/backend/decorators/auth.py @@ -10,6 +10,7 @@ from starlette.authentication import requires from starlette.config import Config from config import ( + OIDC_CLAIM_ROLES, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, OIDC_ENABLED, @@ -58,7 +59,7 @@ oauth.register( config.get("OIDC_SERVER_APPLICATION_URL"), external=True ), client_kwargs={ - "scope": "openid profile email", + "scope": f"openid profile email {OIDC_CLAIM_ROLES}".strip(), "verify": OIDC_TLS_CACERTFILE, }, ) diff --git a/backend/endpoints/feeds.py b/backend/endpoints/feeds.py index 2ebf352f8..0e28360ea 100644 --- a/backend/endpoints/feeds.py +++ b/backend/endpoints/feeds.py @@ -142,8 +142,8 @@ async def tinfoil_index_feed( async def extract_titledb( roms: Sequence[Rom], - ) -> dict[str, TinfoilFeedTitleDBSchema]: - titledb = {} + ) -> dict[str, dict]: + titledb: dict[str, dict] = {} for rom in roms: tdb_match = SWITCH_TITLEDB_REGEX.search(rom.fs_name) pid_match = SWITCH_PRODUCT_ID_REGEX.search(rom.fs_name) @@ -154,18 +154,11 @@ async def tinfoil_index_feed( ) ) if index_entry: - titledb[str(index_entry["nsuId"])] = TinfoilFeedTitleDBSchema( - id=str(index_entry["nsuId"]), - name=index_entry["name"], - description=index_entry["description"], - size=index_entry["size"], - version=index_entry["version"] or 0, - region=index_entry["region"] or "US", - releaseDate=index_entry["releaseDate"] or 19700101, - rating=index_entry["rating"] or 0, - publisher=index_entry["publisher"] or "", - rank=0, - ) + key = str(index_entry.get("nsuId", None)) + if key is not None: # only store if we have an id + titledb[key] = TinfoilFeedTitleDBSchema( + **index_entry + ).model_dump() elif pid_match: _search_term, index_entry = ( await meta_igdb_handler._switch_productid_format( @@ -173,18 +166,11 @@ async def tinfoil_index_feed( ) ) if index_entry: - titledb[str(index_entry["nsuId"])] = TinfoilFeedTitleDBSchema( - id=str(index_entry["nsuId"]), - name=index_entry["name"], - description=index_entry["description"], - size=index_entry["size"], - version=index_entry["version"] or 0, - region=index_entry["region"] or "US", - releaseDate=index_entry["releaseDate"] or 19700101, - rating=index_entry["rating"] or 0, - publisher=index_entry["publisher"] or "", - rank=0, - ) + key = str(index_entry.get("nsuId", None)) + if key is not None: + titledb[key] = TinfoilFeedTitleDBSchema( + **index_entry + ).model_dump() return titledb diff --git a/backend/endpoints/responses/feeds.py b/backend/endpoints/responses/feeds.py index fffc4eb83..dc5bfdcaf 100644 --- a/backend/endpoints/responses/feeds.py +++ b/backend/endpoints/responses/feeds.py @@ -1,4 +1,6 @@ -from typing import NotRequired, TypedDict +from typing import Annotated, Any, NotRequired, TypedDict + +from pydantic import BaseModel, BeforeValidator, Field from handler.metadata.base_handler import UniversalPlatformSlug as UPS @@ -64,6 +66,27 @@ WEBRCADE_SLUG_TO_TYPE_MAP = { # Source: https://docs.webrcade.com/feeds/format/ +def coerce_to_string(value: Any) -> str: + """Coerce value to string, returning empty string for None.""" + return "" if value is None else str(value) + + +def coerce_to_int(value: Any) -> int: + """Coerce value to int, returning 0 for None/empty values.""" + if value in (None, ""): + return 0 + + try: + return int(value) + except (ValueError, TypeError): + return 0 + + +# Annotated types for cleaner field definitions +StringField = Annotated[str, BeforeValidator(coerce_to_string)] +IntField = Annotated[int, BeforeValidator(coerce_to_int)] + + class WebrcadeFeedItemPropsSchema(TypedDict): rom: str @@ -105,22 +128,28 @@ class TinfoilFeedFileSchema(TypedDict): size: int -class TinfoilFeedTitleDBSchema(TypedDict): - id: str - name: str - version: int - region: str - releaseDate: int - rating: int - publisher: str - description: str - size: int - rank: int +class TinfoilFeedTitleDBSchema(BaseModel): + """Schema for Tinfoil feed title database entries. + + This schema handles the conversion and validation of game metadata + for the Tinfoil custom index format. + """ + + id: StringField = Field(default="") + name: StringField = Field(default="") + description: StringField = Field(default="") + region: StringField = Field(default="US") + publisher: StringField = Field(default="") + size: IntField = Field(default=0, ge=0) + version: IntField = Field(default=0, ge=0) + releaseDate: IntField = Field(default=19700101, ge=19700101) + rating: IntField = Field(default=0, ge=0, le=100) + rank: IntField = Field(default=0, ge=0) class TinfoilFeedSchema(TypedDict): files: list[TinfoilFeedFileSchema] directories: list[str] - titledb: NotRequired[dict[str, TinfoilFeedTitleDBSchema]] + titledb: NotRequired[dict[str, dict]] # dict after .model_dump() success: NotRequired[str] error: NotRequired[str] diff --git a/backend/endpoints/rom.py b/backend/endpoints/rom.py index 1d6edb2b9..355b28fc6 100644 --- a/backend/endpoints/rom.py +++ b/backend/endpoints/rom.py @@ -987,6 +987,66 @@ async def add_rom_manuals( return Response() +@protected_route( + router.delete, + "/{id}/manuals", + [Scope.ROMS_WRITE], + responses={status.HTTP_404_NOT_FOUND: {}}, +) +async def delete_rom_manuals( + request: Request, + id: Annotated[int, PathVar(description="Rom internal id.", ge=1)], +) -> Response: + """Delete manuals for a rom.""" + + rom = db_rom_handler.get_rom(id) + if not rom: + raise RomNotFoundInDatabaseException(id) + + if not fs_resource_handler.manual_exists(rom): + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="No manual found for this ROM", + ) + + try: + await fs_resource_handler.remove_manual(rom) + db_rom_handler.update_rom( + id, + { + "path_manual": "", + "url_manual": "", + }, + ) + + log.info( + f"Deleted manual for {hl(rom.name or 'ROM', color=BLUE)} [{hl(rom.fs_name)}]" + ) + except FileNotFoundError: + log.warning( + f"Manual file not found for {hl(rom.name or 'ROM', color=BLUE)} [{hl(rom.fs_name)}]" + ) + # Still update the database even if file doesn't exist + db_rom_handler.update_rom( + id, + { + "path_manual": "", + "url_manual": "", + }, + ) + except Exception as exc: + log.error( + f"Error deleting manual for {hl(rom.name or 'ROM', color=BLUE)} [{hl(rom.fs_name)}]", + exc_info=exc, + ) + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="There was an error deleting the manual", + ) from exc + + return Response() + + @protected_route( router.post, "/delete", diff --git a/backend/handler/filesystem/resources_handler.py b/backend/handler/filesystem/resources_handler.py index f373125bb..5b8f1e5ff 100644 --- a/backend/handler/filesystem/resources_handler.py +++ b/backend/handler/filesystem/resources_handler.py @@ -335,6 +335,9 @@ class FSResourcesHandler(FSHandler): path_manual = self._get_manual_path(rom) if manual_exists else None return path_manual + async def remove_manual(self, rom: Rom): + await self.remove_directory(f"{rom.fs_resources_path}/manual") + async def store_ra_badge(self, url: str, path: str) -> None: httpx_client = ctx_httpx_client.get() directory, filename = os.path.split(path) diff --git a/backend/handler/metadata/fixtures/hltb_api_url b/backend/handler/metadata/fixtures/hltb_api_url new file mode 100644 index 000000000..a006734f3 --- /dev/null +++ b/backend/handler/metadata/fixtures/hltb_api_url @@ -0,0 +1 @@ +https://howlongtobeat.com/api/locate/5d6cf2e5eb308ba8 diff --git a/backend/handler/metadata/hltb_handler.py b/backend/handler/metadata/hltb_handler.py index 298220a35..210e7738d 100644 --- a/backend/handler/metadata/hltb_handler.py +++ b/backend/handler/metadata/hltb_handler.py @@ -164,6 +164,9 @@ def extract_hltb_metadata(game: HLTBGame) -> HLTBMetadata: return metadata +GITHUB_FILE_URL = "https://raw.githubusercontent.com/rommapp/romm/refs/heads/master/backend/handler/metadata/fixtures/hltb_api_url" + + class HowLongToBeatHandler(MetadataHandler): """ Handler for HowLongToBeat, a service that provides game completion times. @@ -172,13 +175,29 @@ class HowLongToBeatHandler(MetadataHandler): def __init__(self) -> None: self.base_url = "https://howlongtobeat.com" self.user_endpoint = f"{self.base_url}/api/user" - self.search_url = f"{self.base_url}/api/seek/791cd10c5e8e894c" + self.search_url = f"{self.base_url}/api/search" self.min_similarity_score: Final = 0.85 + # HLTB rotates their search endpoint regularly + self.fetch_search_endpoint() + @classmethod def is_enabled(cls) -> bool: return HLTB_API_ENABLED + def fetch_search_endpoint(self): + """Fetch the API endpoint URL from Github.""" + if not HLTB_API_ENABLED: + return + + try: + with httpx.Client() as client: + response = client.get(GITHUB_FILE_URL, timeout=10) + response.raise_for_status() + self.search_url = response.text.strip() + except Exception as e: + log.warning("Unexpected error fetching HLTB endpoint from GitHub: %s", e) + async def heartbeat(self) -> bool: if not self.is_enabled(): return False diff --git a/backend/main.py b/backend/main.py index 3e7eddbc8..a4058b5db 100644 --- a/backend/main.py +++ b/backend/main.py @@ -19,6 +19,7 @@ from config import ( DEV_PORT, DISABLE_CSRF_PROTECTION, IS_PYTEST_RUN, + OIDC_ENABLED, ROMM_AUTH_SECRET_KEY, SENTRY_DSN, ) @@ -105,7 +106,7 @@ app.add_middleware( SessionMiddleware, secret_key=ROMM_AUTH_SECRET_KEY, session_cookie="romm_session", - same_site="strict", + same_site="lax" if OIDC_ENABLED else "strict", https_only=False, jwt_alg=ALGORITHM, ) diff --git a/backend/utils/archive_7zip.py b/backend/utils/archive_7zip.py index 35f752da9..7900c7096 100644 --- a/backend/utils/archive_7zip.py +++ b/backend/utils/archive_7zip.py @@ -5,6 +5,7 @@ import tempfile from collections.abc import Callable from pathlib import Path +from config import ROMM_TMP_PATH from logger.logger import log SEVEN_ZIP_PATH = "/usr/bin/7zz" @@ -60,7 +61,7 @@ def process_file_7z( if not largest_file: return False - with tempfile.TemporaryDirectory() as temp_dir: + with tempfile.TemporaryDirectory(dir=ROMM_TMP_PATH) as temp_dir: log.debug(f"Extracting {largest_file} from {file_path}...") temp_path = Path(temp_dir) diff --git a/docker/init_scripts/docker-entrypoint.sh b/docker/init_scripts/docker-entrypoint.sh index 2aa602268..71d3e8373 100755 --- a/docker/init_scripts/docker-entrypoint.sh +++ b/docker/init_scripts/docker-entrypoint.sh @@ -39,6 +39,13 @@ done export ROMM_BASE_PATH=${ROMM_BASE_PATH:-/romm} export ROMM_PORT=${ROMM_PORT:-8080} +# Set IPV6_LISTEN based on IPV4_ONLY +if [[ ${IPV4_ONLY} == "true" ]]; then + export IPV6_LISTEN="#listen [::]:${ROMM_PORT};" +else + export IPV6_LISTEN="listen [::]:${ROMM_PORT};" +fi + # Replace environment variables used in nginx configuration templates. /docker-entrypoint.d/20-envsubst-on-templates.sh >/dev/null diff --git a/docker/nginx/templates/default.conf.template b/docker/nginx/templates/default.conf.template index 8f8e56deb..8ab4e85dd 100644 --- a/docker/nginx/templates/default.conf.template +++ b/docker/nginx/templates/default.conf.template @@ -23,7 +23,7 @@ map $request_uri $coop_header { server { root /var/www/html; listen ${ROMM_PORT}; - listen [::]:${ROMM_PORT}; + ${IPV6_LISTEN} server_name localhost; proxy_set_header Host $http_host; diff --git a/env.template b/env.template index 82bfc9e8e..5d6f485ff 100644 --- a/env.template +++ b/env.template @@ -1,4 +1,5 @@ ROMM_BASE_PATH=/path/to/romm_mock +ROMM_TMP_PATH= KIOSK_MODE=false # IGDB credentials @@ -113,6 +114,7 @@ WEB_SERVER_KEEPALIVE=2 WEB_SERVER_MAX_REQUESTS=1000 WEB_SERVER_MAX_REQUESTS_JITTER=100 WEB_SERVER_WORKER_CONNECTIONS=1000 +IPV4_ONLY=false # Development only DEV_MODE=true diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 464324af7..a0777596d 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -2636,9 +2636,9 @@ "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==" }, "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.25", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", - "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", "devOptional": true, "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", @@ -4806,9 +4806,9 @@ "license": "MIT" }, "node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", "devOptional": true, "dependencies": { "ms": "^2.1.3" diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 506697838..0a2d0fc64 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -79,7 +79,6 @@ export type { TasksDict } from './models/TasksDict'; export type { TaskStatusResponse } from './models/TaskStatusResponse'; export type { TinfoilFeedFileSchema } from './models/TinfoilFeedFileSchema'; export type { TinfoilFeedSchema } from './models/TinfoilFeedSchema'; -export type { TinfoilFeedTitleDBSchema } from './models/TinfoilFeedTitleDBSchema'; export type { TokenResponse } from './models/TokenResponse'; export type { UserCollectionSchema } from './models/UserCollectionSchema'; export type { UserForm } from './models/UserForm'; diff --git a/frontend/src/__generated__/models/TinfoilFeedSchema.ts b/frontend/src/__generated__/models/TinfoilFeedSchema.ts index 7e7e9cf19..bfddc1698 100644 --- a/frontend/src/__generated__/models/TinfoilFeedSchema.ts +++ b/frontend/src/__generated__/models/TinfoilFeedSchema.ts @@ -3,11 +3,10 @@ /* tslint:disable */ /* eslint-disable */ import type { TinfoilFeedFileSchema } from './TinfoilFeedFileSchema'; -import type { TinfoilFeedTitleDBSchema } from './TinfoilFeedTitleDBSchema'; export type TinfoilFeedSchema = { files: Array; directories: Array; - titledb?: Record; + titledb?: Record>; success?: string; error?: string; }; diff --git a/frontend/src/__generated__/models/TinfoilFeedTitleDBSchema.ts b/frontend/src/__generated__/models/TinfoilFeedTitleDBSchema.ts deleted file mode 100644 index 6d42547a9..000000000 --- a/frontend/src/__generated__/models/TinfoilFeedTitleDBSchema.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* generated using openapi-typescript-codegen -- do not edit */ -/* istanbul ignore file */ -/* tslint:disable */ -/* eslint-disable */ -export type TinfoilFeedTitleDBSchema = { - id: string; - name: string; - version: number; - region: string; - releaseDate: number; - rating: number; - publisher: string; - description: string; - size: number; - rank: number; -}; - diff --git a/frontend/src/components/Settings/UserInterface/Interface.vue b/frontend/src/components/Settings/UserInterface/Interface.vue index a38396e7f..425d00541 100644 --- a/frontend/src/components/Settings/UserInterface/Interface.vue +++ b/frontend/src/components/Settings/UserInterface/Interface.vue @@ -46,6 +46,10 @@ const statusRef = useLocalStorage("settings.showStatus", true); const actionBarRef = useLocalStorage("settings.showActionBar", false); const gameTitleRef = useLocalStorage("settings.showGameTitle", false); const enable3DEffectRef = useLocalStorage("settings.enable3DEffect", false); +const enableExperimentalCacheRef = useLocalStorage( + "settings.enableExperimentalCache", + false, +); const homeOptions = computed(() => [ { @@ -167,6 +171,14 @@ const galleryOptions = computed(() => [ model: gameTitleRef, modelTrigger: toggleShowGameTitles, }, + { + title: t("settings.enable-experimental-cache"), + description: t("settings.enable-experimental-cache-desc"), + iconEnabled: "mdi-cached", + iconDisabled: "mdi-cached", + model: enableExperimentalCacheRef, + modelTrigger: toggleExperimentalCache, + }, ]); const setPlatformDrawerGroupBy = (value: string) => { @@ -226,6 +238,9 @@ const toggle3DEffect = (value: boolean) => { const toggleShowGameTitles = (value: boolean) => { gameTitleRef.value = value; }; +const toggleExperimentalCache = (value: boolean) => { + enableExperimentalCacheRef.value = value; +}; + + + + + diff --git a/frontend/src/components/common/Navigation/SettingsDrawer.vue b/frontend/src/components/common/Navigation/SettingsDrawer.vue index 57327d25d..e2300952f 100644 --- a/frontend/src/components/common/Navigation/SettingsDrawer.vue +++ b/frontend/src/components/common/Navigation/SettingsDrawer.vue @@ -67,7 +67,7 @@ function onClose() { v-model="activeSettingsDrawer" mobile :location="smAndDown ? 'top' : 'left'" - width="450" + :width="smAndDown ? 500 : 400" :class="{ 'my-2': mdAndUp || (smAndDown && activeSettingsDrawer), 'ml-2': (mdAndUp && activeSettingsDrawer) || smAndDown, diff --git a/frontend/src/console/views/GamesList.vue b/frontend/src/console/views/GamesList.vue index 801bbee25..7c77c3e9f 100644 --- a/frontend/src/console/views/GamesList.vue +++ b/frontend/src/console/views/GamesList.vue @@ -23,13 +23,19 @@ import { useSpatialNav } from "@/console/composables/useSpatialNav"; import type { InputAction } from "@/console/input/actions"; import { ROUTES } from "@/plugins/router"; import collectionApi from "@/services/api/collection"; -import romApi from "@/services/api/rom"; -import consoleStore from "@/stores/console"; -import type { SimpleRom } from "@/stores/roms"; +import storeCollections from "@/stores/collections"; +import storeConsole from "@/stores/console"; +import storeGalleryFilter from "@/stores/galleryFilter"; +import storePlatforms from "@/stores/platforms"; +import storeRoms, { type SimpleRom } from "@/stores/roms"; const route = useRoute(); const router = useRouter(); -const storeConsole = consoleStore(); +const consoleStore = storeConsole(); +const platformsStore = storePlatforms(); +const collectionsStore = storeCollections(); +const galleryFilterStore = storeGalleryFilter(); +const romsStore = storeRoms(); const { toggleFavorite: toggleFavoriteComposable } = useFavoriteToggle(); const { setSelectedBackgroundArt, clearSelectedBackgroundArt } = useBackgroundArt(); @@ -65,13 +71,13 @@ const gridRef = useTemplateRef("game-grid-ref"); // Initialize selection from store if (platformId != null) { - selectedIndex.value = storeConsole.getPlatformGameIndex(platformId); + selectedIndex.value = consoleStore.getPlatformGameIndex(platformId); } else if (collectionId != null) { - selectedIndex.value = storeConsole.getCollectionGameIndex(collectionId); + selectedIndex.value = consoleStore.getCollectionGameIndex(collectionId); } else if (smartCollectionId != null) { - selectedIndex.value = storeConsole.getCollectionGameIndex(smartCollectionId); + selectedIndex.value = consoleStore.getCollectionGameIndex(smartCollectionId); } else if (virtualCollectionId != null) { - selectedIndex.value = storeConsole.getCollectionGameIndex( + selectedIndex.value = consoleStore.getCollectionGameIndex( Number(virtualCollectionId), ); } @@ -106,13 +112,13 @@ const letters = computed(() => { function persistIndex() { if (platformId != null) { - storeConsole.setPlatformGameIndex(platformId, selectedIndex.value); + consoleStore.setPlatformGameIndex(platformId, selectedIndex.value); } else if (collectionId != null) { - storeConsole.setCollectionGameIndex(collectionId, selectedIndex.value); + consoleStore.setCollectionGameIndex(collectionId, selectedIndex.value); } else if (smartCollectionId != null) { - storeConsole.setCollectionGameIndex(smartCollectionId, selectedIndex.value); + consoleStore.setCollectionGameIndex(smartCollectionId, selectedIndex.value); } else if (virtualCollectionId != null) { - storeConsole.setCollectionGameIndex( + consoleStore.setCollectionGameIndex( Number(virtualCollectionId), selectedIndex.value, ); @@ -313,46 +319,47 @@ let off: (() => void) | null = null; onMounted(async () => { try { if (platformId != null) { - const { data } = await romApi.getRoms({ - platformId: platformId, - limit: 500, - orderBy: "name", - orderDir: "asc", - }); - roms.value = data.items ?? []; + const currentPlatform = platformsStore.get(platformId); + if (currentPlatform) romsStore.setCurrentPlatform(currentPlatform); } else if (collectionId != null) { - const { data } = await romApi.getRoms({ - collectionId: collectionId, - limit: 500, - orderBy: "name", - orderDir: "asc", - }); - roms.value = data.items ?? []; + const currentCollection = collectionsStore.getCollection(collectionId); + if (currentCollection) romsStore.setCurrentCollection(currentCollection); + } else if (smartCollectionId != null) { + const currentSmartCollection = + collectionsStore.getSmartCollection(smartCollectionId); + if (currentSmartCollection) + romsStore.setCurrentSmartCollection(currentSmartCollection); + } else if (virtualCollectionId != null) { + const currentVirtualCollection = + collectionsStore.getVirtualCollection(virtualCollectionId); + if (currentVirtualCollection) + romsStore.setCurrentVirtualCollection(currentVirtualCollection); + } + + romsStore.setLimit(500); + romsStore.setOrderBy("name"); + romsStore.setOrderDir("asc"); + romsStore.resetPagination(); + + const fetchedRoms = await romsStore.fetchRoms({ + galleryFilter: galleryFilterStore, + concat: false, + }); + roms.value = fetchedRoms; + + if (collectionId != null) { const { data: col } = await collectionApi.getCollection(collectionId); collection.value = col ?? null; } else if (smartCollectionId != null) { - const { data } = await romApi.getRoms({ - smartCollectionId: smartCollectionId, - limit: 500, - orderBy: "name", - orderDir: "asc", - }); - roms.value = data.items ?? []; const { data: smartCol } = await collectionApi.getSmartCollection(smartCollectionId); smartCollection.value = smartCol ?? null; } else if (virtualCollectionId != null) { - const { data } = await romApi.getRoms({ - virtualCollectionId: virtualCollectionId, - limit: 500, - orderBy: "name", - orderDir: "asc", - }); - roms.value = data.items ?? []; const { data: virtualCol } = await collectionApi.getVirtualCollection(virtualCollectionId); virtualCollection.value = virtualCol ?? null; } + for (const r of roms.value) { if (!r.url_cover && !r.path_cover_large && !r.path_cover_small) { loadedMap.value[r.id] = true; diff --git a/frontend/src/console/views/Home.vue b/frontend/src/console/views/Home.vue index dc324112b..66a2656e7 100644 --- a/frontend/src/console/views/Home.vue +++ b/frontend/src/console/views/Home.vue @@ -36,15 +36,24 @@ import type { InputAction } from "@/console/input/actions"; import { ROUTES } from "@/plugins/router"; import collectionApi from "@/services/api/collection"; import platformApi from "@/services/api/platform"; -import romApi from "@/services/api/rom"; import storeCollections from "@/stores/collections"; -import consoleStore from "@/stores/console"; +import storeConsole from "@/stores/console"; +import storeRoms from "@/stores/roms"; import type { SimpleRom } from "@/stores/roms"; const router = useRouter(); const collectionsStore = storeCollections(); -const storeConsole = consoleStore(); -const { navigationMode } = storeToRefs(storeConsole); +const consoleStore = storeConsole(); +const romsStore = storeRoms(); +const { + navigationMode, + platformIndex, + recentIndex, + collectionsIndex, + smartCollectionsIndex, + virtualCollectionsIndex, + controlIndex, +} = storeToRefs(consoleStore); const { toggleFavorite: toggleFavoriteComposable } = useFavoriteToggle(); const { setSelectedBackgroundArt, clearSelectedBackgroundArt } = useBackgroundArt(); @@ -60,12 +69,6 @@ const errorMessage = ref(""); const showSettings = ref(false); // Navigation indices -const platformIndex = ref(storeConsole.platformIndex); -const recentIndex = ref(storeConsole.recentIndex); -const collectionsIndex = ref(storeConsole.collectionsIndex); -const smartCollectionsIndex = ref(storeConsole.smartCollectionsIndex); -const virtualCollectionsIndex = ref(storeConsole.virtualCollectionsIndex); -const controlIndex = ref(storeConsole.controlIndex); const scrollContainerRef = useTemplateRef( "scroll-container-ref", ); @@ -625,13 +628,13 @@ onMounted(async () => { try { const [ { data: plats }, - { data: recents }, + recents, { data: cols }, { data: smartCols }, { data: virtualCols }, ] = await Promise.all([ platformApi.getPlatforms(), - romApi.getRecentPlayedRoms(), + romsStore.fetchRecentRoms(), collectionApi.getCollections(), collectionApi.getSmartCollections(), collectionApi.getVirtualCollections({ type: "collection" }), @@ -640,7 +643,7 @@ onMounted(async () => { platforms.value = plats.filter( (p) => p.rom_count > 0 && isSupportedPlatform(p.slug), ); - recentRoms.value = recents.items ?? []; + recentRoms.value = recents ?? []; collections.value = cols ?? []; smartCollections.value = smartCols ?? []; virtualCollections.value = virtualCols ?? []; @@ -692,7 +695,7 @@ onMounted(async () => { let off: (() => void) | null = null; onUnmounted(() => { - storeConsole.setHomeState({ + consoleStore.setHomeState({ platformIndex: platformIndex.value, recentIndex: recentIndex.value, collectionsIndex: collectionsIndex.value, diff --git a/frontend/src/locales/de_DE/settings.json b/frontend/src/locales/de_DE/settings.json index 075ab1bab..1ebde20e5 100644 --- a/frontend/src/locales/de_DE/settings.json +++ b/frontend/src/locales/de_DE/settings.json @@ -5,6 +5,8 @@ "email": "E-Mail", "enable-3d-effect": "3D-Effekt aktivieren", "enable-3d-effect-desc": "3D-Effekt für die Spiel-/Plattform-/Sammlungskarten aktivieren", + "enable-experimental-cache": "Experimentellen Request-Cache aktivieren", + "enable-experimental-cache-desc": "Experimentelles Request-Caching zur Leistungsverbesserung aktivieren (kann Probleme verursachen)", "excluded": "Ausnahmen", "excluded-multi-rom-files": "Unterverzeichnisse in Plattform-Verzeichnissen", "excluded-multi-rom-parts-extensions": "Dateiendungen in Unterverzeichnisse in Plattform-Verzeichnissen", diff --git a/frontend/src/locales/en_GB/collection.json b/frontend/src/locales/en_GB/collection.json index 429331ec4..36921cced 100644 --- a/frontend/src/locales/en_GB/collection.json +++ b/frontend/src/locales/en_GB/collection.json @@ -12,7 +12,7 @@ "private": "Private", "private-desc": "Private (only visible to me)", "public": "Public", - "public-desc": "Pubilc (visible to everyone)", + "public-desc": "Public (visible to everyone)", "removing-collection-1": "Removing collection", "removing-collection-2": "from RomM. Do you confirm?", "removing-smart-collection-1": "Removing smart collection", diff --git a/frontend/src/locales/en_GB/settings.json b/frontend/src/locales/en_GB/settings.json index 0fd9a2603..2871fd49b 100644 --- a/frontend/src/locales/en_GB/settings.json +++ b/frontend/src/locales/en_GB/settings.json @@ -5,6 +5,8 @@ "email": "Email", "enable-3d-effect": "Enable 3D effect", "enable-3d-effect-desc": "Enable 3D effect for the game/platform/collection cards", + "enable-experimental-cache": "Enable experimental request cache", + "enable-experimental-cache-desc": "Enable experimental request caching to improve performance (may cause issues)", "excluded": "Excluded", "excluded-multi-rom-files": "Multi rom files", "excluded-multi-rom-parts-extensions": "Multi rom parts extensions", diff --git a/frontend/src/locales/en_US/collection.json b/frontend/src/locales/en_US/collection.json index 429331ec4..36921cced 100644 --- a/frontend/src/locales/en_US/collection.json +++ b/frontend/src/locales/en_US/collection.json @@ -12,7 +12,7 @@ "private": "Private", "private-desc": "Private (only visible to me)", "public": "Public", - "public-desc": "Pubilc (visible to everyone)", + "public-desc": "Public (visible to everyone)", "removing-collection-1": "Removing collection", "removing-collection-2": "from RomM. Do you confirm?", "removing-smart-collection-1": "Removing smart collection", diff --git a/frontend/src/locales/en_US/settings.json b/frontend/src/locales/en_US/settings.json index 0fd9a2603..2871fd49b 100644 --- a/frontend/src/locales/en_US/settings.json +++ b/frontend/src/locales/en_US/settings.json @@ -5,6 +5,8 @@ "email": "Email", "enable-3d-effect": "Enable 3D effect", "enable-3d-effect-desc": "Enable 3D effect for the game/platform/collection cards", + "enable-experimental-cache": "Enable experimental request cache", + "enable-experimental-cache-desc": "Enable experimental request caching to improve performance (may cause issues)", "excluded": "Excluded", "excluded-multi-rom-files": "Multi rom files", "excluded-multi-rom-parts-extensions": "Multi rom parts extensions", diff --git a/frontend/src/locales/es_ES/settings.json b/frontend/src/locales/es_ES/settings.json index 465b32d21..7fed0ab48 100644 --- a/frontend/src/locales/es_ES/settings.json +++ b/frontend/src/locales/es_ES/settings.json @@ -5,6 +5,8 @@ "email": "Correo electrónico", "enable-3d-effect": "Habilitar efecto 3D", "enable-3d-effect-desc": "Habilitar efecto 3D para las tarjetas de juego/plataforma/colección", + "enable-experimental-cache": "Habilitar caché experimental de peticiones", + "enable-experimental-cache-desc": "Habilitar caché experimental de peticiones para mejorar el rendimiento (puede causar problemas)", "excluded": "Exclusiones", "excluded-multi-rom-files": "Roms multi fichero", "excluded-multi-rom-parts-extensions": "Extensiones de partes de roms multi fichero", diff --git a/frontend/src/locales/fr_FR/settings.json b/frontend/src/locales/fr_FR/settings.json index 14936e811..87b5fa93d 100644 --- a/frontend/src/locales/fr_FR/settings.json +++ b/frontend/src/locales/fr_FR/settings.json @@ -5,6 +5,8 @@ "email": "E-mail", "enable-3d-effect": "Activer l'effet 3D", "enable-3d-effect-desc": "Activer l'effet 3D pour les cartes de jeu/plateforme/collection", + "enable-experimental-cache": "Activer le cache de requêtes expérimental", + "enable-experimental-cache-desc": "Activer la mise en cache expérimentale des requêtes pour améliorer les performances (peut causer des problèmes)", "excluded": "Exclu", "excluded-multi-rom-files": "Fichiers de rom multiples", "excluded-multi-rom-parts-extensions": "Extensions de parties de rom multiples", diff --git a/frontend/src/locales/it_IT/settings.json b/frontend/src/locales/it_IT/settings.json index 5efb2c893..a7c8a4b10 100644 --- a/frontend/src/locales/it_IT/settings.json +++ b/frontend/src/locales/it_IT/settings.json @@ -5,6 +5,8 @@ "email": "Email", "enable-3d-effect": "Abilita effetto 3D", "enable-3d-effect-desc": "Abilita l'effetto 3D per le schede di gioco, piattaforma e collezione", + "enable-experimental-cache": "Abilita cache sperimentale delle richieste", + "enable-experimental-cache-desc": "Abilita la cache sperimentale delle richieste per migliorare le prestazioni (può causare problemi)", "excluded": "Escluso", "excluded-multi-rom-files": "File rom multiple", "excluded-multi-rom-parts-extensions": "Estensioni parti di rom multiple", diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index 3ef57d951..4a8f2ae8f 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -5,6 +5,8 @@ "email": "メール", "enable-3d-effect": "3D効果を有効化", "enable-3d-effect-desc": "ゲーム・プラットフォーム・コレクションカードに3D効果を有効化する", + "enable-experimental-cache": "実験的リクエストキャッシュを有効化", + "enable-experimental-cache-desc": "パフォーマンス向上のための実験的リクエストキャッシュを有効化(問題を引き起こす可能性があります)", "excluded": "除外", "excluded-multi-rom-files": "複数ファイル", "excluded-multi-rom-parts-extensions": "複数ファイルの拡張子", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index 10daceef1..c4af47e25 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -5,6 +5,8 @@ "email": "이메일", "enable-3d-effect": "3D 효과 활성화", "enable-3d-effect-desc": "게임/플랫폼/모음집 카드에 3D 효과를 활성화합니다", + "enable-experimental-cache": "실험적 요청 캐시 활성화", + "enable-experimental-cache-desc": "성능 향상을 위한 실험적 요청 캐시를 활성화합니다 (문제를 일으킬 수 있음)", "excluded": "제외됨", "excluded-multi-rom-files": "멀티 롬 파일", "excluded-multi-rom-parts-extensions": "멀티 롬 부분 확장자", diff --git a/frontend/src/locales/pl_PL/settings.json b/frontend/src/locales/pl_PL/settings.json index 06b7aa094..221199321 100644 --- a/frontend/src/locales/pl_PL/settings.json +++ b/frontend/src/locales/pl_PL/settings.json @@ -5,6 +5,8 @@ "edit-user": "Edytuj użytkownika", "enable-3d-effect": "Włącz efekt 3D", "enable-3d-effect-desc": "Włącz efekt 3D dla kart gier/platform/kolekcji", + "enable-experimental-cache": "Włącz eksperymentalne buforowanie żądań", + "enable-experimental-cache-desc": "Włącz eksperymentalne buforowanie żądań w celu poprawy wydajności (może powodować problemy)", "excluded": "Wykluczone", "excluded-multi-rom-files": "Pliki multi-ROM", "excluded-multi-rom-parts-extensions": "Rozszerzenia części multi-ROM", diff --git a/frontend/src/locales/pt_BR/settings.json b/frontend/src/locales/pt_BR/settings.json index dcbb3d24d..c360bbdf6 100644 --- a/frontend/src/locales/pt_BR/settings.json +++ b/frontend/src/locales/pt_BR/settings.json @@ -5,6 +5,8 @@ "email": "E-mail", "enable-3d-effect": "Ativar efeito 3D", "enable-3d-effect-desc": "Ativar efeito 3D para os cartões de jogo, plataforma e coleção", + "enable-experimental-cache": "Ativar cache experimental de requisições", + "enable-experimental-cache-desc": "Ativar cache experimental de requisições para melhorar o desempenho (pode causar problemas)", "excluded": "Excluído", "excluded-multi-rom-files": "Arquivos de rom múltiplos", "excluded-multi-rom-parts-extensions": "Extensões de partes de rom múltiplos", diff --git a/frontend/src/locales/ro_RO/settings.json b/frontend/src/locales/ro_RO/settings.json index 1d7bc29e9..72451350f 100644 --- a/frontend/src/locales/ro_RO/settings.json +++ b/frontend/src/locales/ro_RO/settings.json @@ -5,6 +5,8 @@ "edit-user": "Editează utilizatorul", "enable-3d-effect": "Activează efectul 3D", "enable-3d-effect-desc": "Activează efectul 3D pentru cardurile de joc, platformă și colecție", + "enable-experimental-cache": "Activează cache-ul experimental de cereri", + "enable-experimental-cache-desc": "Activează cache-ul experimental de cereri pentru a îmbunătăți performanța (poate cauza probleme)", "excluded": "Exclus", "excluded-multi-rom-files": "Fișiere rom multiple", "excluded-multi-rom-parts-extensions": "Extensii părți rom multiple", diff --git a/frontend/src/locales/ru_RU/settings.json b/frontend/src/locales/ru_RU/settings.json index 99ca650fe..b9165c9c6 100644 --- a/frontend/src/locales/ru_RU/settings.json +++ b/frontend/src/locales/ru_RU/settings.json @@ -5,6 +5,8 @@ "email": "Электронная почта", "enable-3d-effect": "Включить 3D-эффект", "enable-3d-effect-desc": "Включить 3D-эффект для карточек игр, платформ и коллекций", + "enable-experimental-cache": "Включить экспериментальное кэширование запросов", + "enable-experimental-cache-desc": "Включить экспериментальное кэширование запросов для повышения производительности (может вызвать проблемы)", "excluded": "Исключено", "excluded-multi-rom-files": "Многосоставные файлы ромов", "excluded-multi-rom-parts-extensions": "Расширения частей многосоставных ромов", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index 397647353..b3d0007e5 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -5,6 +5,8 @@ "email": "电子邮件", "enable-3d-effect": "启用 3D 效果", "enable-3d-effect-desc": "为游戏、平台和收藏卡片启用 3D 效果", + "enable-experimental-cache": "启用实验性请求缓存", + "enable-experimental-cache-desc": "启用实验性请求缓存以提高性能(可能会引起问题)", "excluded": "排除", "excluded-multi-rom-files": "多个 Rom 文件", "excluded-multi-rom-parts-extensions": "多个 Rom 部分扩展", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index 4075c6129..3384e1529 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -5,6 +5,8 @@ "email": "電子郵件", "enable-3d-effect": "啟用 3D 效果", "enable-3d-effect-desc": "為遊戲、平台及收藏卡片啟用 3D 效果", + "enable-experimental-cache": "啟用實驗性請求快取", + "enable-experimental-cache-desc": "啟用實驗性請求快取以提升效能(可能會引起問題)", "excluded": "排除", "excluded-multi-rom-files": "多個 Rom 檔名", "excluded-multi-rom-parts-extensions": "多個 Rom 部分副檔名", diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index 3252db2dc..acc3265a3 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -303,7 +303,6 @@ async function uploadManuals({ const heartbeat = storeHeartbeat(); const uploadStore = storeUpload(); - console.log(filesToUpload); const promises = filesToUpload.map((file) => { const formData = new FormData(); formData.append(file.name, file); @@ -333,6 +332,14 @@ async function uploadManuals({ return Promise.allSettled(promises); } +async function removeManual({ + romId, +}: { + romId: number; +}): Promise<{ data: DetailedRom }> { + return api.delete(`/roms/${romId}/manuals`); +} + async function updateUserRomProps({ romId, data, @@ -375,6 +382,7 @@ export default { searchRom, updateRom, uploadManuals, + removeManual, updateUserRomProps, deleteRoms, }; diff --git a/frontend/src/services/cache/api.ts b/frontend/src/services/cache/api.ts new file mode 100644 index 000000000..99da1495f --- /dev/null +++ b/frontend/src/services/cache/api.ts @@ -0,0 +1,123 @@ +// trunk-ignore-all(eslint/@typescript-eslint/no-explicit-any) +import type { + AxiosRequestConfig, + AxiosResponse, + AxiosHeaders, + Method, +} from "axios"; +import type { CustomLimitOffsetPage_SimpleRomSchema_ as GetRomsResponse } from "@/__generated__/models/CustomLimitOffsetPage_SimpleRomSchema_"; +import type { GetRomsParams } from "@/services/api/rom"; +import cacheService from "@/services/cache"; +import { getStatusKeyForText } from "@/utils"; + +class CachedApiService { + private createRequestConfig( + method: Method, + url: string, + params?: any, + headers?: AxiosHeaders, + ): AxiosRequestConfig { + return { + method, + url, + params, + headers, + }; + } + + async getRoms( + params: GetRomsParams, + onBackgroundUpdate: (data: GetRomsResponse) => void, + ): Promise> { + const config = this.createRequestConfig("GET", "/roms", { + platform_id: params.platformId, + collection_id: params.collectionId, + virtual_collection_id: params.virtualCollectionId, + smart_collection_id: params.smartCollectionId, + search_term: params.searchTerm, + limit: params.limit, + offset: params.offset, + order_by: params.orderBy, + order_dir: params.orderDir, + group_by_meta_id: params.groupByMetaId, + selected_genre: params.selectedGenre, + selected_franchise: params.selectedFranchise, + selected_collection: params.selectedCollection, + selected_company: params.selectedCompany, + selected_age_rating: params.selectedAgeRating, + selected_status: getStatusKeyForText(params.selectedStatus ?? null), + selected_region: params.selectedRegion, + selected_language: params.selectedLanguage, + ...(params.filterUnmatched ? { matched: false } : {}), + ...(params.filterMatched ? { matched: true } : {}), + ...(params.filterFavourites ? { favourite: true } : {}), + ...(params.filterDuplicates ? { duplicate: true } : {}), + ...(params.filterPlayables ? { playable: true } : {}), + ...(params.filterMissing ? { missing: true } : {}), + ...(params.filterRA ? { has_ra: true } : {}), + ...(params.filterVerified ? { verified: true } : {}), + }); + + return cacheService.request(config, onBackgroundUpdate); + } + + async getRecentRoms( + onBackgroundUpdate: (data: GetRomsResponse) => void, + ): Promise> { + const config = this.createRequestConfig("GET", "/roms", { + order_by: "id", + order_dir: "desc", + limit: 15, + with_char_index: false, + }); + + return cacheService.request(config, onBackgroundUpdate); + } + + async getRecentPlayedRoms( + onBackgroundUpdate: (data: GetRomsResponse) => void, + ): Promise> { + const config = this.createRequestConfig("GET", "/roms", { + order_by: "last_played", + order_dir: "desc", + limit: 15, + with_char_index: false, + }); + + return cacheService.request(config, onBackgroundUpdate); + } + + private async clearRomsCache(params: any) { + const queryString = params ? new URLSearchParams(params).toString() : ""; + await cacheService.clearCacheForPattern(`/roms?${queryString}`); + } + + async clearRecentRomsCache() { + await this.clearRomsCache({ + order_by: "id", + order_dir: "desc", + limit: 15, + with_char_index: false, + }); + } + + async clearRecentPlayedRomsCache() { + await this.clearRomsCache({ + order_by: "last_played", + order_dir: "desc", + limit: 15, + with_char_index: false, + }); + } + + // Cache management methods + async clearCache() { + return cacheService.clearCache(); + } + + async getCacheSize() { + return cacheService.getCacheSize(); + } +} + +export default new CachedApiService(); diff --git a/frontend/src/services/cache/index.ts b/frontend/src/services/cache/index.ts new file mode 100644 index 000000000..86c3850cf --- /dev/null +++ b/frontend/src/services/cache/index.ts @@ -0,0 +1,185 @@ +// trunk-ignore-all(eslint/@typescript-eslint/no-explicit-any) +import { useLocalStorage } from "@vueuse/core"; +import type { AxiosRequestConfig, AxiosResponse } from "axios"; +import api from "@/services/api"; + +interface CacheEntry { + data: unknown; +} + +class CacheService { + private cache: Cache | null = null; + private pendingRequests = new Map>(); + private backgroundCallbacks = new Map void>(); + private readonly CACHE_NAME = "romm-api-cache"; + private enableExperimentalCache = useLocalStorage( + "settings.enableExperimentalCache", + false, + ); + + async init(): Promise { + if (!("caches" in window)) { + console.warn("Cache API not supported, falling back to memory cache"); + return; + } + + try { + this.cache = await caches.open(this.CACHE_NAME); + } catch (error) { + console.error("Failed to open cache:", error); + } + } + + private generateCacheKey(config: AxiosRequestConfig): string { + const { url, params } = config; + const queryString = params ? new URLSearchParams(params).toString() : ""; + + return `${window.location.origin}${url}${queryString ? `?${queryString}` : ""}`; + } + + private async getCachedResponse( + cacheKey: string, + ): Promise { + if (!this.cache) return null; + + try { + const response = await this.cache.match(cacheKey); + if (!response) return null; + + return await response.json(); + } catch (error) { + console.error("Error reading from cache:", error); + return null; + } + } + + private async setCachedResponse( + cacheKey: string, + data: unknown, + ): Promise { + if (!this.cache) return; + + try { + const response = new Response(JSON.stringify({ data }), { + headers: { + "Content-Type": "application/json", + }, + }); + + await this.cache.put(cacheKey, response); + } catch (error) { + console.error("Error writing to cache:", error); + } + } + + async request( + config: AxiosRequestConfig, + onBackgroundUpdate: (data: T) => void, + ): Promise> { + // If experimental cache is disabled, make direct API call + if (!this.enableExperimentalCache.value) { + return api.request(config); + } + + const cacheKey = this.generateCacheKey(config); + + // Check if there's already a pending request for this cache key + if (this.pendingRequests.has(cacheKey)) { + return this.pendingRequests.get(cacheKey)!; + } + + // Check cache first + const cachedEntry = await this.getCachedResponse(cacheKey); + if (cachedEntry) { + this.backgroundCallbacks.set(cacheKey, onBackgroundUpdate); + + // Trigger background update + this.makeRequest(cacheKey, config); + return { + data: cachedEntry.data, + status: 200, + statusText: "OK", + headers: {}, + config, + } as AxiosResponse; + } + + // Make the actual request if no cache hit + const requestPromise = this.makeRequest(cacheKey, config); + this.pendingRequests.set(cacheKey, requestPromise); + + try { + return await requestPromise; + } finally { + this.pendingRequests.delete(cacheKey); + } + } + + private async makeRequest( + cacheKey: string, + config: AxiosRequestConfig, + ): Promise> { + const response = await api.request(config); + + // Only cache successful responses + if (response.status >= 200 && response.status < 300) { + await this.setCachedResponse(cacheKey, response.data); + } + + // Trigger the registered callback + const callback = this.backgroundCallbacks.get(cacheKey); + if (callback) { + try { + callback(response.data); + } catch (error) { + console.error("Error in background update callback:", error); + } finally { + this.backgroundCallbacks.delete(cacheKey); + } + } + + return response; + } + + async clearCache(): Promise { + if (!this.cache) return; + + try { + await caches.delete(this.CACHE_NAME); + this.cache = await caches.open(this.CACHE_NAME); + } catch (error) { + console.error("Error clearing cache:", error); + } + } + + async clearCacheForPattern(pattern: string): Promise { + if (!this.cache) return; + + try { + const keys = await this.cache.keys(); + const matchingKeys = keys.filter((key) => key.url.includes(pattern)); + + await Promise.all(matchingKeys.map((key) => this.cache!.delete(key))); + } catch (error) { + console.error("Error clearing cache pattern:", error); + } + } + + async getCacheSize(): Promise { + if (!this.cache) return 0; + + try { + const keys = await this.cache.keys(); + return keys.length; + } catch (error) { + console.error("Error getting cache size:", error); + return 0; + } + } +} + +const cacheService = new CacheService(); + +cacheService.init(); + +export default cacheService; diff --git a/frontend/src/stores/collections.ts b/frontend/src/stores/collections.ts index d979f90ee..107a09b18 100644 --- a/frontend/src/stores/collections.ts +++ b/frontend/src/stores/collections.ts @@ -194,6 +194,12 @@ export default defineStore("collections", { getCollection(collectionId: number) { return this.allCollections.find((p) => p.id === collectionId); }, + getSmartCollection(smartCollectionId: number) { + return this.smartCollections.find((p) => p.id === smartCollectionId); + }, + getVirtualCollection(virtualCollectionId: string) { + return this.virtualCollections.find((p) => p.id === virtualCollectionId); + }, isFavorite(rom: SimpleRom) { return this.favoriteCollection?.rom_ids?.includes(rom.id); }, diff --git a/frontend/src/stores/roms.ts b/frontend/src/stores/roms.ts index 568342282..24354112f 100644 --- a/frontend/src/stores/roms.ts +++ b/frontend/src/stores/roms.ts @@ -2,7 +2,8 @@ import { isNull, isUndefined } from "lodash"; import { defineStore } from "pinia"; import type { SearchRomSchema } from "@/__generated__"; import type { DetailedRomSchema, SimpleRomSchema } from "@/__generated__/"; -import romApi from "@/services/api/rom"; +import type { CustomLimitOffsetPage_SimpleRomSchema_ as GetRomsResponse } from "@/__generated__/models/CustomLimitOffsetPage_SimpleRomSchema_"; +import cachedApiService from "@/services/cache/api"; import { type Collection, type VirtualCollection, @@ -42,13 +43,6 @@ const defaultRomsState = { orderDir: "asc" as "asc" | "desc", }; -// This caches the first 72 roms fetched for each platform -const _romsCacheByID = new Map(); -const _romsCacheByPlatform = new Map(); -const _romsCacheByCollection = new Map(); -const _romsCacheByVirtualCollection = new Map(); -const _romsCacheBySmartCollection = new Map(); - export default defineStore("roms", { state: () => ({ ...defaultRomsState }), @@ -73,14 +67,6 @@ export default defineStore("roms", { }, setCurrentPlatform(platform: Platform | null) { this.currentPlatform = platform; - if (platform) { - const romIDs = _romsCacheByPlatform.get(platform.id); - if (romIDs) { - this.allRoms = romIDs - .filter((id) => _romsCacheByID.has(id)) - .map((id) => _romsCacheByID.get(id)!) as SimpleRom[]; - } - } }, setCurrentRom(rom: DetailedRom) { this.currentRom = rom; @@ -93,38 +79,49 @@ export default defineStore("roms", { }, setCurrentCollection(collection: Collection | null) { this.currentCollection = collection; - if (collection) { - const romIDs = _romsCacheByCollection.get(collection.id); - if (romIDs) { - this.allRoms = romIDs - .filter((id) => _romsCacheByID.has(id)) - .map((id) => _romsCacheByID.get(id)!) as SimpleRom[]; - } - } }, setCurrentVirtualCollection(collection: VirtualCollection | null) { this.currentVirtualCollection = collection; - if (collection) { - const romIDs = _romsCacheByVirtualCollection.get(collection.id); - if (romIDs) { - this.allRoms = romIDs - .filter((id) => _romsCacheByID.has(id)) - .map((id) => _romsCacheByID.get(id)!) as SimpleRom[]; - } - } }, setCurrentSmartCollection(collection: SmartCollection | null) { this.currentSmartCollection = collection; - if (collection) { - const romIDs = _romsCacheBySmartCollection.get(collection.id); - if (romIDs) { - this.allRoms = romIDs - .filter((id) => _romsCacheByID.has(id)) - .map((id) => _romsCacheByID.get(id)!) as SimpleRom[]; - } - } }, - fetchRoms({ + // Fetching multiple roms + _buildRequestParams(galleryFilter: GalleryFilterStore) { + return { + ...galleryFilter.$state, + platformId: + this.currentPlatform?.id ?? + galleryFilter.selectedPlatform?.id ?? + null, + collectionId: this.currentCollection?.id ?? null, + virtualCollectionId: this.currentVirtualCollection?.id ?? null, + smartCollectionId: this.currentSmartCollection?.id ?? null, + limit: this.fetchLimit, + offset: this.fetchOffset, + orderBy: this.orderBy, + orderDir: this.orderDir, + groupByMetaId: this._shouldGroupRoms() && this.onGalleryView, + }; + }, + _postFetchRoms(response: GetRomsResponse, concat: boolean) { + const { items, offset, total, char_index, rom_id_index } = response; + + if (!concat || this.fetchOffset === 0) { + this.allRoms = items; + } else { + this.allRoms = this.allRoms.concat(items); + } + + // Update the offset and total roms in filtered database result + if (offset !== null) this.fetchOffset = offset + this.fetchLimit; + if (total !== null) this.fetchTotalRoms = total; + + // Set the character index for the current platform + this.characterIndex = char_index; + this.romIdIndex = rom_id_index; + }, + async fetchRoms({ galleryFilter, concat = true, }: { @@ -134,69 +131,27 @@ export default defineStore("roms", { if (this.fetchingRoms) return Promise.resolve([]); this.fetchingRoms = true; + // Capture current request parameters to validate background updates + const currentRequestParams = this._buildRequestParams(galleryFilter); + return new Promise((resolve, reject) => { - romApi - .getRoms({ - ...galleryFilter.$state, - platformId: - this.currentPlatform?.id ?? - galleryFilter.selectedPlatform?.id ?? - null, - collectionId: this.currentCollection?.id ?? null, - virtualCollectionId: this.currentVirtualCollection?.id ?? null, - smartCollectionId: this.currentSmartCollection?.id ?? null, - limit: this.fetchLimit, - offset: this.fetchOffset, - orderBy: this.orderBy, - orderDir: this.orderDir, - groupByMetaId: this._shouldGroupRoms() && this.onGalleryView, + cachedApiService + .getRoms(currentRequestParams, (response) => { + if (concat && this.fetchOffset != 0) return; + + // Check if parameters have changed since the request was made + const currentParams = this._buildRequestParams(galleryFilter); + const paramsChanged = + JSON.stringify(currentParams) !== + JSON.stringify(currentRequestParams); + if (paramsChanged) return; + + this._postFetchRoms(response, concat); + }) + .then((response) => { + this._postFetchRoms(response.data, concat); + resolve(response.data.items); }) - .then( - ({ data: { items, offset, total, char_index, rom_id_index } }) => { - if (!concat || this.fetchOffset === 0) { - this.allRoms = items; - - // Cache the first batch of roms for each context - if (this.currentPlatform) { - _romsCacheByPlatform.set( - this.currentPlatform.id, - items.map((rom) => rom.id), - ); - items.forEach((rom) => _romsCacheByID.set(rom.id, rom)); - } else if (this.currentCollection) { - _romsCacheByCollection.set( - this.currentCollection.id, - items.map((rom) => rom.id), - ); - items.forEach((rom) => _romsCacheByID.set(rom.id, rom)); - } else if (this.currentVirtualCollection) { - _romsCacheByVirtualCollection.set( - this.currentVirtualCollection.id, - items.map((rom) => rom.id), - ); - items.forEach((rom) => _romsCacheByID.set(rom.id, rom)); - } else if (this.currentSmartCollection) { - _romsCacheBySmartCollection.set( - this.currentSmartCollection.id, - items.map((rom) => rom.id), - ); - items.forEach((rom) => _romsCacheByID.set(rom.id, rom)); - } - } else { - this.allRoms = this.allRoms.concat(items); - } - - // Update the offset and total roms in filtered database result - if (offset !== null) this.fetchOffset = offset + this.fetchLimit; - if (total !== null) this.fetchTotalRoms = total; - - // Set the character index for the current platform - this.characterIndex = char_index; - this.romIdIndex = rom_id_index; - - resolve(items); - }, - ) .catch((error) => { reject(error); }) @@ -205,48 +160,44 @@ export default defineStore("roms", { }); }); }, - fetchRecentRoms(): Promise { - return new Promise((resolve, reject) => { - romApi - .getRecentRoms() - .then(({ data: { items } }) => { - this.setRecentRoms(items); - resolve(items); - }) - .catch((error) => { - reject(error); - }); + // Recent ROMs for home page + async fetchRecentRoms(): Promise { + const response = await cachedApiService.getRecentRoms((data) => { + this.setRecentRoms(data.items); }); + const { items } = response.data; + this.setRecentRoms(items); + return items; }, - fetchContinuePlayingRoms(): Promise { - return new Promise((resolve, reject) => { - romApi - .getRecentPlayedRoms() - .then(({ data: { items } }) => { - this.setContinuePlayingRoms(items); - resolve(items); - }) - .catch((error) => { - reject(error); - }); + // Continue playing ROMs for home page + async fetchContinuePlayingRoms(): Promise { + const response = await cachedApiService.getRecentPlayedRoms((data) => { + this.setContinuePlayingRoms(data.items); }); + const { items } = response.data; + this.setContinuePlayingRoms(items); + return items; }, add(roms: SimpleRom[]) { this.allRoms = this.allRoms.concat(roms); }, addToRecent(rom: SimpleRom) { this.recentRoms = [rom, ...this.recentRoms]; + cachedApiService.clearRecentRomsCache(); }, removeFromRecent(rom: SimpleRom) { this.recentRoms = this.recentRoms.filter((value) => value.id !== rom.id); + cachedApiService.clearRecentRomsCache(); }, addToContinuePlaying(rom: SimpleRom) { this.continuePlayingRoms = [rom, ...this.continuePlayingRoms]; + cachedApiService.clearRecentPlayedRomsCache(); }, removeFromContinuePlaying(rom: SimpleRom) { this.continuePlayingRoms = this.continuePlayingRoms.filter( (value) => value.id !== rom.id, ); + cachedApiService.clearRecentPlayedRomsCache(); }, update(rom: SimpleRom) { this.allRoms = this.allRoms.map((value) => @@ -255,6 +206,9 @@ export default defineStore("roms", { this.recentRoms = this.recentRoms.map((value) => value.id === rom.id ? rom : value, ); + this.continuePlayingRoms = this.continuePlayingRoms.map((value) => + value.id === rom.id ? rom : value, + ); }, remove(roms: SimpleRom[]) { this.allRoms = this.allRoms.filter((value) => { diff --git a/frontend/src/views/Auth/Login.vue b/frontend/src/views/Auth/Login.vue index b754f31e8..98b2d83e7 100644 --- a/frontend/src/views/Auth/Login.vue +++ b/frontend/src/views/Auth/Login.vue @@ -87,6 +87,7 @@ async function sendReset() { } async function loginOIDC() { + if (loggingInOIDC.value) return; loggingInOIDC.value = true; window.open("/api/login/openid", "_self"); } diff --git a/pyproject.toml b/pyproject.toml index 819470d74..528739a69 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,7 +24,7 @@ dependencies = [ "fastapi[standard-no-fastapi-cloud-cli] ~= 0.116", "gunicorn ~= 23.0", "httpx ~= 0.27", - "joserfc ~= 1.3", + "joserfc ~= 1.3.4", "opentelemetry-distro ~= 0.56", "opentelemetry-exporter-otlp ~= 1.36", "opentelemetry-instrumentation-aiohttp-client ~= 0.56", diff --git a/uv.lock b/uv.lock index 4df00334d..392dce66e 100644 --- a/uv.lock +++ b/uv.lock @@ -822,14 +822,14 @@ wheels = [ [[package]] name = "joserfc" -version = "1.3.2" +version = "1.3.4" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "cryptography" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/9e/ca/416df9a71e2eacca95a55f9a4978cd771742c0eccf14e07e088315554c6f/joserfc-1.3.2.tar.gz", hash = "sha256:147bbba5b0b7c29fa270921dc1f17d83b48ccf0fecf51295b8de1ff1b682ca53", size = 196379, upload-time = "2025-09-04T06:51:11.349Z" } +sdist = { url = "https://files.pythonhosted.org/packages/b0/79/d63a882c0212e95f3ba8863a115e5ca9a5d39413b02273ddce72058e717f/joserfc-1.3.4.tar.gz", hash = "sha256:67d8413c501c239f65eefad5ae685cfbfc401aa63289fc409ef7cc331b007227", size = 197787, upload-time = "2025-09-21T15:49:34.7Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ec/2a/f4915889af9b77d8ea96797640e77ca1995037eaa456be2cdc80ef4a7507/joserfc-1.3.2-py3-none-any.whl", hash = "sha256:81a1d14a0da6d0278f963cb6d6ee43b4640552341b6e984d1535083eba535723", size = 74499, upload-time = "2025-09-04T06:51:09.863Z" }, + { url = "https://files.pythonhosted.org/packages/9a/78/beb171f0caac81f51695f43c87c0c20b3ce2a190cf74a3fbb0b9afe03b45/joserfc-1.3.4-py3-none-any.whl", hash = "sha256:30c845c58d441cfe32d08ac35e437812481ca8155373873b7abf80224bf601c0", size = 75638, upload-time = "2025-09-21T15:49:33.14Z" }, ] [[package]] @@ -1970,7 +1970,7 @@ requires-dist = [ { name = "httpx", specifier = "~=0.27" }, { name = "ipdb", marker = "extra == 'dev'", specifier = "~=0.13" }, { name = "ipykernel", marker = "extra == 'dev'", specifier = "~=6.29" }, - { name = "joserfc", specifier = "~=1.3" }, + { name = "joserfc", specifier = "~=1.3.4" }, { name = "memray", marker = "extra == 'dev'", specifier = "~=1.15" }, { name = "mypy", marker = "extra == 'dev'", specifier = "~=1.13" }, { name = "opentelemetry-distro", specifier = "~=0.56" },