149 lines
4.0 KiB
TypeScript
149 lines
4.0 KiB
TypeScript
import { api } from "../convex/_generated/api"
|
|
import type { Id } from "../convex/_generated/dataModel"
|
|
import type { BrowseAlbumDetail, BrowseSong } from "../convex/types"
|
|
import type { QueryClient } from "./cached-query"
|
|
import { readCache, subscribeCacheLoaded, writeCache } from "./persistent-cache"
|
|
|
|
const FETCH_BATCH_SIZE = 100
|
|
const FETCH_DELAY_MS = 16
|
|
|
|
const listeners = new Set<() => void>()
|
|
const missingSongIds = new Set<string>()
|
|
const inFlightSongIds = new Set<string>()
|
|
const queuedSongIds = new Set<Id<"songs">>()
|
|
let version = 0
|
|
let fetchTimer: ReturnType<typeof setTimeout> | null = null
|
|
|
|
function songKey(songId: string) {
|
|
return `song:${songId}`
|
|
}
|
|
|
|
function notify() {
|
|
version += 1
|
|
for (const listener of listeners) {
|
|
listener()
|
|
}
|
|
}
|
|
|
|
if (typeof window !== "undefined") {
|
|
subscribeCacheLoaded(notify)
|
|
}
|
|
|
|
export function subscribeSongs(listener: () => void) {
|
|
listeners.add(listener)
|
|
return () => {
|
|
listeners.delete(listener)
|
|
}
|
|
}
|
|
|
|
/** Changes whenever any cached song changes. */
|
|
export function getSongsVersion() {
|
|
return version
|
|
}
|
|
|
|
function sameSong(a: BrowseSong, b: BrowseSong) {
|
|
return (
|
|
a.title === b.title &&
|
|
a.durationSeconds === b.durationSeconds &&
|
|
a.explicit === b.explicit &&
|
|
a.artist.id === b.artist.id &&
|
|
a.artist.name === b.artist.name &&
|
|
a.artist.photo === b.artist.photo &&
|
|
a.album.id === b.album.id &&
|
|
a.album.title === b.album.title &&
|
|
a.album.cover === b.album.cover
|
|
)
|
|
}
|
|
|
|
export function getCachedSong(songId: string) {
|
|
return readCache<BrowseSong>(songKey(songId))
|
|
}
|
|
|
|
/**
|
|
* `useSyncExternalStore` snapshot for one song: the song once cached, else the
|
|
* cache version, so a missing song re-renders on every cache change (to retry
|
|
* the fetch) and a cached one only when it changes.
|
|
*/
|
|
export function getSongSnapshot(songId: string | null) {
|
|
return songId ? (getCachedSong(songId) ?? version) : null
|
|
}
|
|
|
|
export function songFromSnapshot(snapshot: ReturnType<typeof getSongSnapshot>) {
|
|
return typeof snapshot === "object" ? snapshot : null
|
|
}
|
|
|
|
/** Stores song metadata so the player and queue can render it offline. */
|
|
export function rememberSongs(songs: readonly BrowseSong[]) {
|
|
let changed = false
|
|
for (const song of songs) {
|
|
const existing = getCachedSong(song.id)
|
|
if (existing && sameSong(existing, song)) {
|
|
continue
|
|
}
|
|
writeCache(songKey(song.id), song)
|
|
missingSongIds.delete(song.id)
|
|
changed = true
|
|
}
|
|
if (changed) {
|
|
notify()
|
|
}
|
|
}
|
|
|
|
export function albumDetailSongs(album: BrowseAlbumDetail): BrowseSong[] {
|
|
return album.tracks.map((track) => ({
|
|
id: track.id,
|
|
title: track.title,
|
|
artist: album.artist,
|
|
album: { id: album.id, title: album.title, cover: album.cover },
|
|
durationSeconds: track.durationSeconds,
|
|
}))
|
|
}
|
|
|
|
async function fetchQueuedSongs(convex: QueryClient) {
|
|
fetchTimer = null
|
|
const ids = [...queuedSongIds]
|
|
queuedSongIds.clear()
|
|
|
|
for (let start = 0; start < ids.length; start += FETCH_BATCH_SIZE) {
|
|
const batch = ids.slice(start, start + FETCH_BATCH_SIZE)
|
|
try {
|
|
const songs = await convex.query(api.library.browseSongsByIds, {
|
|
ids: batch,
|
|
})
|
|
const found = new Set(songs.map((song) => song.id as string))
|
|
for (const id of batch) {
|
|
if (!found.has(id)) {
|
|
missingSongIds.add(id)
|
|
}
|
|
}
|
|
rememberSongs(songs)
|
|
} catch {
|
|
// Leave them uncached so a later render retries.
|
|
} finally {
|
|
for (const id of batch) {
|
|
inFlightSongIds.delete(id)
|
|
}
|
|
}
|
|
}
|
|
notify()
|
|
}
|
|
|
|
/** Fetches metadata for songs that are not cached yet, in batches. */
|
|
export function requestSongs(convex: QueryClient, songIds: Id<"songs">[]) {
|
|
for (const songId of songIds) {
|
|
if (
|
|
getCachedSong(songId) ||
|
|
missingSongIds.has(songId) ||
|
|
inFlightSongIds.has(songId)
|
|
) {
|
|
continue
|
|
}
|
|
inFlightSongIds.add(songId)
|
|
queuedSongIds.add(songId)
|
|
}
|
|
|
|
if (queuedSongIds.size > 0 && fetchTimer === null) {
|
|
fetchTimer = setTimeout(() => void fetchQueuedSongs(convex), FETCH_DELAY_MS)
|
|
}
|
|
}
|