Files
stemengine_old/frontend/src/hooks/useSubsonicLibrary.ts
T
2026-04-06 14:49:06 +09:00

77 lines
2.3 KiB
TypeScript

import { useCallback, useEffect, useState } from 'react'
import { getSubsonicAlbum, getSubsonicConfig, listSubsonicAlbums, searchSubsonic } from '../api/client'
import type { SubsonicSong } from '../types'
interface UseSubsonicLibraryResult {
songs: SubsonicSong[]
loading: boolean
configured: boolean
error: string | null
refresh: () => Promise<void>
}
export function useSubsonicLibrary(count = 300): UseSubsonicLibraryResult {
const [songs, setSongs] = useState<SubsonicSong[]>([])
const [loading, setLoading] = useState(true)
const [configured, setConfigured] = useState(true)
const [error, setError] = useState<string | null>(null)
const refresh = useCallback(async () => {
setLoading(true)
setError(null)
try {
const cfg = await getSubsonicConfig()
if (!cfg.configured) {
setConfigured(false)
setSongs([])
return
}
setConfigured(true)
const dedupe = new Map<string, SubsonicSong>()
try {
// Primary path: wildcard search (fastest when server supports it)
const fetched = await searchSubsonic({ q: '*', count, offset: 0 })
setSongs(fetched)
return
} catch {
// Fallback path: album browse + album detail flattening
// Some Subsonic-compatible servers reject wildcard search queries.
}
const estimatedSongsPerAlbum = 10
const albumFetchSize = Math.min(80, Math.max(20, Math.ceil(count / estimatedSongsPerAlbum)))
const albums = await listSubsonicAlbums({ offset: 0, size: albumFetchSize })
const details = await Promise.all(
albums.map((album) => getSubsonicAlbum(album.id).catch(() => null))
)
for (const detail of details) {
if (!detail) continue
for (const song of detail.songs) {
if (!dedupe.has(song.id)) dedupe.set(song.id, song)
if (dedupe.size >= count) break
}
if (dedupe.size >= count) break
}
setSongs(Array.from(dedupe.values()))
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load Subsonic library')
setSongs([])
} finally {
setLoading(false)
}
}, [count])
useEffect(() => {
refresh()
}, [refresh])
return { songs, loading, configured, error, refresh }
}