import { useCallback, useContext, useState } from "react"; import { PlayerContext, type PlayerItem, } from "../../contexts/player/PlayerContext.ts"; import { BANDCAMP_PLAYER } from "../../config/playerMode.ts"; import { resolveBandcampQueue } from "../../utils/player/bandcamp.ts"; export interface PlayableRichContent { type: string; url: string; title?: string; embedUrl?: string; /** Header artwork. Callers with a dump-level override should pass that. */ thumbnailUrl?: string; /** Header subtitle — "YouTube", "SoundCloud", the site's own name. */ siteName?: string; } /** * Start playback for a rich-content item. * * Everything except Bandcamp goes straight to the iframe embed, exactly as * before. Bandcamp additionally honours GERBEUR_BANDCAMP_PLAYER: in "native" * mode the page is resolved to its mp3 streams and played as a queue, which is * what makes it autoplay and lets albums play through. Any failure — offline, * preorder-only release, Bandcamp changing its markup — falls back to the embed. * * Returns whether playback actually started. A native-mode page with no stored * embedUrl (an artist root, a /music index, a preorder) has nothing to fall * back to, and the caller has to be told so the click isn't swallowed. */ export function usePlayRichContent() { const { play, playQueue } = useContext(PlayerContext); const [pending, setPending] = useState(false); const playEmbed = useCallback( (rc: PlayableRichContent, dumpHref?: string): boolean => { if (!rc.embedUrl) return false; play({ kind: "embed", embedUrl: rc.embedUrl, title: rc.title, type: rc.type, dumpHref, artworkUrl: rc.thumbnailUrl, subtitle: rc.siteName, }); return true; }, [play], ); const playRichContent = useCallback( async (rc: PlayableRichContent, dumpHref?: string): Promise => { const native = rc.type === "bandcamp" && BANDCAMP_PLAYER === "native"; if (!native) return playEmbed(rc, dumpHref); setPending(true); try { const items: PlayerItem[] = await resolveBandcampQueue(rc.url, { dumpHref, embedUrl: rc.embedUrl, // Bandcamp's own album art wins; this is the fallback if the page // doesn't carry one. fallbackArtworkUrl: rc.thumbnailUrl, }); playQueue(items, 0); return true; } catch (err) { console.warn("bandcamp: native playback unavailable, using embed", err); return playEmbed(rc, dumpHref); } finally { setPending(false); } }, [playEmbed, playQueue], ); return { playRichContent, pending }; } /** * Whether a rich-content item can be played at all. In native mode a Bandcamp * page is playable even without a stored embedUrl, since the streams are * resolved from the page itself. */ export function canPlayRichContent(rc: PlayableRichContent): boolean { if (rc.embedUrl) return true; return rc.type === "bandcamp" && BANDCAMP_PLAYER === "native"; }