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:
1 parent
93e12cfc72
commit
c84e7e715d
11 files changed
+495
-181
No files matched your search
+1
-1
@@ -28,7 +28,7 @@ sha2 = "0.10"
|
||||
|
||||
[package.metadata.deb]
|
||||
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
|
||||
recommends = "yt-dlp"
|
||||
assets = [
|
||||
|
||||
+1
-3
@@ -25,14 +25,12 @@ RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates libssl3 python3 python3-venv \
|
||||
&& 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.
|
||||
ARG YTDLP_VERSION=
|
||||
RUN python3 -m venv /opt/yt-dlp \
|
||||
&& /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
|
||||
# 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=ui /src/dist /usr/share/playlistd/discover
|
||||
|
||||
@@ -24,8 +24,8 @@ otherwise against the query data in `.sqlx/`. After changing a query, update tha
|
||||
|
||||
### Docker Compose
|
||||
|
||||
`compose.yaml` runs playlistd with its own Postgres database. The image includes the web UI,
|
||||
yt-dlp and Deno (which yt-dlp needs for YouTube).
|
||||
`compose.yaml` runs playlistd with its own Postgres database. The image includes the web UI and
|
||||
yt-dlp (for finding new songs on YouTube).
|
||||
|
||||
```sh
|
||||
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_BASE`.
|
||||
|
||||
YouTube changes often 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:
|
||||
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 finding new songs:
|
||||
|
||||
```sh
|
||||
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
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
||||
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
|
||||
installed on the server (keep it up to date: YouTube changes often break older versions). You can
|
||||
like a new song to keep it in "Liked new songs", or hide it so it isn't suggested again.
|
||||
[yt-dlp](https://github.com/yt-dlp/yt-dlp) on the server (keep it up to date: YouTube changes can
|
||||
break older versions), and play in the browser, in YouTube's embedded player kept out of sight.
|
||||
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
|
||||
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 |
|
||||
| `GET /stream/<song id>` | Stream a library song 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:
|
||||
|
||||
|
||||
+6
-1
@@ -96,12 +96,17 @@ export const api = {
|
||||
body: JSON.stringify({ status }),
|
||||
}),
|
||||
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) =>
|
||||
`/api/discover/cover/${encodeURIComponent(coverArt)}?size=${size}`;
|
||||
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" */
|
||||
export const mixTitle = (mix: MixSummary) =>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { coverUrl, Song, streamUrl, Suggestion, youtubeUrl } from "./api";
|
||||
import { coverUrl, Song, streamUrl, Suggestion } from "./api";
|
||||
|
||||
export type QueueItem = {
|
||||
key: string;
|
||||
source: "library" | "youtube";
|
||||
/** Audio to stream, for library songs. YouTube ones play from `suggestionId`. */
|
||||
src: string;
|
||||
title: string;
|
||||
artist: string;
|
||||
@@ -24,7 +25,7 @@ export const fromSong = (song: Song): QueueItem => ({
|
||||
export const fromSuggestion = (s: Suggestion): QueueItem => ({
|
||||
key: `suggestion:${s.id}`,
|
||||
source: "youtube",
|
||||
src: youtubeUrl(s.id),
|
||||
src: "",
|
||||
title: s.title,
|
||||
artist: s.artist,
|
||||
album: s.release,
|
||||
|
||||
@@ -1125,6 +1125,20 @@ h2 {
|
||||
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 ---------- */
|
||||
|
||||
@media (max-width: 800px) {
|
||||
|
||||
+155
-30
@@ -1,16 +1,32 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { api } from "./api";
|
||||
import { QueueItem } from "./queue";
|
||||
import { HiddenYouTubePlayer, State, YouTubeEvents } from "./youtubePlayer";
|
||||
|
||||
export type PlayerStatus = "idle" | "loading" | "playing" | "paused" | "error";
|
||||
|
||||
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) {
|
||||
const audio = useRef<HTMLAudioElement | null>(null);
|
||||
if (audio.current === null && typeof Audio !== "undefined") {
|
||||
audio.current = new Audio();
|
||||
audio.current.preload = "auto";
|
||||
}
|
||||
const youtube = useRef<HiddenYouTubePlayer | null>(null);
|
||||
|
||||
const [queue, setQueue] = useState<QueueItem[]>([]);
|
||||
const [index, setIndex] = useState(-1);
|
||||
@@ -18,10 +34,16 @@ export function usePlayer(onError: (item: QueueItem) => void) {
|
||||
const [time, setTime] = useState(0);
|
||||
const [duration, setDuration] = useState(0);
|
||||
const current = index >= 0 ? queue[index] : undefined;
|
||||
const onYouTube = current?.source === "youtube";
|
||||
|
||||
// keep the latest values for the audio element's event handlers
|
||||
const state = useRef({ queue, index, onError });
|
||||
state.current = { queue, index, onError };
|
||||
// counts loads, so a slow YouTube lookup for a song that's been skipped is ignored
|
||||
const loads = useRef(0);
|
||||
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) => {
|
||||
setQueue(items);
|
||||
@@ -33,45 +55,149 @@ export function usePlayer(onError: (item: QueueItem) => void) {
|
||||
if (index + 1 < queue.length) setIndex(index + 1);
|
||||
else {
|
||||
audio.current?.pause();
|
||||
youtube.current?.pause();
|
||||
setStatus("paused");
|
||||
}
|
||||
}, []);
|
||||
|
||||
const previous = useCallback(() => {
|
||||
const el = audio.current;
|
||||
if (el && el.currentTime > 3) el.currentTime = 0;
|
||||
else setIndex((i) => Math.max(0, i - 1));
|
||||
}, []);
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
const el = audio.current;
|
||||
if (!el || !state.current.queue.length) return;
|
||||
if (el.paused) void el.play().catch(() => undefined);
|
||||
else el.pause();
|
||||
}, []);
|
||||
/** Give up on the current item and move on */
|
||||
const failed = useCallback(() => {
|
||||
setStatus("error");
|
||||
const { queue, index, onError } = state.current;
|
||||
if (queue[index]) onError(queue[index]);
|
||||
window.clearTimeout(errorTimer.current);
|
||||
errorTimer.current = window.setTimeout(next, 1500);
|
||||
}, [next]);
|
||||
|
||||
const seek = useCallback((seconds: number) => {
|
||||
if (!audio.current) return;
|
||||
audio.current.currentTime = seconds;
|
||||
if (state.current.onYouTube) youtube.current?.seek(seconds);
|
||||
else if (audio.current) audio.current.currentTime = seconds;
|
||||
// update now, or the controlled slider snaps back and its change event seeks back too
|
||||
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(() => {
|
||||
const el = audio.current;
|
||||
if (!el || !current) return;
|
||||
const load = ++loads.current;
|
||||
window.clearTimeout(errorTimer.current);
|
||||
setTime(0);
|
||||
setDuration(0);
|
||||
setStatus("loading");
|
||||
el.src = current.src;
|
||||
void el.play().catch(() => undefined);
|
||||
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;
|
||||
void el.play().catch(() => undefined);
|
||||
}
|
||||
}, [current?.key]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
const el = audio.current;
|
||||
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> = {
|
||||
playing: () => setStatus("playing"),
|
||||
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),
|
||||
ended: () => next(),
|
||||
error: () => {
|
||||
if (!el.src) return;
|
||||
setStatus("error");
|
||||
const { queue, index, onError } = state.current;
|
||||
if (queue[index]) onError(queue[index]);
|
||||
errorTimer = window.setTimeout(next, 1500);
|
||||
if (el.getAttribute("src")) failed();
|
||||
},
|
||||
};
|
||||
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 () => {
|
||||
window.clearTimeout(errorTimer);
|
||||
for (const [event, handler] of Object.entries(handlers)) el.removeEventListener(event, handler);
|
||||
for (const [event, handler] of bound) el.removeEventListener(event, handler);
|
||||
};
|
||||
}, [next]);
|
||||
}, [next, failed]);
|
||||
|
||||
// stop playing when the app goes away (e.g. on logging out)
|
||||
useEffect(
|
||||
() => () => {
|
||||
window.clearTimeout(errorTimer.current);
|
||||
youtube.current?.destroy();
|
||||
youtube.current = null;
|
||||
const el = audio.current;
|
||||
if (!el) return;
|
||||
el.pause();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ url = "postgres:///navidrome-playlists"
|
||||
[discover]
|
||||
# Directory with the built discover UI (discover/dist) to serve at /
|
||||
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"
|
||||
# Format to ask Subsonic to stream in ("raw" = no transcoding), e.g. "mp3" if your
|
||||
# library has files browsers can't play
|
||||
|
||||
+105
-68
@@ -1,12 +1,12 @@
|
||||
//! API for the discover UI: mixes, suggested songs, and audio/cover streaming
|
||||
//! from Subsonic or YouTube.
|
||||
//! API for the discover UI: mixes, suggested songs, audio and cover art from Subsonic, and
|
||||
//! finding suggested songs on YouTube.
|
||||
|
||||
use crate::auth::User;
|
||||
use crate::models::{ClusterMixRule, MixSuggestion, PartialClusterMixRule};
|
||||
use crate::subsonic::Subsonic;
|
||||
use crate::track::Track;
|
||||
use crate::tracked::{fail, ApiError};
|
||||
use crate::youtube::YouTube;
|
||||
use crate::youtube::{valid_video_id, YouTube};
|
||||
use futures_util::TryStreamExt;
|
||||
use rocket::http::Status;
|
||||
use rocket::request::{FromRequest, Outcome};
|
||||
@@ -33,7 +33,8 @@ pub fn routes() -> Vec<Route> {
|
||||
rebuild,
|
||||
stream,
|
||||
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> {
|
||||
Uuid::parse_str(id).map_err(|_| Status::NotFound)
|
||||
}
|
||||
@@ -107,10 +119,6 @@ async fn create_rule(
|
||||
rule: Json<PartialClusterMixRule>,
|
||||
pool: &State<PgPool>,
|
||||
) -> 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();
|
||||
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
|
||||
let existing = ClusterMixRule::all(pool.inner())
|
||||
.await
|
||||
.map_err(database_error)?;
|
||||
.map_err(db_fail)?;
|
||||
if existing
|
||||
.iter()
|
||||
.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!(
|
||||
"Created mix rule {} for {}",
|
||||
created.id,
|
||||
@@ -153,13 +161,9 @@ async fn delete_rule(
|
||||
pool: &State<PgPool>,
|
||||
media_client: &State<Arc<Subsonic>>,
|
||||
) -> 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 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
|
||||
let playlist_ids = sqlx::query_scalar!(
|
||||
r#"SELECT playlist_id FROM "cluster_mix_playlist" WHERE rule_id = $1"#,
|
||||
@@ -167,16 +171,16 @@ async fn delete_rule(
|
||||
)
|
||||
.fetch_all(&mut *transaction)
|
||||
.await
|
||||
.map_err(database_error)?;
|
||||
.map_err(db_fail)?;
|
||||
let tracking_user = sqlx::query_scalar!(
|
||||
r#"DELETE FROM "cluster_mix_rule" WHERE id = $1 RETURNING tracking_user"#,
|
||||
id
|
||||
)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(database_error)?
|
||||
.map_err(db_fail)?
|
||||
.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);
|
||||
if delete_playlists.unwrap_or(false) {
|
||||
@@ -474,67 +478,100 @@ async fn cover(
|
||||
.map_err(|_| Status::BadGateway)
|
||||
}
|
||||
|
||||
/// Find a suggested song on YouTube and stream its audio
|
||||
#[get("/youtube/<id>")]
|
||||
#[derive(Serialize)]
|
||||
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(
|
||||
_user: User,
|
||||
id: &str,
|
||||
range: Range,
|
||||
refresh: Option<bool>,
|
||||
pool: &State<PgPool>,
|
||||
youtube: &State<YouTube>,
|
||||
) -> Result<Proxied, Status> {
|
||||
) -> Result<Json<YouTubeVideos>, Custom<Json<ApiError>>> {
|
||||
let suggestion = sqlx::query_as!(
|
||||
MixSuggestion,
|
||||
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())
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
.map_err(db_fail)?;
|
||||
|
||||
let video_id = match suggestion.youtube_id {
|
||||
Some(video_id) => video_id,
|
||||
None => {
|
||||
let video_id = youtube
|
||||
.search(&suggestion.artist, &suggestion.title)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
log::warn!(
|
||||
"YouTube search failed for {} - {}: {}",
|
||||
suggestion.artist,
|
||||
suggestion.title,
|
||||
e
|
||||
);
|
||||
Status::BadGateway
|
||||
})?
|
||||
.ok_or(Status::NotFound)?;
|
||||
sqlx::query!(
|
||||
r#"UPDATE "mix_suggestion" SET youtube_id = $1 WHERE id = $2"#,
|
||||
video_id,
|
||||
suggestion.id
|
||||
)
|
||||
.execute(pool.inner())
|
||||
.await
|
||||
.map_err(db_error)?;
|
||||
video_id
|
||||
}
|
||||
};
|
||||
|
||||
// a cached URL may have expired; fetch a fresh one once
|
||||
for refresh in [false, true] {
|
||||
let url = youtube.audio_url(&video_id, refresh).await.map_err(|e| {
|
||||
log::warn!("Could not get audio for YouTube video {}: {}", video_id, e);
|
||||
Status::BadGateway
|
||||
})?;
|
||||
let mut request = youtube.client.get(url);
|
||||
if let Some(range) = &range.0 {
|
||||
request = request.header(reqwest::header::RANGE, range);
|
||||
}
|
||||
let response = request.send().await.map_err(|_| Status::BadGateway)?;
|
||||
if !refresh && matches!(response.status().as_u16(), 403 | 404 | 410) {
|
||||
continue;
|
||||
}
|
||||
return Ok(Proxied(response));
|
||||
if let (Some(video_id), false) = (&suggestion.youtube_id, refresh.unwrap_or(false)) {
|
||||
return Ok(Json(YouTubeVideos {
|
||||
video_ids: vec![video_id.clone()],
|
||||
cached: true,
|
||||
}));
|
||||
}
|
||||
|
||||
let video_ids = youtube
|
||||
.search(&suggestion.artist, &suggestion.title)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
log::warn!(
|
||||
"YouTube search failed for {} - {}: {}",
|
||||
suggestion.artist,
|
||||
suggestion.title,
|
||||
e
|
||||
);
|
||||
fail(Status::BadGateway, "Couldn't search YouTube")
|
||||
})?;
|
||||
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!(
|
||||
r#"UPDATE "mix_suggestion" SET youtube_id = $1 WHERE id = $2"#,
|
||||
best,
|
||||
suggestion.id
|
||||
)
|
||||
.execute(pool.inner())
|
||||
.await
|
||||
.map_err(db_fail)?;
|
||||
|
||||
Ok(Json(YouTubeVideos {
|
||||
video_ids,
|
||||
cached: false,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PlayedVideo {
|
||||
video_id: String,
|
||||
}
|
||||
|
||||
/// Remember the video the UI managed to play for a suggestion, when it wasn't the first result
|
||||
#[put("/youtube/<id>", data = "<played>")]
|
||||
async fn set_youtube_video(
|
||||
_user: User,
|
||||
id: &str,
|
||||
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),
|
||||
}
|
||||
Err(Status::BadGateway)
|
||||
}
|
||||
+36
-66
@@ -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::time::{Duration, Instant};
|
||||
use thiserror::Error;
|
||||
use tokio::process::Command;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
/// Search results longer than this are probably full albums or mixes
|
||||
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;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -19,14 +15,10 @@ pub enum YouTubeError {
|
||||
Spawn(#[from] std::io::Error),
|
||||
#[error("yt-dlp failed: {0}")]
|
||||
Failed(String),
|
||||
#[error("invalid video id")]
|
||||
InvalidId,
|
||||
}
|
||||
|
||||
pub struct YouTube {
|
||||
binary: String,
|
||||
urls: Mutex<HashMap<String, (String, Instant)>>,
|
||||
pub client: reqwest::Client,
|
||||
}
|
||||
|
||||
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 == '_')
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
pub fn new(binary: String) -> Self {
|
||||
Self {
|
||||
binary,
|
||||
urls: Mutex::new(HashMap::new()),
|
||||
client: reqwest::Client::new(),
|
||||
}
|
||||
Self { binary }
|
||||
}
|
||||
|
||||
async fn run(&self, args: &[&str]) -> Result<String, YouTubeError> {
|
||||
@@ -61,61 +69,14 @@ impl YouTube {
|
||||
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
|
||||
}
|
||||
|
||||
/// The ID of the best matching video for a song, skipping very long videos
|
||||
pub async fn search(&self, artist: &str, title: &str) -> Result<Option<String>, YouTubeError> {
|
||||
/// IDs of the videos that best match a song, best first. Several, as some videos can't be
|
||||
/// embedded.
|
||||
pub async fn search(&self, artist: &str, title: &str) -> Result<Vec<String>, YouTubeError> {
|
||||
let query = format!("ytsearch{}:{} - {}", SEARCH_RESULTS, artist, title);
|
||||
let output = self
|
||||
.run(&["--flat-playlist", "--print", "%(id)s\t%(duration)s", &query])
|
||||
.await?;
|
||||
|
||||
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)
|
||||
Ok(rank_results(&output))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,4 +91,13 @@ mod tests {
|
||||
assert!(!valid_video_id("--exec=rm -"));
|
||||
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"]
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user