diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 8256e8e..46de027 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -24,7 +24,7 @@ import { collectionDbPath, detectOsuInstallDir, isValidOsuInstallDir } from "./o import { loadSettings, saveSettings, type AppSettings } from "./settings.js"; import { getBeatmapSetByIdWithFallback, - resolveDownloadUrlForResult, + installBeatmapSetWithFallback, searchWithFallback, } from "./source-registry.js"; import { checkForUpdate } from "./updates.js"; @@ -89,22 +89,16 @@ function registerIpcHandlers(): void { ipcMain.handle("beatmaps:getById", (_e, beatmapSetId: number) => getBeatmapSetByIdWithFallback(loadSettings().searchSources, beatmapSetId) ); - ipcMain.handle("beatmaps:install", async (_e, set: BeatmapSet) => { - const downloadUrl = await resolveDownloadUrlForResult( - loadSettings().searchSources, - set.source, - set.id - ); - if (!downloadUrl) { - throw new Error(`No download available for "${set.artist} - ${set.title}" yet.`); - } - await installBeatmapSet( - requireInstallDir(), - downloadUrl, - `${set.id} ${set.artist} - ${set.title}`, - set.coverUrl - ); - }); + ipcMain.handle("beatmaps:install", (_e, set: BeatmapSet) => + installBeatmapSetWithFallback(loadSettings().searchSources, set.source, set.id, (downloadUrl) => + installBeatmapSet( + requireInstallDir(), + downloadUrl, + `${set.id} ${set.artist} - ${set.title}`, + set.coverUrl + ) + ) + ); ipcMain.handle("collections:read", async () => { const path = collectionDbPath(requireInstallDir()); diff --git a/apps/desktop/src/main/source-registry.ts b/apps/desktop/src/main/source-registry.ts index 2e3b732..2444ee7 100644 --- a/apps/desktop/src/main/source-registry.ts +++ b/apps/desktop/src/main/source-registry.ts @@ -1,10 +1,12 @@ // Tries enabled beatmap sources in the user's configured order, falling // through to the next one on failure, and throttles per-source requests so // rapid filter changes (typing, dragging the star slider) can't hammer a -// mirror faster than a search reasonably should. Install/download always -// goes back to the specific mirror a result came from — each mirror has its -// own independent id space, so a numeric id from one can't be assumed to -// exist, let alone mean the same thing, on another. +// mirror faster than a search reasonably should. Downloads prefer the +// mirror a search result actually came from (freshest data), but fall back +// to any other enabled mirror on failure — beatmapset ids are the same +// across mirrors (they all index the same osu.ppy.sh catalog), so a mirror +// having a transient outage or its own rate limit doesn't need to fail the +// whole install. import type { BeatmapSearchQuery, BeatmapSearchResult, @@ -71,14 +73,33 @@ export async function getBeatmapSetByIdWithFallback( return null; } -export async function resolveDownloadUrlForResult( +export async function installBeatmapSetWithFallback( sources: BeatmapSourceConfig[], - sourceName: string, - beatmapSetId: number -): Promise { - const config = - sources.find((s) => s.name === sourceName && s.enabled) ?? enabledInOrder(sources)[0]; - if (!config) return null; - await throttle(config.id); - return new MirrorSource(config).resolveDownloadUrl(beatmapSetId); + preferredSourceName: string, + beatmapSetId: number, + install: (downloadUrl: string) => Promise +): Promise { + const candidates = enabledInOrder(sources); + if (candidates.length === 0) { + throw new Error("No beatmap search sources are enabled."); + } + + const ordered = [ + ...candidates.filter((c) => c.name === preferredSourceName), + ...candidates.filter((c) => c.name !== preferredSourceName), + ]; + + let lastError: unknown; + for (const config of ordered) { + try { + await throttle(config.id); + const url = await new MirrorSource(config).resolveDownloadUrl(beatmapSetId); + if (!url) continue; + await install(url); + return; + } catch (err) { + lastError = err; + } + } + throw lastError instanceof Error ? lastError : new Error("No source could download this beatmapset."); } diff --git a/apps/desktop/src/renderer/src/assets/icons/muted/check.svg b/apps/desktop/src/renderer/src/assets/icons/muted/check.svg new file mode 100644 index 0000000..43b5db4 --- /dev/null +++ b/apps/desktop/src/renderer/src/assets/icons/muted/check.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/desktop/src/renderer/src/library-context.tsx b/apps/desktop/src/renderer/src/library-context.tsx new file mode 100644 index 0000000..37ed412 --- /dev/null +++ b/apps/desktop/src/renderer/src/library-context.tsx @@ -0,0 +1,45 @@ +// Shared installed-library state: scanned once on mount, then re-scanned +// automatically on an interval so newly-installed maps (from Find maps) +// show up in the Library without a manual rescan, and so Find maps can +// mark results that are already downloaded. +import type { BeatmapSet } from "@directify/shared"; +import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from "react"; + +const AUTO_SCAN_INTERVAL_MS = 5000; + +interface LibraryContextValue { + sets: BeatmapSet[] | null; + installedIds: Set; + refresh: () => Promise; +} + +const LibraryContext = createContext(null); + +export function LibraryProvider({ children }: { children: ReactNode }) { + const [sets, setSets] = useState(null); + + const refresh = useCallback(async () => { + const scanned = await window.directify.scanLibrary(); + setSets(scanned); + }, []); + + useEffect(() => { + refresh(); + const interval = setInterval(refresh, AUTO_SCAN_INTERVAL_MS); + return () => clearInterval(interval); + }, [refresh]); + + const installedIds = useMemo(() => new Set((sets ?? []).map((s) => s.id)), [sets]); + + return ( + + {children} + + ); +} + +export function useLibrary(): LibraryContextValue { + const ctx = useContext(LibraryContext); + if (!ctx) throw new Error("useLibrary must be used within LibraryProvider"); + return ctx; +} diff --git a/apps/desktop/src/renderer/src/locales/en.json b/apps/desktop/src/renderer/src/locales/en.json index aa9991a..e16de6f 100644 --- a/apps/desktop/src/renderer/src/locales/en.json +++ b/apps/desktop/src/renderer/src/locales/en.json @@ -51,7 +51,10 @@ "importByLinkPlaceholder": "Paste a beatmap link or ID...", "importButton": "Import", "importNotFound": "Couldn't find a beatmapset at that link.", - "importInvalidLink": "That doesn't look like a beatmap link or ID." + "importInvalidLink": "That doesn't look like a beatmap link or ID.", + "showDownloaded": "Show downloaded", + "downloaded": "Downloaded", + "allDownloaded": "You already have every result here — enable \"Show downloaded\" to see them." }, "collections": { "title": "Collections", diff --git a/apps/desktop/src/renderer/src/locales/es.json b/apps/desktop/src/renderer/src/locales/es.json index 8a4e4db..49a26fa 100644 --- a/apps/desktop/src/renderer/src/locales/es.json +++ b/apps/desktop/src/renderer/src/locales/es.json @@ -51,7 +51,10 @@ "importByLinkPlaceholder": "Pega un enlace o ID de beatmap...", "importButton": "Importar", "importNotFound": "No se encontró ningún beatmapset en ese enlace.", - "importInvalidLink": "Eso no parece un enlace o ID de beatmap válido." + "importInvalidLink": "Eso no parece un enlace o ID de beatmap válido.", + "showDownloaded": "Mostrar descargados", + "downloaded": "Descargado", + "allDownloaded": "Ya tienes todos los resultados aquí — activa \"Mostrar descargados\" para verlos." }, "collections": { "title": "Colecciones", diff --git a/apps/desktop/src/renderer/src/locales/ja.json b/apps/desktop/src/renderer/src/locales/ja.json index 7ed3b82..712408e 100644 --- a/apps/desktop/src/renderer/src/locales/ja.json +++ b/apps/desktop/src/renderer/src/locales/ja.json @@ -50,7 +50,10 @@ "importByLinkPlaceholder": "譜面のリンクまたはIDを貼り付け...", "importButton": "インポート", "importNotFound": "そのリンクの譜面セットが見つかりませんでした。", - "importInvalidLink": "有効な譜面リンクまたはIDではないようです。" + "importInvalidLink": "有効な譜面リンクまたはIDではないようです。", + "showDownloaded": "ダウンロード済みを表示", + "downloaded": "ダウンロード済み", + "allDownloaded": "ここにある結果はすべてダウンロード済みです。「ダウンロード済みを表示」を有効にすると表示されます。" }, "collections": { "title": "コレクション", diff --git a/apps/desktop/src/renderer/src/main.tsx b/apps/desktop/src/renderer/src/main.tsx index 8ae73ca..a0f6b9a 100644 --- a/apps/desktop/src/renderer/src/main.tsx +++ b/apps/desktop/src/renderer/src/main.tsx @@ -11,6 +11,7 @@ import { HashRouter } from "react-router-dom"; import { App } from "./App"; import "./i18n"; import { resolveDesktopIcon } from "./icon-map"; +import { LibraryProvider } from "./library-context"; import { installMockDirectifyIfNeeded } from "./mock-directify"; import { SettingsProvider } from "./settings-context"; @@ -20,9 +21,11 @@ ReactDOM.createRoot(document.getElementById("root")!).render( - - - + + + + + diff --git a/apps/desktop/src/renderer/src/pages/LibraryPage.tsx b/apps/desktop/src/renderer/src/pages/LibraryPage.tsx index 3219bca..47e31be 100644 --- a/apps/desktop/src/renderer/src/pages/LibraryPage.tsx +++ b/apps/desktop/src/renderer/src/pages/LibraryPage.tsx @@ -1,12 +1,13 @@ -// Library page: shows installed beatmapsets (scanned from Songs), lets the user filter, select, add to a collection, or delete. +// Library page: shows installed beatmapsets (auto-scanned from Songs by LibraryProvider), lets the user filter, select, add to a collection, or delete. import type { BeatmapSet, CollectionDatabase } from "@directify/shared"; import { Button, Card, Icon, TextInput } from "@directify/ui"; import { useEffect, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; +import { useLibrary } from "../library-context"; export function LibraryPage() { const { t } = useTranslation(); - const [sets, setSets] = useState(null); + const { sets, refresh } = useLibrary(); const [collections, setCollections] = useState(null); const [query, setQuery] = useState(""); const [selected, setSelected] = useState>(new Set()); @@ -16,23 +17,22 @@ export function LibraryPage() { async function rescan() { setStatus(t("library.scanning")); try { - const [scanned, db] = await Promise.all([ - window.directify.scanLibrary(), - window.directify.readCollections(), - ]); - setSets(scanned); + const [, db] = await Promise.all([refresh(), window.directify.readCollections()]); setCollections(db); setSelected(new Set()); - setStatus(t("library.foundCount", { count: scanned.length })); } catch (err) { setStatus((err as Error).message); } } useEffect(() => { - rescan(); + window.directify.readCollections().then(setCollections); }, []); + useEffect(() => { + if (sets) setStatus(t("library.foundCount", { count: sets.length })); + }, [sets, t]); + const filtered = useMemo(() => { if (!sets) return []; const q = query.trim().toLowerCase(); diff --git a/apps/desktop/src/renderer/src/pages/SearchPage.tsx b/apps/desktop/src/renderer/src/pages/SearchPage.tsx index cba0c5c..6cc442e 100644 --- a/apps/desktop/src/renderer/src/pages/SearchPage.tsx +++ b/apps/desktop/src/renderer/src/pages/SearchPage.tsx @@ -8,8 +8,9 @@ import { type RankedStatus, } from "@directify/shared"; import { Button, Card, DualRangeSlider, Icon, StatusBadge, TextInput } from "@directify/ui"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; +import { useLibrary } from "../library-context"; const MODES: { value: OsuMode | ""; label: string }[] = [ { value: "", label: "All" }, @@ -89,6 +90,8 @@ function selectStyle(): React.CSSProperties { export function SearchPage() { const { t } = useTranslation(); + const { installedIds, refresh: refreshLibrary } = useLibrary(); + const [showDownloaded, setShowDownloaded] = useState(false); const [query, setQuery] = useState(""); const [mode, setMode] = useState(""); const [keys, setKeys] = useState(null); @@ -169,6 +172,7 @@ export function SearchPage() { try { await window.directify.installBeatmapSet(set); setStatus(`${set.artist} - ${set.title}`); + await refreshLibrary(); } catch (err) { setStatus((err as Error).message); } finally { @@ -176,6 +180,11 @@ export function SearchPage() { } } + const visibleResults = useMemo( + () => (showDownloaded ? results : results.filter((set) => !installedIds.has(set.id))), + [results, showDownloaded, installedIds] + ); + return (
@@ -321,13 +330,33 @@ export function SearchPage() { />
- {status && ( -

- {status} -

- )} +
+ {status && ( +

+ {status} +

+ )} + +
- {results.length === 0 ? ( + {visibleResults.length === 0 ? (
- {t("search.emptyPrompt")} + {results.length > 0 ? t("search.allDownloaded") : t("search.emptyPrompt")}
) : (
- {results.map((set) => ( - -
-
{set.title}
- -
-
- {set.artist} · {set.creator} -
- -
- ))} + {visibleResults.map((set) => { + const downloaded = installedIds.has(set.id); + return ( + +
+
{set.title}
+ +
+
+ {set.artist} · {set.creator} +
+ +
+ ); + })}
)}