sonda/web/src/api/peaks.ts
tgiachi 7243fe7a04 feat: the seek bar shows the waveform of a friend's track
A friend's server works out the peaks of a track in a shared library and gives
them to a signed friend (GET /peer/tracks/{id}/peaks). This server asks for them
and passes them on to the listener after checking them: 1 to 1000 levels from 0
to 255, as many as the count says (GET /friends/{friend}/tracks/{id}/peaks). The
player uses it for a friend's track, so its bar is no longer flat.
2026-11-13 19:46:37 +01:00

35 lines
1.6 KiB
TypeScript

import { useQuery } from '@tanstack/react-query'
import { ApiError, api } from './client'
/** What the server answers while it is still working the shape out (202). */
interface Working {
status: 'working'
}
interface Shape {
count: number
peaks: number[]
}
/** How long to wait before asking again while the server works (it also says so in Retry-After). */
const POLL_MS = 3000
/**
* The shape of a track, from 0 to 255 for each of its bars: how loud it is along its length. The server works it out
* the first time it is asked for, so until then this is `undefined` and the question is asked again every few seconds.
* A track whose shape cannot be had stays without one. For a friend's track pass the `friend`: this server asks the
* friend's, and the track id is the friend's own.
*/
export function usePeaks(trackId: number | null, opts: { friend?: number; enabled?: boolean; pollMs?: number } = {}): number[] | undefined {
const { friend, enabled = true, pollMs = POLL_MS } = opts
const query = useQuery({
queryKey: ['peaks', friend ?? null, trackId],
enabled: enabled && trackId !== null,
retry: false,
// A shape does not change while the file does not: keep it for as long as the page lives.
staleTime: Infinity,
queryFn: () => api.get<Shape | Working>(friend === undefined ? `/tracks/${trackId}/peaks` : `/friends/${friend}/tracks/${trackId}/peaks`),
refetchInterval: (q) => ('status' in (q.state.data ?? {}) ? pollMs : false),
})
if (query.error instanceof ApiError || query.data === undefined || 'status' in query.data) return undefined
return query.data.peaks
}