Play new songs from YouTube in the browser

YouTube's bot checks block yt-dlp from fetching audio on the server, so
suggested songs now play in YouTube's embedded player, kept out of sight,
in the browser. yt-dlp is only used to search.

- GET /api/discover/youtube/<id> returns candidate video IDs, best first,
  or the one that played before (?refresh=true searches again).
- PUT /api/discover/youtube/<id> remembers the video that played.
- The UI tries the next candidate when a video can't be embedded, searches
  again when a remembered video is gone, and skips the song otherwise.
- Drop the YouTube audio proxy, and Deno from the image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
judeandClaude Opus 5.5 committed 2026-11-23 10:59:40 +00:00
1 parent 93e12cfc72
commit c84e7e715d
11 files changed
+478 -164

No files matched your search

+1 -1
View File
@@ -28,7 +28,7 @@ sha2 = "0.10"
[package.metadata.deb] [package.metadata.deb]
depends = "$auto" depends = "$auto"
# plays suggested songs from YouTube. Distribution packages may be too old to work with YouTube, # finds suggested songs on YouTube. Distribution packages may be too old to work with YouTube,
# so it's only recommended: a current yt-dlp from elsewhere (e.g. pip) works too # so it's only recommended: a current yt-dlp from elsewhere (e.g. pip) works too
recommends = "yt-dlp" recommends = "yt-dlp"
assets = [ assets = [
+1 -3
View File
@@ -25,14 +25,12 @@ RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates libssl3 python3 python3-venv \ && apt-get install -y --no-install-recommends ca-certificates libssl3 python3 python3-venv \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# yt-dlp plays suggested songs from YouTube. It has to be recent to keep working with YouTube, so # yt-dlp finds suggested songs on YouTube. It has to be recent to keep working with YouTube, so
# the latest version is installed: rebuild the image to update it, or set YTDLP_VERSION to pin one. # the latest version is installed: rebuild the image to update it, or set YTDLP_VERSION to pin one.
ARG YTDLP_VERSION= ARG YTDLP_VERSION=
RUN python3 -m venv /opt/yt-dlp \ RUN python3 -m venv /opt/yt-dlp \
&& /opt/yt-dlp/bin/pip install --no-cache-dir "yt-dlp[default]${YTDLP_VERSION:+==${YTDLP_VERSION}}" \ && /opt/yt-dlp/bin/pip install --no-cache-dir "yt-dlp[default]${YTDLP_VERSION:+==${YTDLP_VERSION}}" \
&& ln -s /opt/yt-dlp/bin/yt-dlp /usr/local/bin/yt-dlp && ln -s /opt/yt-dlp/bin/yt-dlp /usr/local/bin/yt-dlp
# yt-dlp needs a JavaScript runtime for YouTube; Deno is the one it uses by default
COPY --from=denoland/deno:bin-2.9.8 /deno /usr/local/bin/deno
COPY --from=server /src/target/release/playlistd /usr/local/bin/playlistd COPY --from=server /src/target/release/playlistd /usr/local/bin/playlistd
COPY --from=ui /src/dist /usr/share/playlistd/discover COPY --from=ui /src/dist /usr/share/playlistd/discover
+15 -9
View File
@@ -24,8 +24,8 @@ otherwise against the query data in `.sqlx/`. After changing a query, update tha
### Docker Compose ### Docker Compose
`compose.yaml` runs playlistd with its own Postgres database. The image includes the web UI, `compose.yaml` runs playlistd with its own Postgres database. The image includes the web UI and
yt-dlp and Deno (which yt-dlp needs for YouTube). yt-dlp (for finding new songs on YouTube).
```sh ```sh
cp .env.example .env # then fill in your Subsonic server and a database password cp .env.example .env # then fill in your Subsonic server and a database password
@@ -39,8 +39,8 @@ your network. If your
Subsonic server runs on the Docker host, use `http://host.docker.internal:4533/rest` as Subsonic server runs on the Docker host, use `http://host.docker.internal:4533/rest` as
`SUBSONIC_BASE`. `SUBSONIC_BASE`.
YouTube changes often break older yt-dlp versions, and the image installs the latest one when it's YouTube changes can break older yt-dlp versions, and the image installs the latest one when it's
built, so rebuild it now and then to keep new songs playing: built, so rebuild it now and then to keep finding new songs:
```sh ```sh
docker compose build --pull && docker compose up -d docker compose build --pull && docker compose up -d
@@ -74,7 +74,7 @@ The package is written to `target/debian/`. It installs the web UI to `/usr/shar
which the default config serves at `/`. `cargo deb` refuses to build the package if the UI hasn't been which the default config serves at `/`. `cargo deb` refuses to build the package if the UI hasn't been
built. built.
The package recommends `yt-dlp`, for playing suggested songs from YouTube. Distribution packages of The package recommends `yt-dlp`, for finding suggested songs on YouTube. Distribution packages of
yt-dlp are often too old to work with YouTube, so you may want a current one instead, e.g. from pip. yt-dlp are often too old to work with YouTube, so you may want a current one instead, e.g. from pip.
### Logging ### Logging
@@ -191,9 +191,14 @@ Every candidate's MusicBrainz genres are compared with each mix's, and it's sugg
it fits best (if it fits well enough), skipping songs already in your library. it fits best (if it fits well enough), skipping songs already in your library.
In the UI, songs from your library stream from Subsonic. New songs are found on YouTube with In the UI, songs from your library stream from Subsonic. New songs are found on YouTube with
[yt-dlp](https://github.com/yt-dlp/yt-dlp) and streamed through playlistd, so yt-dlp needs to be [yt-dlp](https://github.com/yt-dlp/yt-dlp) on the server (keep it up to date: YouTube changes can
installed on the server (keep it up to date: YouTube changes often break older versions). You can break older versions), and play in the browser, in YouTube's embedded player kept out of sight.
like a new song to keep it in "Liked new songs", or hide it so it isn't suggested again. Playing them from the browser, rather than the server, keeps YouTube's bot checks from blocking
them. If the first video found can't be embedded, the next search result is tried. You can like a
new song to keep it in "Liked new songs", or hide it so it isn't suggested again.
Mobile browsers pause embedded YouTube videos when the screen locks or the tab is in the
background, so new songs only play while the UI is open.
"Play mix" plays a mix's new songs in random order with songs you already know (the songs in the "Play mix" plays a mix's new songs in random order with songs you already know (the songs in the
mix you've played recently) mixed in evenly, so that `familiar_ratio` of what you hear is familiar. mix you've played recently) mixed in evenly, so that `familiar_ratio` of what you hear is familiar.
@@ -261,7 +266,8 @@ The UI uses these endpoints under `/api/discover`:
| `POST /rules/<id>/rebuild` | Rebuild a rule's mixes on the next daemon tick | | `POST /rules/<id>/rebuild` | Rebuild a rule's mixes on the next daemon tick |
| `GET /stream/<song id>` | Stream a library song from Subsonic | | `GET /stream/<song id>` | Stream a library song from Subsonic |
| `GET /cover/<cover art id>` | Library cover art from Subsonic | | `GET /cover/<cover art id>` | Library cover art from Subsonic |
| `GET /youtube/<suggestion id>` | Stream a suggested song from YouTube | | `GET /youtube/<suggestion id>?refresh=` | YouTube videos for a suggestion, best first (`refresh` searches again) |
| `PUT /youtube/<suggestion id>` | Remember the video that played (`video_id`) |
and these under `/api/tracked` for tracked playlists: and these under `/api/tracked` for tracked playlists:
+6 -1
View File
@@ -96,12 +96,17 @@ export const api = {
body: JSON.stringify({ status }), body: JSON.stringify({ status }),
}), }),
rebuild: (ruleId: string) => request<void>(`/rules/${ruleId}/rebuild`, { method: "POST" }), rebuild: (ruleId: string) => request<void>(`/rules/${ruleId}/rebuild`, { method: "POST" }),
/** Videos to play a suggestion with, best first. `refresh` searches again. */
youtubeVideos: (suggestionId: string, refresh = false) =>
request<{ video_ids: string[]; cached: boolean }>(`/youtube/${suggestionId}?refresh=${refresh}`),
/** The video that played, when it wasn't the first one */
setYoutubeVideo: (suggestionId: string, videoId: string) =>
request<void>(`/youtube/${suggestionId}`, json("PUT", { video_id: videoId })),
}; };
export const coverUrl = (coverArt: string, size = 120) => export const coverUrl = (coverArt: string, size = 120) =>
`/api/discover/cover/${encodeURIComponent(coverArt)}?size=${size}`; `/api/discover/cover/${encodeURIComponent(coverArt)}?size=${size}`;
export const streamUrl = (songId: string) => `/api/discover/stream/${encodeURIComponent(songId)}`; export const streamUrl = (songId: string) => `/api/discover/stream/${encodeURIComponent(songId)}`;
export const youtubeUrl = (suggestionId: string) => `/api/discover/youtube/${suggestionId}`;
/** "Mix: Pop Punk / Emo" -> "Pop Punk / Emo" */ /** "Mix: Pop Punk / Emo" -> "Pop Punk / Emo" */
export const mixTitle = (mix: MixSummary) => export const mixTitle = (mix: MixSummary) =>
+3 -2
View File
@@ -1,8 +1,9 @@
import { coverUrl, Song, streamUrl, Suggestion, youtubeUrl } from "./api"; import { coverUrl, Song, streamUrl, Suggestion } from "./api";
export type QueueItem = { export type QueueItem = {
key: string; key: string;
source: "library" | "youtube"; source: "library" | "youtube";
/** Audio to stream, for library songs. YouTube ones play from `suggestionId`. */
src: string; src: string;
title: string; title: string;
artist: string; artist: string;
@@ -24,7 +25,7 @@ export const fromSong = (song: Song): QueueItem => ({
export const fromSuggestion = (s: Suggestion): QueueItem => ({ export const fromSuggestion = (s: Suggestion): QueueItem => ({
key: `suggestion:${s.id}`, key: `suggestion:${s.id}`,
source: "youtube", source: "youtube",
src: youtubeUrl(s.id), src: "",
title: s.title, title: s.title,
artist: s.artist, artist: s.artist,
album: s.release, album: s.release,
+14
View File
@@ -1125,6 +1125,20 @@ h2 {
color: var(--accent); color: var(--accent);
} }
/* YouTube's player, for new songs: only the sound is wanted. Not display: none, as browsers
may not start or may throttle players that aren't rendered. */
.youtube-host {
position: fixed;
left: 0;
bottom: 0;
z-index: -1;
width: 1px;
height: 1px;
overflow: hidden;
opacity: 0;
pointer-events: none;
}
/* ---------- small screens ---------- */ /* ---------- small screens ---------- */
@media (max-width: 800px) { @media (max-width: 800px) {
+153 -28
View File
@@ -1,16 +1,32 @@
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { api } from "./api";
import { QueueItem } from "./queue"; import { QueueItem } from "./queue";
import { HiddenYouTubePlayer, State, YouTubeEvents } from "./youtubePlayer";
export type PlayerStatus = "idle" | "loading" | "playing" | "paused" | "error"; export type PlayerStatus = "idle" | "loading" | "playing" | "paused" | "error";
export type Player = ReturnType<typeof usePlayer>; export type Player = ReturnType<typeof usePlayer>;
/** The video being tried for the current YouTube item */
type YouTubeAttempt = {
suggestionId: string;
videoIds: string[];
at: number;
/** `videoIds` is the one video that played before, so a fresh search might find another */
cached: boolean;
};
/**
* Library songs play in an <audio> element, streamed from Subsonic through playlistd. New songs
* play from YouTube in a hidden embedded player, in the browser.
*/
export function usePlayer(onError: (item: QueueItem) => void) { export function usePlayer(onError: (item: QueueItem) => void) {
const audio = useRef<HTMLAudioElement | null>(null); const audio = useRef<HTMLAudioElement | null>(null);
if (audio.current === null && typeof Audio !== "undefined") { if (audio.current === null && typeof Audio !== "undefined") {
audio.current = new Audio(); audio.current = new Audio();
audio.current.preload = "auto"; audio.current.preload = "auto";
} }
const youtube = useRef<HiddenYouTubePlayer | null>(null);
const [queue, setQueue] = useState<QueueItem[]>([]); const [queue, setQueue] = useState<QueueItem[]>([]);
const [index, setIndex] = useState(-1); const [index, setIndex] = useState(-1);
@@ -18,10 +34,16 @@ export function usePlayer(onError: (item: QueueItem) => void) {
const [time, setTime] = useState(0); const [time, setTime] = useState(0);
const [duration, setDuration] = useState(0); const [duration, setDuration] = useState(0);
const current = index >= 0 ? queue[index] : undefined; const current = index >= 0 ? queue[index] : undefined;
const onYouTube = current?.source === "youtube";
// keep the latest values for the audio element's event handlers // counts loads, so a slow YouTube lookup for a song that's been skipped is ignored
const state = useRef({ queue, index, onError }); const loads = useRef(0);
state.current = { queue, index, onError }; const attempt = useRef<YouTubeAttempt | null>(null);
const errorTimer = useRef<number | undefined>();
// keep the latest values for event handlers
const state = useRef({ queue, index, onError, onYouTube });
state.current = { queue, index, onError, onYouTube };
const playAt = useCallback((items: QueueItem[], at: number) => { const playAt = useCallback((items: QueueItem[], at: number) => {
setQueue(items); setQueue(items);
@@ -33,45 +55,149 @@ export function usePlayer(onError: (item: QueueItem) => void) {
if (index + 1 < queue.length) setIndex(index + 1); if (index + 1 < queue.length) setIndex(index + 1);
else { else {
audio.current?.pause(); audio.current?.pause();
youtube.current?.pause();
setStatus("paused"); setStatus("paused");
} }
}, []); }, []);
const previous = useCallback(() => { /** Give up on the current item and move on */
const el = audio.current; const failed = useCallback(() => {
if (el && el.currentTime > 3) el.currentTime = 0; setStatus("error");
else setIndex((i) => Math.max(0, i - 1)); const { queue, index, onError } = state.current;
}, []); if (queue[index]) onError(queue[index]);
window.clearTimeout(errorTimer.current);
const toggle = useCallback(() => { errorTimer.current = window.setTimeout(next, 1500);
const el = audio.current; }, [next]);
if (!el || !state.current.queue.length) return;
if (el.paused) void el.play().catch(() => undefined);
else el.pause();
}, []);
const seek = useCallback((seconds: number) => { const seek = useCallback((seconds: number) => {
if (!audio.current) return; if (state.current.onYouTube) youtube.current?.seek(seconds);
audio.current.currentTime = seconds; else if (audio.current) audio.current.currentTime = seconds;
// update now, or the controlled slider snaps back and its change event seeks back too // update now, or the controlled slider snaps back and its change event seeks back too
setTime(seconds); setTime(seconds);
}, []); }, []);
// load the current item const previous = useCallback(() => {
const at = state.current.onYouTube ? youtube.current?.time ?? 0 : audio.current?.currentTime ?? 0;
if (at > 3) seek(0);
else setIndex((i) => Math.max(0, i - 1));
}, [seek]);
const toggle = useCallback(() => {
if (!state.current.queue.length) return;
if (state.current.onYouTube) {
const yt = youtube.current;
if (yt?.playing) yt.pause();
else yt?.play();
return;
}
const el = audio.current;
if (!el) return;
if (el.paused) void el.play().catch(() => undefined);
else el.pause();
}, []);
// ---------- YouTube ----------
const getYouTube = useCallback(
() =>
(youtube.current ??= new HiddenYouTubePlayer({
onState: (s) => youtubeEvents.current.onState(s),
onError: (code) => youtubeEvents.current.onError(code),
})),
[],
);
/** Look up videos for a suggestion and play the first that works */
const playYouTube = useCallback(
async (suggestionId: string, load: number, refresh: boolean) => {
try {
const found = await api.youtubeVideos(suggestionId, refresh);
if (load !== loads.current) return;
attempt.current = { suggestionId, videoIds: found.video_ids, at: 0, cached: found.cached };
await getYouTube().load(found.video_ids[0]);
} catch {
if (load === loads.current) failed();
}
},
[failed, getYouTube],
);
// the player's handlers, kept current for the player made on first use
const youtubeEvents = useRef<YouTubeEvents>({ onState: () => undefined, onError: () => undefined });
youtubeEvents.current = {
onState: (s) => {
if (!state.current.onYouTube) return;
if (s === State.Playing) {
setStatus("playing");
// the first video is the one playlistd already has
const a = attempt.current;
if (a && a.at > 0) {
void api.setYoutubeVideo(a.suggestionId, a.videoIds[a.at]).catch(() => undefined);
attempt.current = { ...a, videoIds: [a.videoIds[a.at]], at: 0 };
}
} else if (s === State.Paused) setStatus("paused");
else if (s === State.Buffering) setStatus("loading");
else if (s === State.Ended) next();
},
onError: () => {
// (no attempt: the previous song's video, while this one is being looked up)
const a = attempt.current;
if (!state.current.onYouTube || !a) return;
// usually a video that can't be embedded: try the next one
if (a.at + 1 < a.videoIds.length) {
attempt.current = { ...a, at: a.at + 1 };
void getYouTube().load(a.videoIds[a.at + 1]).catch(failed);
} else if (a.cached) {
attempt.current = null;
void playYouTube(a.suggestionId, loads.current, true);
} else {
failed();
}
},
};
// the embedded player has no time events
useEffect(() => {
if (!onYouTube || status !== "playing") return;
const update = () => {
setTime(youtube.current?.time ?? 0);
setDuration(youtube.current?.duration ?? 0);
};
update();
const t = window.setInterval(update, 250);
return () => window.clearInterval(t);
}, [onYouTube, status]);
// ---------- loading items ----------
useEffect(() => { useEffect(() => {
const el = audio.current; const el = audio.current;
if (!el || !current) return; if (!el || !current) return;
const load = ++loads.current;
window.clearTimeout(errorTimer.current);
setTime(0); setTime(0);
setDuration(0); setDuration(0);
setStatus("loading"); setStatus("loading");
if (current.source === "youtube" && current.suggestionId) {
el.pause();
el.removeAttribute("src");
el.load();
attempt.current = null;
void playYouTube(current.suggestionId, load, false);
} else {
youtube.current?.stop();
el.src = current.src; el.src = current.src;
void el.play().catch(() => undefined); void el.play().catch(() => undefined);
}
}, [current?.key]); // eslint-disable-line react-hooks/exhaustive-deps }, [current?.key]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => { useEffect(() => {
const el = audio.current; const el = audio.current;
if (!el) return; if (!el) return;
let errorTimer: number | undefined; // ignore the audio element while YouTube is playing (e.g. its pause on switching over)
const forAudio = (handler: () => void) => () => {
if (!state.current.onYouTube) handler();
};
const handlers: Record<string, () => void> = { const handlers: Record<string, () => void> = {
playing: () => setStatus("playing"), playing: () => setStatus("playing"),
pause: () => setStatus((s) => (s === "error" ? s : "paused")), pause: () => setStatus((s) => (s === "error" ? s : "paused")),
@@ -80,23 +206,22 @@ export function usePlayer(onError: (item: QueueItem) => void) {
durationchange: () => setDuration(Number.isFinite(el.duration) ? el.duration : 0), durationchange: () => setDuration(Number.isFinite(el.duration) ? el.duration : 0),
ended: () => next(), ended: () => next(),
error: () => { error: () => {
if (!el.src) return; if (el.getAttribute("src")) failed();
setStatus("error");
const { queue, index, onError } = state.current;
if (queue[index]) onError(queue[index]);
errorTimer = window.setTimeout(next, 1500);
}, },
}; };
for (const [event, handler] of Object.entries(handlers)) el.addEventListener(event, handler); const bound = Object.entries(handlers).map(([event, handler]) => [event, forAudio(handler)] as const);
for (const [event, handler] of bound) el.addEventListener(event, handler);
return () => { return () => {
window.clearTimeout(errorTimer); for (const [event, handler] of bound) el.removeEventListener(event, handler);
for (const [event, handler] of Object.entries(handlers)) el.removeEventListener(event, handler);
}; };
}, [next]); }, [next, failed]);
// stop playing when the app goes away (e.g. on logging out) // stop playing when the app goes away (e.g. on logging out)
useEffect( useEffect(
() => () => { () => () => {
window.clearTimeout(errorTimer.current);
youtube.current?.destroy();
youtube.current = null;
const el = audio.current; const el = audio.current;
if (!el) return; if (!el) return;
el.pause(); el.pause();
+158
View File
@@ -0,0 +1,158 @@
// Plays YouTube videos for their audio, with YouTube's IFrame player API, in a player that's
// kept out of sight (see .youtube-host in styles.css).
/** The parts of YT.Player used here */
type YTPlayer = {
loadVideoById(videoId: string): void;
playVideo(): void;
pauseVideo(): void;
stopVideo(): void;
seekTo(seconds: number, allowSeekAhead: boolean): void;
getCurrentTime(): number;
getDuration(): number;
getPlayerState(): number;
destroy(): void;
};
type YTNamespace = {
Player: new (
element: HTMLElement,
options: {
width: number;
height: number;
playerVars: Record<string, number>;
events: {
onReady: () => void;
onStateChange: (e: { data: number }) => void;
onError: (e: { data: number }) => void;
};
},
) => YTPlayer;
};
declare global {
interface Window {
YT?: YTNamespace;
onYouTubeIframeAPIReady?: () => void;
}
}
/** YT.PlayerState */
export const State = { Unstarted: -1, Ended: 0, Playing: 1, Paused: 2, Buffering: 3, Cued: 5 } as const;
let api: Promise<YTNamespace> | null = null;
function loadApi(): Promise<YTNamespace> {
if (window.YT?.Player) return Promise.resolve(window.YT);
api ??= new Promise<YTNamespace>((resolve, reject) => {
const previous = window.onYouTubeIframeAPIReady;
window.onYouTubeIframeAPIReady = () => {
previous?.();
resolve(window.YT!);
};
const script = document.createElement("script");
script.src = "https://www.youtube.com/iframe_api";
script.async = true;
script.onerror = () => {
script.remove();
api = null;
reject(new Error("Couldn't load YouTube's player"));
};
document.head.appendChild(script);
});
return api;
}
export type YouTubeEvents = {
onState: (state: number) => void;
/** YouTube's error code: 2 bad id, 5 HTML5 error, 100 not found, 101/150 can't be embedded */
onError: (code: number) => void;
};
export class HiddenYouTubePlayer {
private player: Promise<YTPlayer> | null = null;
private ready: YTPlayer | null = null;
private host: HTMLElement | null = null;
private destroyed = false;
constructor(private events: YouTubeEvents) {}
private create(): Promise<YTPlayer> {
if (this.player) return this.player;
this.player = loadApi().then(
(YT) =>
new Promise<YTPlayer>((resolve) => {
const host = document.createElement("div");
host.className = "youtube-host";
host.setAttribute("aria-hidden", "true");
const target = document.createElement("div");
host.appendChild(target);
document.body.appendChild(host);
this.host = host;
const player = new YT.Player(target, {
width: 200,
height: 200,
playerVars: { autoplay: 1, controls: 0, disablekb: 1, fs: 0, playsinline: 1, rel: 0 },
events: {
onReady: () => {
if (this.destroyed) {
player.destroy();
host.remove();
return;
}
this.ready = player;
resolve(player);
},
onStateChange: (e) => this.events.onState(e.data),
onError: (e) => this.events.onError(e.data),
},
});
}),
);
this.player.catch(() => (this.player = null));
return this.player;
}
/** Start playing a video. Rejects if YouTube's player can't be loaded. */
async load(videoId: string) {
(await this.create()).loadVideoById(videoId);
}
play() {
this.ready?.playVideo();
}
pause() {
this.ready?.pauseVideo();
}
stop() {
this.ready?.stopVideo();
}
seek(seconds: number) {
this.ready?.seekTo(seconds, true);
}
get playing() {
return this.ready?.getPlayerState() === State.Playing;
}
get time() {
return this.ready?.getCurrentTime() ?? 0;
}
get duration() {
return this.ready?.getDuration() ?? 0;
}
destroy() {
this.destroyed = true;
this.ready?.destroy();
this.host?.remove();
this.ready = null;
this.player = null;
this.host = null;
}
}
+1 -1
View File
@@ -28,7 +28,7 @@ url = "postgres:///navidrome-playlists"
[discover] [discover]
# Directory with the built discover UI (discover/dist) to serve at / # Directory with the built discover UI (discover/dist) to serve at /
ui = "/usr/share/playlistd/discover" ui = "/usr/share/playlistd/discover"
# yt-dlp binary used to play suggested songs that aren't in your library # yt-dlp binary used to find suggested songs that aren't in your library on YouTube
# ytdlp = "yt-dlp" # ytdlp = "yt-dlp"
# Format to ask Subsonic to stream in ("raw" = no transcoding), e.g. "mp3" if your # Format to ask Subsonic to stream in ("raw" = no transcoding), e.g. "mp3" if your
# library has files browsers can't play # library has files browsers can't play
+90 -53
View File
@@ -1,12 +1,12 @@
//! API for the discover UI: mixes, suggested songs, and audio/cover streaming //! API for the discover UI: mixes, suggested songs, audio and cover art from Subsonic, and
//! from Subsonic or YouTube. //! finding suggested songs on YouTube.
use crate::auth::User; use crate::auth::User;
use crate::models::{ClusterMixRule, MixSuggestion, PartialClusterMixRule}; use crate::models::{ClusterMixRule, MixSuggestion, PartialClusterMixRule};
use crate::subsonic::Subsonic; use crate::subsonic::Subsonic;
use crate::track::Track; use crate::track::Track;
use crate::tracked::{fail, ApiError}; use crate::tracked::{fail, ApiError};
use crate::youtube::YouTube; use crate::youtube::{valid_video_id, YouTube};
use futures_util::TryStreamExt; use futures_util::TryStreamExt;
use rocket::http::Status; use rocket::http::Status;
use rocket::request::{FromRequest, Outcome}; use rocket::request::{FromRequest, Outcome};
@@ -33,7 +33,8 @@ pub fn routes() -> Vec<Route> {
rebuild, rebuild,
stream, stream,
cover, cover,
youtube youtube,
set_youtube_video
] ]
} }
@@ -49,6 +50,17 @@ fn db_error(e: sqlx::Error) -> Status {
} }
} }
/// `db_error` with a message, for endpoints that explain their errors
fn db_fail(e: sqlx::Error) -> Custom<Json<ApiError>> {
let status = db_error(e);
let message = if status == Status::NotFound {
"Not found"
} else {
"Database error"
};
fail(status, message)
}
fn parse_id(id: &str) -> Result<Uuid, Status> { fn parse_id(id: &str) -> Result<Uuid, Status> {
Uuid::parse_str(id).map_err(|_| Status::NotFound) Uuid::parse_str(id).map_err(|_| Status::NotFound)
} }
@@ -107,10 +119,6 @@ async fn create_rule(
rule: Json<PartialClusterMixRule>, rule: Json<PartialClusterMixRule>,
pool: &State<PgPool>, pool: &State<PgPool>,
) -> Result<Json<ClusterMixRule>, Custom<Json<ApiError>>> { ) -> Result<Json<ClusterMixRule>, Custom<Json<ApiError>>> {
let database_error = |e: sqlx::Error| {
log::error!("Database error: {}", e);
fail(Status::InternalServerError, "Database error")
};
let mut rule = rule.into_inner(); let mut rule = rule.into_inner();
rule.tracking_user = rule.tracking_user.trim().to_string(); rule.tracking_user = rule.tracking_user.trim().to_string();
@@ -123,7 +131,7 @@ async fn create_rule(
// the UI picks mixes by Listenbrainz user, so one rule each // the UI picks mixes by Listenbrainz user, so one rule each
let existing = ClusterMixRule::all(pool.inner()) let existing = ClusterMixRule::all(pool.inner())
.await .await
.map_err(database_error)?; .map_err(db_fail)?;
if existing if existing
.iter() .iter()
.any(|r| r.tracking_user.eq_ignore_ascii_case(&rule.tracking_user)) .any(|r| r.tracking_user.eq_ignore_ascii_case(&rule.tracking_user))
@@ -134,7 +142,7 @@ async fn create_rule(
)); ));
} }
let created = rule.record(pool.inner()).await.map_err(database_error)?; let created = rule.record(pool.inner()).await.map_err(db_fail)?;
log::info!( log::info!(
"Created mix rule {} for {}", "Created mix rule {} for {}",
created.id, created.id,
@@ -153,13 +161,9 @@ async fn delete_rule(
pool: &State<PgPool>, pool: &State<PgPool>,
media_client: &State<Arc<Subsonic>>, media_client: &State<Arc<Subsonic>>,
) -> Result<Status, Custom<Json<ApiError>>> { ) -> Result<Status, Custom<Json<ApiError>>> {
let database_error = |e: sqlx::Error| {
log::error!("Database error: {}", e);
fail(Status::InternalServerError, "Database error")
};
let id = parse_id(id).map_err(|_| fail(Status::NotFound, "Not found"))?; let id = parse_id(id).map_err(|_| fail(Status::NotFound, "Not found"))?;
let mut transaction = pool.begin().await.map_err(database_error)?; let mut transaction = pool.begin().await.map_err(db_fail)?;
// the rule's playlists go with it (ON DELETE CASCADE), so note them first // the rule's playlists go with it (ON DELETE CASCADE), so note them first
let playlist_ids = sqlx::query_scalar!( let playlist_ids = sqlx::query_scalar!(
r#"SELECT playlist_id FROM "cluster_mix_playlist" WHERE rule_id = $1"#, r#"SELECT playlist_id FROM "cluster_mix_playlist" WHERE rule_id = $1"#,
@@ -167,16 +171,16 @@ async fn delete_rule(
) )
.fetch_all(&mut *transaction) .fetch_all(&mut *transaction)
.await .await
.map_err(database_error)?; .map_err(db_fail)?;
let tracking_user = sqlx::query_scalar!( let tracking_user = sqlx::query_scalar!(
r#"DELETE FROM "cluster_mix_rule" WHERE id = $1 RETURNING tracking_user"#, r#"DELETE FROM "cluster_mix_rule" WHERE id = $1 RETURNING tracking_user"#,
id id
) )
.fetch_optional(&mut *transaction) .fetch_optional(&mut *transaction)
.await .await
.map_err(database_error)? .map_err(db_fail)?
.ok_or_else(|| fail(Status::NotFound, "Not found"))?; .ok_or_else(|| fail(Status::NotFound, "Not found"))?;
transaction.commit().await.map_err(database_error)?; transaction.commit().await.map_err(db_fail)?;
log::info!("Deleted mix rule {} for {}", id, tracking_user); log::info!("Deleted mix rule {} for {}", id, tracking_user);
if delete_playlists.unwrap_or(false) { if delete_playlists.unwrap_or(false) {
@@ -474,28 +478,41 @@ async fn cover(
.map_err(|_| Status::BadGateway) .map_err(|_| Status::BadGateway)
} }
/// Find a suggested song on YouTube and stream its audio #[derive(Serialize)]
#[get("/youtube/<id>")] struct YouTubeVideos {
/// Candidate videos, best first: the UI plays the first one that can be embedded
video_ids: Vec<String>,
/// The one video that played before, rather than search results
cached: bool,
}
/// Videos to play a suggested song with, in the UI's embedded YouTube player: the one that
/// played before, or with `refresh` (or the first time) the results of a new search
#[get("/youtube/<id>?<refresh>")]
async fn youtube( async fn youtube(
_user: User, _user: User,
id: &str, id: &str,
range: Range, refresh: Option<bool>,
pool: &State<PgPool>, pool: &State<PgPool>,
youtube: &State<YouTube>, youtube: &State<YouTube>,
) -> Result<Proxied, Status> { ) -> Result<Json<YouTubeVideos>, Custom<Json<ApiError>>> {
let suggestion = sqlx::query_as!( let suggestion = sqlx::query_as!(
MixSuggestion, MixSuggestion,
r#"SELECT * FROM "mix_suggestion" WHERE id = $1"#, r#"SELECT * FROM "mix_suggestion" WHERE id = $1"#,
parse_id(id)? parse_id(id).map_err(|_| fail(Status::NotFound, "Not found"))?
) )
.fetch_one(pool.inner()) .fetch_one(pool.inner())
.await .await
.map_err(db_error)?; .map_err(db_fail)?;
let video_id = match suggestion.youtube_id { if let (Some(video_id), false) = (&suggestion.youtube_id, refresh.unwrap_or(false)) {
Some(video_id) => video_id, return Ok(Json(YouTubeVideos {
None => { video_ids: vec![video_id.clone()],
let video_id = youtube cached: true,
}));
}
let video_ids = youtube
.search(&suggestion.artist, &suggestion.title) .search(&suggestion.artist, &suggestion.title)
.await .await
.map_err(|e| { .map_err(|e| {
@@ -505,36 +522,56 @@ async fn youtube(
suggestion.title, suggestion.title,
e e
); );
Status::BadGateway fail(Status::BadGateway, "Couldn't search YouTube")
})? })?;
.ok_or(Status::NotFound)?; let Some(best) = video_ids.first() else {
return Err(fail(Status::NotFound, "Couldn't find it on YouTube"));
};
// for "Open on YouTube"; replaced if the UI ends up playing another one
sqlx::query!( sqlx::query!(
r#"UPDATE "mix_suggestion" SET youtube_id = $1 WHERE id = $2"#, r#"UPDATE "mix_suggestion" SET youtube_id = $1 WHERE id = $2"#,
video_id, best,
suggestion.id suggestion.id
) )
.execute(pool.inner()) .execute(pool.inner())
.await .await
.map_err(db_error)?; .map_err(db_fail)?;
video_id
}
};
// a cached URL may have expired; fetch a fresh one once Ok(Json(YouTubeVideos {
for refresh in [false, true] { video_ids,
let url = youtube.audio_url(&video_id, refresh).await.map_err(|e| { cached: false,
log::warn!("Could not get audio for YouTube video {}: {}", video_id, e); }))
Status::BadGateway }
})?;
let mut request = youtube.client.get(url); #[derive(Deserialize)]
if let Some(range) = &range.0 { struct PlayedVideo {
request = request.header(reqwest::header::RANGE, range); video_id: String,
} }
let response = request.send().await.map_err(|_| Status::BadGateway)?;
if !refresh && matches!(response.status().as_u16(), 403 | 404 | 410) { /// Remember the video the UI managed to play for a suggestion, when it wasn't the first result
continue; #[put("/youtube/<id>", data = "<played>")]
} async fn set_youtube_video(
return Ok(Proxied(response)); _user: User,
} id: &str,
Err(Status::BadGateway) played: Json<PlayedVideo>,
pool: &State<PgPool>,
) -> Status {
if !valid_video_id(&played.video_id) {
return Status::UnprocessableEntity;
}
let Ok(id) = parse_id(id) else {
return Status::NotFound;
};
match sqlx::query!(
r#"UPDATE "mix_suggestion" SET youtube_id = $1 WHERE id = $2"#,
played.video_id,
id
)
.execute(pool.inner())
.await
{
Ok(r) if r.rows_affected() > 0 => Status::NoContent,
Ok(_) => Status::NotFound,
Err(e) => db_error(e),
}
} }
+36 -66
View File
@@ -1,16 +1,12 @@
//! Find and stream songs from YouTube with yt-dlp. //! Find suggested songs on YouTube with yt-dlp. The web UI plays them itself, with YouTube's
//! embedded player, so only searching happens here.
use std::collections::HashMap;
use std::process::Stdio; use std::process::Stdio;
use std::time::{Duration, Instant};
use thiserror::Error; use thiserror::Error;
use tokio::process::Command; use tokio::process::Command;
use tokio::sync::Mutex;
/// Search results longer than this are probably full albums or mixes /// Search results longer than this are probably full albums or mixes
const MAX_DURATION_SECS: f64 = 15.0 * 60.0; const MAX_DURATION_SECS: f64 = 15.0 * 60.0;
/// YouTube's media URLs expire after about 6 hours
const URL_TTL: Duration = Duration::from_secs(60 * 60);
const SEARCH_RESULTS: usize = 5; const SEARCH_RESULTS: usize = 5;
#[derive(Debug, Error)] #[derive(Debug, Error)]
@@ -19,14 +15,10 @@ pub enum YouTubeError {
Spawn(#[from] std::io::Error), Spawn(#[from] std::io::Error),
#[error("yt-dlp failed: {0}")] #[error("yt-dlp failed: {0}")]
Failed(String), Failed(String),
#[error("invalid video id")]
InvalidId,
} }
pub struct YouTube { pub struct YouTube {
binary: String, binary: String,
urls: Mutex<HashMap<String, (String, Instant)>>,
pub client: reqwest::Client,
} }
pub fn valid_video_id(id: &str) -> bool { pub fn valid_video_id(id: &str) -> bool {
@@ -36,13 +28,29 @@ pub fn valid_video_id(id: &str) -> bool {
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
} }
/// Video IDs from yt-dlp's `<id>\t<duration>` lines, best first: videos of a plausible song
/// length in search order, then any longer ones
fn rank_results(output: &str) -> Vec<String> {
let results: Vec<(&str, Option<f64>)> = output
.lines()
.filter_map(|line| {
let (id, duration) = line.split_once('\t')?;
valid_video_id(id).then(|| (id, duration.trim().parse::<f64>().ok()))
})
.collect();
let (songs, long): (Vec<_>, Vec<_>) = results
.into_iter()
.partition(|(_, d)| d.is_some_and(|d| d <= MAX_DURATION_SECS));
songs
.into_iter()
.chain(long)
.map(|(id, _)| id.to_string())
.collect()
}
impl YouTube { impl YouTube {
pub fn new(binary: String) -> Self { pub fn new(binary: String) -> Self {
Self { Self { binary }
binary,
urls: Mutex::new(HashMap::new()),
client: reqwest::Client::new(),
}
} }
async fn run(&self, args: &[&str]) -> Result<String, YouTubeError> { async fn run(&self, args: &[&str]) -> Result<String, YouTubeError> {
@@ -61,61 +69,14 @@ impl YouTube {
Ok(String::from_utf8_lossy(&output.stdout).into_owned()) Ok(String::from_utf8_lossy(&output.stdout).into_owned())
} }
/// The ID of the best matching video for a song, skipping very long videos /// IDs of the videos that best match a song, best first. Several, as some videos can't be
pub async fn search(&self, artist: &str, title: &str) -> Result<Option<String>, YouTubeError> { /// embedded.
pub async fn search(&self, artist: &str, title: &str) -> Result<Vec<String>, YouTubeError> {
let query = format!("ytsearch{}:{} - {}", SEARCH_RESULTS, artist, title); let query = format!("ytsearch{}:{} - {}", SEARCH_RESULTS, artist, title);
let output = self let output = self
.run(&["--flat-playlist", "--print", "%(id)s\t%(duration)s", &query]) .run(&["--flat-playlist", "--print", "%(id)s\t%(duration)s", &query])
.await?; .await?;
Ok(rank_results(&output))
let results: Vec<(&str, Option<f64>)> = output
.lines()
.filter_map(|line| {
let (id, duration) = line.split_once('\t')?;
valid_video_id(id).then(|| (id, duration.trim().parse::<f64>().ok()))
})
.collect();
Ok(results
.iter()
.find(|(_, d)| d.is_some_and(|d| d <= MAX_DURATION_SECS))
.or(results.first())
.map(|(id, _)| id.to_string()))
}
/// A direct URL to the video's audio, preferring m4a since every browser can play it
pub async fn audio_url(&self, video_id: &str, refresh: bool) -> Result<String, YouTubeError> {
if !valid_video_id(video_id) {
return Err(YouTubeError::InvalidId);
}
{
let urls = self.urls.lock().await;
if let Some((url, fetched)) = urls.get(video_id) {
if !refresh && fetched.elapsed() < URL_TTL {
return Ok(url.clone());
}
}
}
let output = self
.run(&[
"-f",
"bestaudio[ext=m4a]/bestaudio",
"--get-url",
&format!("https://www.youtube.com/watch?v={}", video_id),
])
.await?;
let url = output
.lines()
.next()
.filter(|l| l.starts_with("http"))
.ok_or_else(|| YouTubeError::Failed("no audio URL".to_string()))?
.to_string();
let mut urls = self.urls.lock().await;
urls.retain(|_, (_, fetched)| fetched.elapsed() < URL_TTL);
urls.insert(video_id.to_string(), (url.clone(), Instant::now()));
Ok(url)
} }
} }
@@ -130,4 +91,13 @@ mod tests {
assert!(!valid_video_id("--exec=rm -")); assert!(!valid_video_id("--exec=rm -"));
assert!(!valid_video_id("short")); assert!(!valid_video_id("short"));
} }
#[test]
fn ranks_song_length_videos_first() {
let output = "aaaaaaaaaaa\t3600\nbbbbbbbbbbb\t240\nnot-an-id\t200\nccccccccccc\tNA\nddddddddddd\t180.5\n";
assert_eq!(
rank_results(output),
["bbbbbbbbbbb", "ddddddddddd", "aaaaaaaaaaa", "ccccccccccc"]
);
}
} }