Auto-scan library, mark/hide downloaded results, and fix download reliability

- Library now auto-rescans every 5s via a shared LibraryProvider instead
  of only on manual Rescan, so newly-installed maps show up without
  navigating away and back.
- Find maps: results already in the library show a checkmark and
  "Downloaded" instead of Install (disabled), and a "Show downloaded"
  toggle (off by default) hides them from results entirely. Installing
  now triggers an immediate library refresh.
- Downloads previously only ever tried the single mirror a search result
  came from; verified live that catboy.best's /d/ endpoint has its own
  short per-beatmapset cooldown independent of the general API rate
  limit, which could fail an install outright even though the map is
  available. installBeatmapSetWithFallback now retries the other
  enabled mirrors (same beatmapset ids across mirrors, since they all
  index the same osu.ppy.sh catalog) before giving up — verified this
  recovers a forced failure on the preferred source.
This commit is contained in:
pvrzz
2026-09-18 07:30:27 -04:00
parent 902e59f974
commit 202d933d4a
10 changed files with 184 additions and 75 deletions
+6 -12
View File
@@ -24,7 +24,7 @@ import { collectionDbPath, detectOsuInstallDir, isValidOsuInstallDir } from "./o
import { loadSettings, saveSettings, type AppSettings } from "./settings.js"; import { loadSettings, saveSettings, type AppSettings } from "./settings.js";
import { import {
getBeatmapSetByIdWithFallback, getBeatmapSetByIdWithFallback,
resolveDownloadUrlForResult, installBeatmapSetWithFallback,
searchWithFallback, searchWithFallback,
} from "./source-registry.js"; } from "./source-registry.js";
import { checkForUpdate } from "./updates.js"; import { checkForUpdate } from "./updates.js";
@@ -89,22 +89,16 @@ function registerIpcHandlers(): void {
ipcMain.handle("beatmaps:getById", (_e, beatmapSetId: number) => ipcMain.handle("beatmaps:getById", (_e, beatmapSetId: number) =>
getBeatmapSetByIdWithFallback(loadSettings().searchSources, beatmapSetId) getBeatmapSetByIdWithFallback(loadSettings().searchSources, beatmapSetId)
); );
ipcMain.handle("beatmaps:install", async (_e, set: BeatmapSet) => { ipcMain.handle("beatmaps:install", (_e, set: BeatmapSet) =>
const downloadUrl = await resolveDownloadUrlForResult( installBeatmapSetWithFallback(loadSettings().searchSources, set.source, set.id, (downloadUrl) =>
loadSettings().searchSources, installBeatmapSet(
set.source,
set.id
);
if (!downloadUrl) {
throw new Error(`No download available for "${set.artist} - ${set.title}" yet.`);
}
await installBeatmapSet(
requireInstallDir(), requireInstallDir(),
downloadUrl, downloadUrl,
`${set.id} ${set.artist} - ${set.title}`, `${set.id} ${set.artist} - ${set.title}`,
set.coverUrl set.coverUrl
)
)
); );
});
ipcMain.handle("collections:read", async () => { ipcMain.handle("collections:read", async () => {
const path = collectionDbPath(requireInstallDir()); const path = collectionDbPath(requireInstallDir());
+33 -12
View File
@@ -1,10 +1,12 @@
// Tries enabled beatmap sources in the user's configured order, falling // Tries enabled beatmap sources in the user's configured order, falling
// through to the next one on failure, and throttles per-source requests so // 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 // rapid filter changes (typing, dragging the star slider) can't hammer a
// mirror faster than a search reasonably should. Install/download always // mirror faster than a search reasonably should. Downloads prefer the
// goes back to the specific mirror a result came from — each mirror has its // mirror a search result actually came from (freshest data), but fall back
// own independent id space, so a numeric id from one can't be assumed to // to any other enabled mirror on failure — beatmapset ids are the same
// exist, let alone mean the same thing, on another. // 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 { import type {
BeatmapSearchQuery, BeatmapSearchQuery,
BeatmapSearchResult, BeatmapSearchResult,
@@ -71,14 +73,33 @@ export async function getBeatmapSetByIdWithFallback(
return null; return null;
} }
export async function resolveDownloadUrlForResult( export async function installBeatmapSetWithFallback(
sources: BeatmapSourceConfig[], sources: BeatmapSourceConfig[],
sourceName: string, preferredSourceName: string,
beatmapSetId: number beatmapSetId: number,
): Promise<string | null> { install: (downloadUrl: string) => Promise<void>
const config = ): Promise<void> {
sources.find((s) => s.name === sourceName && s.enabled) ?? enabledInOrder(sources)[0]; const candidates = enabledInOrder(sources);
if (!config) return null; 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); await throttle(config.id);
return new MirrorSource(config).resolveDownloadUrl(beatmapSetId); 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.");
} }
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="none" stroke="#9CA3A8" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 6L9 17l-5-5"/></svg>

After

Width:  |  Height:  |  Size: 209 B

@@ -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<number>;
refresh: () => Promise<void>;
}
const LibraryContext = createContext<LibraryContextValue | null>(null);
export function LibraryProvider({ children }: { children: ReactNode }) {
const [sets, setSets] = useState<BeatmapSet[] | null>(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 (
<LibraryContext.Provider value={{ sets, installedIds, refresh }}>
{children}
</LibraryContext.Provider>
);
}
export function useLibrary(): LibraryContextValue {
const ctx = useContext(LibraryContext);
if (!ctx) throw new Error("useLibrary must be used within LibraryProvider");
return ctx;
}
@@ -51,7 +51,10 @@
"importByLinkPlaceholder": "Paste a beatmap link or ID...", "importByLinkPlaceholder": "Paste a beatmap link or ID...",
"importButton": "Import", "importButton": "Import",
"importNotFound": "Couldn't find a beatmapset at that link.", "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": { "collections": {
"title": "Collections", "title": "Collections",
@@ -51,7 +51,10 @@
"importByLinkPlaceholder": "Pega un enlace o ID de beatmap...", "importByLinkPlaceholder": "Pega un enlace o ID de beatmap...",
"importButton": "Importar", "importButton": "Importar",
"importNotFound": "No se encontró ningún beatmapset en ese enlace.", "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": { "collections": {
"title": "Colecciones", "title": "Colecciones",
@@ -50,7 +50,10 @@
"importByLinkPlaceholder": "譜面のリンクまたはIDを貼り付け...", "importByLinkPlaceholder": "譜面のリンクまたはIDを貼り付け...",
"importButton": "インポート", "importButton": "インポート",
"importNotFound": "そのリンクの譜面セットが見つかりませんでした。", "importNotFound": "そのリンクの譜面セットが見つかりませんでした。",
"importInvalidLink": "有効な譜面リンクまたはIDではないようです。" "importInvalidLink": "有効な譜面リンクまたはIDではないようです。",
"showDownloaded": "ダウンロード済みを表示",
"downloaded": "ダウンロード済み",
"allDownloaded": "ここにある結果はすべてダウンロード済みです。「ダウンロード済みを表示」を有効にすると表示されます。"
}, },
"collections": { "collections": {
"title": "コレクション", "title": "コレクション",
+3
View File
@@ -11,6 +11,7 @@ import { HashRouter } from "react-router-dom";
import { App } from "./App"; import { App } from "./App";
import "./i18n"; import "./i18n";
import { resolveDesktopIcon } from "./icon-map"; import { resolveDesktopIcon } from "./icon-map";
import { LibraryProvider } from "./library-context";
import { installMockDirectifyIfNeeded } from "./mock-directify"; import { installMockDirectifyIfNeeded } from "./mock-directify";
import { SettingsProvider } from "./settings-context"; import { SettingsProvider } from "./settings-context";
@@ -20,9 +21,11 @@ ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode> <React.StrictMode>
<IconProvider resolve={resolveDesktopIcon}> <IconProvider resolve={resolveDesktopIcon}>
<SettingsProvider> <SettingsProvider>
<LibraryProvider>
<HashRouter> <HashRouter>
<App /> <App />
</HashRouter> </HashRouter>
</LibraryProvider>
</SettingsProvider> </SettingsProvider>
</IconProvider> </IconProvider>
</React.StrictMode> </React.StrictMode>
@@ -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 type { BeatmapSet, CollectionDatabase } from "@directify/shared";
import { Button, Card, Icon, TextInput } from "@directify/ui"; import { Button, Card, Icon, TextInput } from "@directify/ui";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useLibrary } from "../library-context";
export function LibraryPage() { export function LibraryPage() {
const { t } = useTranslation(); const { t } = useTranslation();
const [sets, setSets] = useState<BeatmapSet[] | null>(null); const { sets, refresh } = useLibrary();
const [collections, setCollections] = useState<CollectionDatabase | null>(null); const [collections, setCollections] = useState<CollectionDatabase | null>(null);
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const [selected, setSelected] = useState<Set<string>>(new Set()); const [selected, setSelected] = useState<Set<string>>(new Set());
@@ -16,23 +17,22 @@ export function LibraryPage() {
async function rescan() { async function rescan() {
setStatus(t("library.scanning")); setStatus(t("library.scanning"));
try { try {
const [scanned, db] = await Promise.all([ const [, db] = await Promise.all([refresh(), window.directify.readCollections()]);
window.directify.scanLibrary(),
window.directify.readCollections(),
]);
setSets(scanned);
setCollections(db); setCollections(db);
setSelected(new Set()); setSelected(new Set());
setStatus(t("library.foundCount", { count: scanned.length }));
} catch (err) { } catch (err) {
setStatus((err as Error).message); setStatus((err as Error).message);
} }
} }
useEffect(() => { useEffect(() => {
rescan(); window.directify.readCollections().then(setCollections);
}, []); }, []);
useEffect(() => {
if (sets) setStatus(t("library.foundCount", { count: sets.length }));
}, [sets, t]);
const filtered = useMemo(() => { const filtered = useMemo(() => {
if (!sets) return []; if (!sets) return [];
const q = query.trim().toLowerCase(); const q = query.trim().toLowerCase();
@@ -8,8 +8,9 @@ import {
type RankedStatus, type RankedStatus,
} from "@directify/shared"; } from "@directify/shared";
import { Button, Card, DualRangeSlider, Icon, StatusBadge, TextInput } from "@directify/ui"; 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 { useTranslation } from "react-i18next";
import { useLibrary } from "../library-context";
const MODES: { value: OsuMode | ""; label: string }[] = [ const MODES: { value: OsuMode | ""; label: string }[] = [
{ value: "", label: "All" }, { value: "", label: "All" },
@@ -89,6 +90,8 @@ function selectStyle(): React.CSSProperties {
export function SearchPage() { export function SearchPage() {
const { t } = useTranslation(); const { t } = useTranslation();
const { installedIds, refresh: refreshLibrary } = useLibrary();
const [showDownloaded, setShowDownloaded] = useState(false);
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const [mode, setMode] = useState<OsuMode | "">(""); const [mode, setMode] = useState<OsuMode | "">("");
const [keys, setKeys] = useState<number | null>(null); const [keys, setKeys] = useState<number | null>(null);
@@ -169,6 +172,7 @@ export function SearchPage() {
try { try {
await window.directify.installBeatmapSet(set); await window.directify.installBeatmapSet(set);
setStatus(`${set.artist} - ${set.title}`); setStatus(`${set.artist} - ${set.title}`);
await refreshLibrary();
} catch (err) { } catch (err) {
setStatus((err as Error).message); setStatus((err as Error).message);
} finally { } finally {
@@ -176,6 +180,11 @@ export function SearchPage() {
} }
} }
const visibleResults = useMemo(
() => (showDownloaded ? results : results.filter((set) => !installedIds.has(set.id))),
[results, showDownloaded, installedIds]
);
return ( return (
<div style={{ display: "flex", flexDirection: "column", gap: 20 }}> <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
<div style={{ position: "relative" }}> <div style={{ position: "relative" }}>
@@ -321,13 +330,33 @@ export function SearchPage() {
/> />
</div> </div>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12 }}>
{status && ( {status && (
<p role="status" style={{ color: "var(--df-text-muted)", fontSize: 13 }}> <p role="status" style={{ color: "var(--df-text-muted)", fontSize: 13, margin: 0 }}>
{status} {status}
</p> </p>
)} )}
<label
style={{
display: "flex",
alignItems: "center",
gap: 6,
fontSize: 13,
color: "var(--df-text-muted)",
marginLeft: "auto",
whiteSpace: "nowrap",
}}
>
<input
type="checkbox"
checked={showDownloaded}
onChange={(e) => setShowDownloaded(e.target.checked)}
/>
{t("search.showDownloaded")}
</label>
</div>
{results.length === 0 ? ( {visibleResults.length === 0 ? (
<div <div
style={{ style={{
padding: 40, padding: 40,
@@ -337,7 +366,7 @@ export function SearchPage() {
borderRadius: "var(--df-radius-lg)", borderRadius: "var(--df-radius-lg)",
}} }}
> >
{t("search.emptyPrompt")} {results.length > 0 ? t("search.allDownloaded") : t("search.emptyPrompt")}
</div> </div>
) : ( ) : (
<div <div
@@ -347,7 +376,9 @@ export function SearchPage() {
gap: 16, gap: 16,
}} }}
> >
{results.map((set) => ( {visibleResults.map((set) => {
const downloaded = installedIds.has(set.id);
return (
<Card key={set.id} coverUrl={set.coverUrl} label={`${set.title} — ${set.artist}`}> <Card key={set.id} coverUrl={set.coverUrl} label={`${set.title} — ${set.artist}`}>
<div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}> <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
<div style={{ fontWeight: 700, fontSize: 15 }}>{set.title}</div> <div style={{ fontWeight: 700, fontSize: 15 }}>{set.title}</div>
@@ -359,16 +390,21 @@ export function SearchPage() {
<Button <Button
variant="secondary" variant="secondary"
onClick={() => install(set)} onClick={() => install(set)}
disabled={installing === set.id} disabled={installing === set.id || downloaded}
aria-label={`${t("common.install")} ${set.title}`} aria-label={`${t("common.install")} ${set.title}`}
> >
<span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}> <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
<Icon name="download" size={14} /> <Icon name={downloaded ? "check" : "download"} size={14} />
{installing === set.id ? t("common.installing") : t("common.install")} {downloaded
? t("search.downloaded")
: installing === set.id
? t("common.installing")
: t("common.install")}
</span> </span>
</Button> </Button>
</Card> </Card>
))} );
})}
</div> </div>
)} )}
</div> </div>