From 383e20226ff5862217d6cb9d8e977e68d8cf6779 Mon Sep 17 00:00:00 2001 From: az3ta <24527778+az3ta@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:59:12 +0100 Subject: [PATCH] feat(radio): play pasted stream links in Single --- .../radio/dj/external-search/search-input.tsx | 2 +- .../radio/node/node-inspector.test.tsx | 4 +- .../components/radio/node/station-content.tsx | 1 - .../src/components/radio/radio-search-bar.tsx | 2 +- .../radio/single/single-player.test.tsx | 200 ++++++++++++++++++ .../components/radio/single/single-player.tsx | 20 ++ .../src/lib/collections/session-radios.ts | 6 +- apps/radio/src/lib/node-source-loaders.ts | 36 +--- .../src/lib/stations/stream-station-loader.ts | 36 ++++ 9 files changed, 268 insertions(+), 39 deletions(-) create mode 100644 apps/radio/src/components/radio/single/single-player.test.tsx create mode 100644 apps/radio/src/lib/stations/stream-station-loader.ts diff --git a/apps/radio/src/components/radio/dj/external-search/search-input.tsx b/apps/radio/src/components/radio/dj/external-search/search-input.tsx index 8869a757f..ee28aaa57 100644 --- a/apps/radio/src/components/radio/dj/external-search/search-input.tsx +++ b/apps/radio/src/components/radio/dj/external-search/search-input.tsx @@ -238,7 +238,7 @@ export function SearchInput({ isSearching={isPending} maxLength={2048} onChange={handleQueryChange} - placeholder="Search, or paste a link" + placeholder="Search or paste a link" value={query} /> diff --git a/apps/radio/src/components/radio/node/node-inspector.test.tsx b/apps/radio/src/components/radio/node/node-inspector.test.tsx index 8667613a6..c75c24df5 100644 --- a/apps/radio/src/components/radio/node/node-inspector.test.tsx +++ b/apps/radio/src/components/radio/node/node-inspector.test.tsx @@ -722,7 +722,9 @@ describe("NodeInspector", () => { fireEvent.click(view.getByRole("button", { name: "Close settings" })); }; checkSettings("Empty Station", () => - expect(view.getByPlaceholderText("Search or paste a stream")).toBeTruthy() + expect( + view.getByPlaceholderText("Search stations or paste a link") + ).toBeTruthy() ); checkSettings("Empty Track", () => expect(view.getByRole("combobox", { name: "Platform" })).toBeTruthy() diff --git a/apps/radio/src/components/radio/node/station-content.tsx b/apps/radio/src/components/radio/node/station-content.tsx index 6ee57f2a6..df7431ae3 100644 --- a/apps/radio/src/components/radio/node/station-content.tsx +++ b/apps/radio/src/components/radio/node/station-content.tsx @@ -91,7 +91,6 @@ function EmptyStation({ onSelectDiscovered={onSelectDiscovered} onSelectLocal={onSelectLocal} onSubmitUrl={onSubmitUrl} - placeholder="Search or paste a stream" radios={radios} /> diff --git a/apps/radio/src/components/radio/radio-search-bar.tsx b/apps/radio/src/components/radio/radio-search-bar.tsx index 7f084dabb..2370388e1 100644 --- a/apps/radio/src/components/radio/radio-search-bar.tsx +++ b/apps/radio/src/components/radio/radio-search-bar.tsx @@ -387,7 +387,7 @@ export function RadioSearchBar({ onSubmitUrl, className, dropdownClassName, - placeholder = "Search stations…", + placeholder = "Search stations or paste a link", }: RadioSearchBarProps) { const [query, setQuery] = useState(""); const [isOpen, setIsOpen] = useState(false); diff --git a/apps/radio/src/components/radio/single/single-player.test.tsx b/apps/radio/src/components/radio/single/single-player.test.tsx new file mode 100644 index 000000000..2607c7f8b --- /dev/null +++ b/apps/radio/src/components/radio/single/single-player.test.tsx @@ -0,0 +1,200 @@ +import { afterEach, beforeEach, expect, mock, spyOn, test } from "bun:test"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +// @ts-expect-error jsdom types are not installed in this workspace. +import { JSDOM } from "jsdom"; +import type { Radio } from "@/lib/audio"; +import { browserTestGlobals } from "@/test-utils/browser-globals"; + +if (process.env.RADIO_SINGLE_LINK_REGRESSION === "1") { + const dom = new JSDOM("", { + pretendToBeVisual: true, + url: "https://radio.test", + }); + for (const key of [ + "document", + "Element", + "HTMLElement", + "HTMLInputElement", + "HTMLFormElement", + "CustomEvent", + "DocumentFragment", + "MutationObserver", + "Node", + "NodeFilter", + "navigator", + "window", + "getComputedStyle", + ]) { + Object.defineProperty(globalThis, key, { + configurable: true, + value: dom.window[key], + writable: true, + }); + } + Object.assign(globalThis, browserTestGlobals(dom.window), { + IS_REACT_ACT_ENVIRONMENT: true, + ResizeObserver: class { + disconnect() { + // JSDOM does not perform layout. + } + observe() { + // JSDOM does not perform layout. + } + unobserve() { + // JSDOM does not perform layout. + } + }, + }); + Object.assign(CSS, { supports: () => false }); + const noop = () => undefined; + const playRadio = mock(async (_radio: Radio) => undefined); + mock.module("@/lib/hooks/use-single-session", () => ({ + useSingleSession: () => ({ + currentRadio: null, + playRadio, + selectRadio: noop, + setVolume: noop, + toggleMute: noop, + togglePlayPause: noop, + volume: 1, + }), + })); + mock.module("@/lib/hooks/use-media-session", () => ({ + useMediaSession: noop, + })); + mock.module("@/lib/hooks/use-radio-metadata", () => ({ + useRadioMetadata: () => ({ metadata: null }), + })); + mock.module("@/components/settings/radio-dialog", () => ({ + prefetchStationDialogOnIntent: noop, + RadioDialog: () => null, + })); + const { act, cleanup, fireEvent, render, waitFor } = await import( + "@testing-library/react" + ); + const { radiosCollection } = await import("@/lib/collections/radios"); + const { getSessionRadios, isSessionRadio, sessionRadiosCollection } = + await import("@/lib/collections/session-radios"); + const { stationIntake } = await import( + "@/lib/stations/external-station-workflow" + ); + const { SinglePlayer } = await import("./single-player"); + beforeEach(async () => { + await sessionRadiosCollection.stateWhenReady(); + playRadio.mockClear(); + }); + afterEach(() => { + cleanup(); + mock.restore(); + for (const id of sessionRadiosCollection.state.keys()) { + sessionRadiosCollection.delete(id); + } + }); + function renderPlayer() { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const view = render( + + + + ); + const search = view.getByRole("combobox", { + name: "Search stations", + }) as HTMLInputElement; + const type = (value: string) => { + fireEvent.focusIn(search); + fireEvent.change(search, { target: { value } }); + }; + return { search, type, view }; + } + + test.each(["https://stream.example/live", "https://stream.example/live.mp3"])( + "Single plays %s as a temporary station without saving it", + async (url) => { + const savedIds = [...radiosCollection.state.keys()]; + const { search, type, view } = renderPlayer(); + expect(search.placeholder).toBe("Search stations or paste a link"); + type(` ${url} `); + fireEvent.keyDown(search, { key: "Enter" }); + await waitFor(() => expect(playRadio).toHaveBeenCalledTimes(1)); + const [station] = getSessionRadios(); + expect(station).toMatchObject({ + id: "stream.example", + name: "stream.example", + streamUrl: url, + }); + expect(playRadio).toHaveBeenCalledWith(station); + expect(isSessionRadio(station)).toBe(true); + expect([...radiosCollection.state.keys()]).toEqual(savedIds); + await waitFor(() => expect(search.value).toBe("")); + fireEvent.click( + view.getByRole("button", { name: "Options for stream.example" }) + ); + expect(view.getByRole("menuitem", { name: "Save" })).toBeTruthy(); + fireEvent.click(view.getByRole("menuitem", { name: "Remove" })); + await waitFor(() => expect(getSessionRadios()).toEqual([])); + } + ); + + test.each([ + "https://www.youtube.com/watch?v=dQw4w9WgXcQ", + "https://youtu.be/dQw4w9WgXcQ", + "https://soundcloud.com/artist/track", + "https://artist.bandcamp.com/track/song", + ])("Single explains where platform links play: %s", async (url) => { + const createSession = spyOn(stationIntake, "createSession"); + const { search, type, view } = renderPlayer(); + type(url); + fireEvent.keyDown(search, { key: "Enter" }); + await waitFor(() => + expect(view.getByRole("alert").textContent).toBe( + "Platform links play in Node or DJ" + ) + ); + expect(createSession).not.toHaveBeenCalled(); + expect(playRadio).not.toHaveBeenCalled(); + expect(search.value).toBe(url); + type("another search"); + expect(view.queryByRole("alert")).toBeNull(); + }); + + test("changing the query cancels a stream before it is registered or played", async () => { + const { createSession } = stationIntake; + const pending = Promise.withResolvers(); + spyOn(stationIntake, "createSession").mockImplementation( + async (candidate, options) => { + await pending.promise; + return createSession(candidate, options); + } + ); + const { search, type } = renderPlayer(); + type("https://stream.example/live"); + fireEvent.keyDown(search, { key: "Enter" }); + type("changed"); + await act(async () => { + pending.resolve(); + await pending.promise; + }); + expect(playRadio).not.toHaveBeenCalled(); + expect(getSessionRadios()).toEqual([]); + expect(search.value).toBe("changed"); + }); +} else { + test("Single pasted-link regressions (isolated playback mocks)", async () => { + const child = Bun.spawn([process.execPath, "test", import.meta.path], { + env: { ...process.env, RADIO_SINGLE_LINK_REGRESSION: "1" }, + stderr: "pipe", + stdout: "pipe", + timeout: 20_000, + }); + const [stderr, exitCode] = await Promise.all([ + new Response(child.stderr).text(), + child.exited, + ]); + expect({ errors: exitCode ? stderr : "", exitCode }).toEqual({ + errors: "", + exitCode: 0, + }); + }, 25_000); +} diff --git a/apps/radio/src/components/radio/single/single-player.tsx b/apps/radio/src/components/radio/single/single-player.tsx index 31774ba6b..cf9690d90 100644 --- a/apps/radio/src/components/radio/single/single-player.tsx +++ b/apps/radio/src/components/radio/single/single-player.tsx @@ -11,6 +11,7 @@ import { LazyBoundary, lazyWithRetry } from "@/components/lazy-recovery"; import type { Radio } from "@/lib/audio"; import { isMediaVolumeLocked } from "@/lib/audio/playback/media-element-volume-control"; import { shouldUseNativeSinglePlayback } from "@/lib/collections/settings"; +import { detectPlatformFromUrl } from "@/lib/external-url/detect"; import { useDiscoveredStationActions } from "@/lib/hooks/use-discovered-station-actions"; import { useMediaSession } from "@/lib/hooks/use-media-session"; import { useRadioMetadata } from "@/lib/hooks/use-radio-metadata"; @@ -22,6 +23,7 @@ import { } from "@/lib/hooks/use-session-radios"; import { useAudioSettings } from "@/lib/hooks/use-settings"; import { useSingleSession } from "@/lib/hooks/use-single-session"; +import { loadStreamStation } from "@/lib/stations/stream-station-loader"; import { prefetchStationDialogOnIntent, RadioDialog, @@ -92,6 +94,23 @@ export function SinglePlayer({ radios }: SinglePlayerProps) { const { saveDiscoveredStation, selectDiscoveredStation } = useDiscoveredStationActions(playRadio); + const handleSubmitUrl = async (url: string, signal: AbortSignal) => { + const platform = detectPlatformFromUrl(url); + if (platform && platform !== "static-audio") { + return "Platform links play in Node or DJ"; + } + const isCurrent = () => !signal.aborted; + const loaded = await loadStreamStation(url, { isCurrent }); + if (!isCurrent()) { + return null; + } + if ("error" in loaded) { + return loaded.error; + } + await playRadio(loaded.radio); + return null; + }; + const [dialogOpen, setDialogOpen] = useState(false); const [dialogMode, setDialogMode] = useState<"create" | "edit">("create"); const [selectedRadio, setSelectedRadio] = useState(); @@ -220,6 +239,7 @@ export function SinglePlayer({ radios }: SinglePlayerProps) { onSaveDiscovered={saveDiscoveredStation} onSelectDiscovered={selectDiscoveredStation} onSelectLocal={playRadio} + onSubmitUrl={handleSubmitUrl} radios={radios ?? []} /> } diff --git a/apps/radio/src/lib/collections/session-radios.ts b/apps/radio/src/lib/collections/session-radios.ts index 331384f2f..e153e6b5b 100644 --- a/apps/radio/src/lib/collections/session-radios.ts +++ b/apps/radio/src/lib/collections/session-radios.ts @@ -164,7 +164,11 @@ export function isSessionRadio(radio: Radio): boolean { return false; } const id = String(radio.id); - return id.startsWith("rb_") || id.startsWith("rg_"); + return ( + id.startsWith("rb_") || + id.startsWith("rg_") || + sessionRadiosCollection.state.has(id) + ); } function getOrderedSessionRadioRecords(): SessionRadioRecord[] { diff --git a/apps/radio/src/lib/node-source-loaders.ts b/apps/radio/src/lib/node-source-loaders.ts index 8714876af..f03a5cf3b 100644 --- a/apps/radio/src/lib/node-source-loaders.ts +++ b/apps/radio/src/lib/node-source-loaders.ts @@ -37,6 +37,8 @@ import { stationIntake, } from "@/lib/stations/external-station-workflow"; +export { loadStreamStation } from "@/lib/stations/stream-station-loader"; + export type SourceLoad = { radio: Radio } | { error: string }; export type NodeSourceLoaderDependencies = { @@ -138,40 +140,6 @@ export async function loadLocalFile( } } -function streamName(url: string): string { - try { - return new URL(url).hostname || url; - } catch { - return url; - } -} - -/** - * A radio stream URL pasted into a Station, made a session station as a - * URL added in Settings would be, under its host's name. - */ -export async function loadStreamStation( - url: string, - { - createSession = stationIntake.createSession, - isCurrent, - }: NodeSourceLoaderDependencies = {} -): Promise { - const result = await createSession( - { - fields: { name: streamName(url), streamUrl: url }, - origin: "manual", - }, - { isCurrent } - ); - if (!result.ok) { - return { error: result.error.message }; - } - const { radio } = result.data; - // The session record is keyed by name when the radio has no id. - return { radio: { ...radio, id: radio.id ?? radio.name } }; -} - export async function loadLocalFiles( files: readonly File[], { loadFile = extractFileMetadata }: NodeSourceLoaderDependencies = {} diff --git a/apps/radio/src/lib/stations/stream-station-loader.ts b/apps/radio/src/lib/stations/stream-station-loader.ts new file mode 100644 index 000000000..90e0f5c91 --- /dev/null +++ b/apps/radio/src/lib/stations/stream-station-loader.ts @@ -0,0 +1,36 @@ +import type { Radio } from "@/lib/audio"; +import { stationIntake } from "./external-station-workflow"; + +function streamName(url: string): string { + try { + return new URL(url).hostname || url; + } catch { + return url; + } +} + +/** A pasted stream becomes a temporary station named after its host. */ +export async function loadStreamStation( + url: string, + { + createSession = stationIntake.createSession, + isCurrent, + }: { + createSession?: typeof stationIntake.createSession; + isCurrent?: () => boolean; + } = {} +): Promise<{ radio: Radio } | { error: string }> { + const result = await createSession( + { + fields: { name: streamName(url), streamUrl: url }, + origin: "manual", + }, + { isCurrent } + ); + if (!result.ok) { + return { error: result.error.message }; + } + const { radio } = result.data; + // The session record is keyed by name when the radio has no id. + return { radio: { ...radio, id: radio.id ?? radio.name } }; +}