Commit 27f06c50 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Stream audio directly with a token query param instead of downloading a blob first

Matches the backend fix: every fetchXStreamUrl (library, soundmarks, posts,
live-location, rooms) used to fetch the entire audio file as a blob before
handing <audio> a src, since a plain <audio src="..."> can't send an
Authorization header - so playback couldn't start until the whole file had
downloaded, and seeking didn't work at all. They now return a direct URL
(api/client.ts's new buildStreamUrl, token as ?token=) that the browser
streams natively - playback starts after the first buffered chunk, and
seeking uses real Range requests. Removed the now-dead objectUrlRef/
revokeObjectURL bookkeeping from PlayerContext.tsx.

Also adds a General QOL column to the Roadmap page (streaming fix, plus
grounded gaps found while looking: no volume control, no global error
boundary, no offline handling, inconsistent loading states, playback state
not persisted across reloads) and updates test counts.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent eac69cde
Pipeline #1086 canceled with stage
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { apiFetch, ApiError, clearTokens, getAccessToken, setTokens } from './client'
import { apiFetch, ApiError, API_BASE_URL, buildStreamUrl, clearTokens, getAccessToken, setTokens } from './client'
function jsonResponse(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), {
......@@ -160,3 +160,28 @@ describe('apiFetch', () => {
expect(fetch).toHaveBeenCalledTimes(5) // not 6 - the refresh call itself was shared
})
})
describe('buildStreamUrl', () => {
beforeEach(() => {
clearTokens()
})
it('appends the access token as a query param, not a header', () => {
setTokens('access-123', 'refresh-456')
expect(buildStreamUrl('/library/stream/42')).toBe(`${API_BASE_URL}/library/stream/42?token=access-123`)
})
it('uses & when the path already has a query string', () => {
setTokens('access-123', 'refresh-456')
expect(buildStreamUrl('/soundmarks/5/stream?foo=bar')).toBe(`${API_BASE_URL}/soundmarks/5/stream?foo=bar&token=access-123`)
})
it('url-encodes the token', () => {
setTokens('a.b+c/d', 'refresh-456')
expect(buildStreamUrl('/library/stream/1')).toBe(`${API_BASE_URL}/library/stream/1?token=a.b%2Bc%2Fd`)
})
it('omits the token param entirely when logged out', () => {
expect(buildStreamUrl('/library/stream/42')).toBe(`${API_BASE_URL}/library/stream/42`)
})
})
......@@ -121,4 +121,22 @@ export async function apiFetch<T = unknown>(path: string, options: RequestOption
return res.json() as Promise<T>
}
/** Builds a direct, same-origin/absolute URL for a streaming GET endpoint, with the access
* token attached as a `?token=` query param instead of an Authorization header - a plain
* <audio src="..."> can't send custom headers (browsers don't attach one to media element
* requests), so the token has to travel in the URL for direct streaming to work at all. The
* backend's get_current_user_for_stream accepts either form; only read-only GET media
* endpoints should use this pattern (see that function's docstring for why).
*
* Handing the browser a real URL like this - instead of fetching the whole file as a blob
* first - is what lets it use its native HTTP client: playback can start after the first
* buffered chunk instead of waiting for the entire file, and seeking works via real Range
* requests instead of not working at all. */
export function buildStreamUrl(path: string): string {
const token = getAccessToken()
if (!token) return `${API_BASE_URL}${path}`
const separator = path.includes('?') ? '&' : '?'
return `${API_BASE_URL}${path}${separator}token=${encodeURIComponent(token)}`
}
export { API_BASE_URL }
import { API_BASE_URL, apiFetch, getAccessToken } from './client'
import { apiFetch, buildStreamUrl } from './client'
export interface SocialSong {
id: number
......@@ -42,19 +42,11 @@ export function getPostTree(postId: number) {
return apiFetch<PostTree>(`/social/posts/${postId}/tree`)
}
/** For PlayerContext's `streamUrl` override - fetches a post's song as an authenticated blob,
* regardless of who uploaded it (a post's song_id isn't necessarily the poster's own library
* song). Caller is responsible for calling URL.revokeObjectURL(). */
/** For PlayerContext's `streamUrl` override - a direct, token-authenticated URL for a post's
* song, regardless of who uploaded it (a post's song_id isn't necessarily the poster's own
* library song). See buildStreamUrl for why this is a direct URL rather than a blob fetch. */
export async function fetchPostStreamUrl(postId: number): Promise<string> {
const token = getAccessToken()
const res = await fetch(`${API_BASE_URL}/social/posts/${postId}/stream`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
})
if (!res.ok) {
throw new Error(`Failed to load audio (${res.status})`)
}
const blob = await res.blob()
return URL.createObjectURL(blob)
return buildStreamUrl(`/social/posts/${postId}/stream`)
}
export interface LiveListener {
......@@ -92,20 +84,11 @@ export function getNearbyLiveListeners(lat: number, lon: number, radiusKm = 5) {
)
}
/** For PlayerContext's `streamUrl` override - fetches whatever a nearby user is currently
* playing as an authenticated blob, regardless of who uploaded it (mirrors
* fetchRoomStreamUrl/fetchSoundmarkStreamUrl against the analogous endpoint). Caller is
* responsible for calling URL.revokeObjectURL(). */
/** For PlayerContext's `streamUrl` override - a direct, token-authenticated URL for whatever
* a nearby user is currently playing, regardless of who uploaded it (mirrors
* fetchRoomStreamUrl/fetchSoundmarkStreamUrl against the analogous endpoint). */
export async function fetchLiveLocationStreamUrl(userId: number): Promise<string> {
const token = getAccessToken()
const res = await fetch(`${API_BASE_URL}/social/live-location/${userId}/stream`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
})
if (!res.ok) {
throw new Error(`Failed to load audio (${res.status})`)
}
const blob = await res.blob()
return URL.createObjectURL(blob)
return buildStreamUrl(`/social/live-location/${userId}/stream`)
}
export interface LiveRoom {
......@@ -125,18 +108,9 @@ export function createRoom(name: string) {
return apiFetch<LiveRoom>('/social/rooms', { method: 'POST', json: { name } })
}
/** For PlayerContext's `streamUrl` override - fetches whatever's currently playing in a room
* as an authenticated blob, regardless of who uploaded the underlying song (mirrors
* api/soundmarks.ts's fetchSoundmarkStreamUrl against the analogous room-scoped endpoint).
* Caller is responsible for calling URL.revokeObjectURL() when done. */
/** For PlayerContext's `streamUrl` override - a direct, token-authenticated URL for whatever's
* currently playing in a room, regardless of who uploaded the underlying song (mirrors
* api/soundmarks.ts's fetchSoundmarkStreamUrl against the analogous room-scoped endpoint). */
export async function fetchRoomStreamUrl(roomId: number): Promise<string> {
const token = getAccessToken()
const res = await fetch(`${API_BASE_URL}/social/rooms/${roomId}/stream`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
})
if (!res.ok) {
throw new Error(`Failed to load audio (${res.status})`)
}
const blob = await res.blob()
return URL.createObjectURL(blob)
return buildStreamUrl(`/social/rooms/${roomId}/stream`)
}
import { API_BASE_URL, apiFetch, getAccessToken } from './client'
import { apiFetch, buildStreamUrl } from './client'
export interface SoundmarkSong {
id: number
......@@ -136,20 +136,12 @@ export function updateUserRole(userId: number, role: string) {
)
}
/** For PlayerContext's `streamUrl` override - fetches a soundmark's anthem as an authenticated
* blob and returns an object URL, mirroring api/stream.ts's fetchStreamUrl but against the
* soundmark-specific endpoint (streamable regardless of who uploaded the underlying song).
* Caller is responsible for calling URL.revokeObjectURL() when done, same as fetchStreamUrl. */
/** For PlayerContext's `streamUrl` override - a direct, token-authenticated URL for a
* soundmark's anthem (streamable regardless of who uploaded the underlying song), mirroring
* api/stream.ts's fetchStreamUrl but against the soundmark-specific endpoint. See
* buildStreamUrl for why this is a direct URL rather than a blob fetch. */
export async function fetchSoundmarkStreamUrl(soundmarkId: number): Promise<string> {
const token = getAccessToken()
const res = await fetch(`${API_BASE_URL}/soundmarks/${soundmarkId}/stream`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
})
if (!res.ok) {
throw new Error(`Failed to load audio (${res.status})`)
}
const blob = await res.blob()
return URL.createObjectURL(blob)
return buildStreamUrl(`/soundmarks/${soundmarkId}/stream`)
}
export interface GeocodeResult {
......
import { API_BASE_URL, getAccessToken } from './client'
import { buildStreamUrl } from './client'
/**
* /library/stream/{id} requires a Bearer auth header, which a plain <audio src="..."> can't
* send - browsers don't attach custom headers to media element requests. Fetch it as a blob
* with the header attached instead, and hand back an object URL for the <audio> tag to use.
* Caller is responsible for calling URL.revokeObjectURL() on it when done (e.g. on unmount).
* /library/stream/{id} requires an authenticated caller, which a plain <audio src="..."> can't
* provide via a header - the token travels as a query param instead (see buildStreamUrl). The
* browser streams the URL directly, so playback can start as soon as the first chunk is
* buffered and seeking works via real Range requests.
*/
export async function fetchStreamUrl(fileId: number): Promise<string> {
const token = getAccessToken()
const res = await fetch(`${API_BASE_URL}/library/stream/${fileId}`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
})
if (!res.ok) {
throw new Error(`Failed to load audio (${res.status})`)
}
const blob = await res.blob()
return URL.createObjectURL(blob)
return buildStreamUrl(`/library/stream/${fileId}`)
}
......@@ -12,12 +12,15 @@ export interface PlayableSong {
album?: string | null
coverart?: string | null
lyrics?: string | null
/** Overrides how the audio URL is fetched - used for sources that aren't a plain
* LibrarySong id, e.g. a Soundmark's anthem (streamed via /soundmarks/{id}/stream and
* playable regardless of who originally uploaded the underlying song, unlike the default
* /library/stream/{id} path). When set, `id` only needs to be unique for play/pause
* identity purposes - callers should give it a value that can't collide with a real
* LibrarySong id (e.g. negate a soundmark's own id) since it's never used to fetch audio. */
/** Overrides which URL is streamed - used for sources that aren't a plain LibrarySong id,
* e.g. a Soundmark's anthem (streamed via /soundmarks/{id}/stream and playable regardless
* of who originally uploaded the underlying song, unlike the default /library/stream/{id}
* path). When set, `id` only needs to be unique for play/pause identity purposes - callers
* should give it a value that can't collide with a real LibrarySong id (e.g. negate a
* soundmark's own id) since it's never used to fetch audio. The returned URL is a direct,
* token-authenticated stream URL (see api/client.ts's buildStreamUrl) - not a blob - so the
* browser can start playing before the whole file downloads and can seek via Range
* requests. */
streamUrl?: () => Promise<string>
}
......@@ -76,7 +79,6 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
const [repeatMode, setRepeatMode] = useState<RepeatMode>('off')
const [playbackError, setPlaybackError] = useState<string | null>(null)
const audioRef = useRef<HTMLAudioElement | null>(null)
const objectUrlRef = useRef<string | null>(null)
// The queue as originally handed to toggle(), before any shuffling - restored when shuffle
// is turned back off.
const originalQueueRef = useRef<PlayableSong[]>([])
......@@ -99,12 +101,7 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
const streamUrlPromise = song.streamUrl ? song.streamUrl() : fetchStreamUrl(song.id)
streamUrlPromise
.then((url) => {
if (requestId !== requestIdRef.current) {
URL.revokeObjectURL(url) // a newer play request already superseded this one
return
}
if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current)
objectUrlRef.current = url
if (requestId !== requestIdRef.current) return // a newer play request already superseded this one
audio.src = url
return audio.play().then(() => {
if (requestId === requestIdRef.current) setIsPlaying(true)
......@@ -173,7 +170,6 @@ export function PlayerProvider({ children }: { children: ReactNode }) {
audio.removeEventListener('timeupdate', onTimeUpdate)
audio.removeEventListener('loadedmetadata', onLoadedMetadata)
audio.pause()
if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current)
}
}, [])
......
......@@ -156,6 +156,20 @@ const ROADMAP_COLUMNS: { title: string; sub: string; dot: string; items: string[
'Telegram chat scanning — auto-scan all or user-approved linked chats for music, tag and save straight into the library, instead of the current one-chat-at-a-time /auth/telegram/chats/{id}/music lookup.',
],
},
{
title: 'General QOL',
sub: 'Polish, not features',
dot: 'bg-sky-400',
items: [
'Fixed: audio now streams directly instead of downloading the whole file first — see "Recently fixed" above.',
'No volume control anywhere in the player — always whatever the OS/browser last had it at.',
'No global error boundary — an unhandled render error white-screens the whole app with no recovery UI, not even a reload prompt.',
'No offline/connectivity-loss handling — a dropped connection just makes requests silently fail one at a time.',
"Loading states are inconsistent across pages — some show a spinner, others just render empty until data arrives.",
"Only one destructive action (deleting a soundmark) has a confirm dialog — worth an explicit pass once more delete endpoints exist (see Ideas).",
'Playback position/volume isn\'t remembered across a reload - every fresh page load starts silent from 0:00.',
],
},
]
export function Roadmap() {
......@@ -171,8 +185,8 @@ export function Roadmap() {
{[
['9', 'Feature areas'],
['0', 'Critical security gaps'],
['202', 'Backend tests'],
['148', 'Frontend tests'],
['206', 'Backend tests'],
['152', 'Frontend tests'],
['4', 'Pages w/ zero tests'],
].map(([n, l]) => (
<div key={l}>
......@@ -221,6 +235,24 @@ export function Roadmap() {
</div>
</div>
</div>
<div className="rounded-xl border border-emerald-900/50 bg-emerald-950/20 p-4">
<div className="flex items-start gap-3">
<ShieldCheck size={16} strokeWidth={2} className="mt-0.5 shrink-0 text-emerald-400" />
<div>
<p className="mb-1 text-sm font-semibold text-white">Every audio source now streams directly instead of downloading first</p>
<p className="text-sm leading-relaxed text-neutral-400">
All five stream endpoints (library, soundmarks, posts, live-location, rooms) were fetched as a full blob
before playback could start at all — a 5MB track meant waiting for all 5MB before hearing a single
second, with no seeking. <code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">{'<audio src>'}</code>{' '}
can't send an Authorization header, which is why the blob fetch existed in the first place — fixed by
accepting the access token as a{' '}
<code className="rounded bg-neutral-800 px-1.5 py-0.5 text-xs text-neutral-200">?token=</code> query param too
(same pattern as the Rooms websocket fix above) so the browser can stream the URL directly: playback starts
after the first buffered chunk, and seeking uses real HTTP Range requests.
</p>
</div>
</div>
</div>
</div>
</section>
......@@ -267,7 +299,7 @@ export function Roadmap() {
<h2 className="text-xs font-bold uppercase tracking-wide text-neutral-500">What's next</h2>
<span className="text-xs text-neutral-500">Ordered by urgency, left to right</span>
</div>
<div className="grid gap-3 md:grid-cols-3">
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
{ROADMAP_COLUMNS.map((col) => (
<div key={col.title} className="rounded-xl border border-neutral-800 bg-neutral-900">
<div className="flex items-center gap-2 border-b border-neutral-800 px-4 py-3">
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment