Skip to content

Open-source music player for YouTube Music's catalog, with genres, full albums and playlists. Windows, macOS, Linux, Android, iPhone and Docker. No account needed.

TypeScript

fix: play through YouTube's bot check with a direct-audio fallback

Ernani056f74b02551
diff --git a/README.md b/README.md
index f622ecb..1c4c5d3 100644
--- a/README.md
+++ b/README.md
@@ -418,8 +418,11 @@ musike/
**Songs stopped playing, or "YouTube refused the stream"**
YouTube changes often and yt-dlp keeps up. Open **Settings** and click **Update**. If the fix hasn't reached the Stable channel yet, pick **Nightly**.
-**"YouTube asked for an anti-bot check"**
-Pass cookies from a signed-in browser (Firefox works best on Windows):
+**"YouTube is asking this connection to prove it's not a bot"**
+YouTube asks this of some connections, mostly VPNs and shared networks (offices, universities, some providers). Musike first tries to get the audio another way, so you only see this message when that fails too.
+
+- If you use a VPN, turn it off and try again.
+- Running the server yourself, you can pass cookies from a signed-in browser (Firefox works best on Windows). YouTube may flag an account used this way, so prefer one you don't mind losing:
```bash
YTDLP_EXTRA_ARGS="--cookies-from-browser firefox" pnpm start
diff --git a/server/src/directAudio.ts b/server/src/directAudio.ts
new file mode 100644
index 0000000..7acc8c0
--- /dev/null
+++ b/server/src/directAudio.ts
@@ -0,0 +1,71 @@
+import type { Lang } from "./i18n.js";
+import { text, withClient } from "./search.js";
+
+/**
+ * A track's audio asked straight from YouTube's API, without yt-dlp. The Android app plays it this way, and the
+ * server falls back to it when yt-dlp fails (YouTube's bot check on some connections, an outdated yt-dlp).
+ *
+ * YouTube only serves the first megabyte of a stream to most clients unless the request carries a proof-of-origin
+ * token. A few clients don't need one; VISIONOS (the Apple Vision Pro app) is the one yt-dlp itself relies on, and
+ * its URLs need no deciphering either. When YouTube changes that, the list of clients can be updated remotely
+ * (mobile/streaming.json in the repository) without shipping a new version.
+ */
+
+export const DEFAULT_CLIENTS = ["VISIONOS"];
+const REMOTE_CONFIG = "https://raw.githubusercontent.com/Ernani1234/musike/main/mobile/streaming.json";
+
+export interface DirectAudio {
+ url: string;
+ mime: string;
+ title: string;
+ duration: number;
+ /** When the URL stops working (ms). */
+ expiresAt: number;
+}
+
+export const validClients = (v: unknown): string[] | null =>
+ Array.isArray(v) && v.length > 0 && v.every((c) => typeof c === "string" && /^[A-Z_]{2,30}$/.test(c)) ? (v as string[]) : null;
+
+/** The client list published in the repository, or null when it can't be read. */
+export async function fetchRemoteClients(): Promise<string[] | null> {
+ try {
+ const res = await fetch(REMOTE_CONFIG, { signal: AbortSignal.timeout(6000) });
+ return validClients(((await res.json()) as { clients?: unknown }).clients);
+ } catch {
+ return null; // offline or no config: keep what we have
+ }
+}
+
+/** Tries each client in turn. Throws with YouTube's reason (or an empty message) when none of them has audio. */
+export async function directAudio(id: string, clients: string[], lang?: Lang): Promise<DirectAudio> {
+ let reason = "";
+ for (const client of clients) {
+ try {
+ const info: any = await withClient((yt) => yt.getBasicInfo(id, { client: client as never }), lang);
+ const status = info.playability_status;
+ if (status?.status && status.status !== "OK") {
+ reason = text(status.reason) || reason;
+ continue;
+ }
+ const formats: any[] = [...(info.streaming_data?.adaptive_formats ?? []), ...(info.streaming_data?.formats ?? [])].filter(
+ (f) => f.has_audio && !f.has_video && typeof f.url === "string",
+ );
+ // AAC (m4a) first: it plays everywhere. Highest bitrate within the same kind.
+ const best = formats.sort(
+ (a, b) => Number(b.mime_type?.startsWith("audio/mp4")) - Number(a.mime_type?.startsWith("audio/mp4")) || (b.bitrate ?? 0) - (a.bitrate ?? 0),
+ )[0];
+ if (!best) continue;
+ const expire = Number(new URL(best.url).searchParams.get("expire")) * 1000;
+ return {
+ url: best.url,
+ mime: best.mime_type?.startsWith("audio/webm") ? "audio/webm" : "audio/mp4",
+ title: info.basic_info?.title ?? "",
+ duration: info.basic_info?.duration ?? 0,
+ expiresAt: expire || Date.now() + 3 * 3600_000,
+ };
+ } catch (e) {
+ reason = (e as Error).message || reason;
+ }
+ }
+ throw new Error(reason);
+}
diff --git a/server/src/i18n.ts b/server/src/i18n.ts
index d61cf82..ea301a9 100644
--- a/server/src/i18n.ts
+++ b/server/src/i18n.ts
@@ -33,7 +33,7 @@ const en = {
ytdlpMissing: "yt-dlp wasn't found on this computer. Open Settings in Musike to install it.",
ytdlpTimeout: "yt-dlp took too long to answer.",
ytdlpCantRun: "Couldn't run yt-dlp ({error}). Open Settings in Musike.",
- botCheck: "YouTube asked for an anti-bot check. Set YTDLP_EXTRA_ARGS with cookies (see the README).",
+ botCheck: "YouTube is asking this connection to prove it's not a bot. If you're on a VPN, turn it off and try again.",
videoUnavailable: "This video isn't available on YouTube.",
ageRestricted: "Age-restricted video. It needs cookies from a signed-in account.",
ytdlpFailed: "yt-dlp failed.",
@@ -83,7 +83,7 @@ const pt: Record<MsgKey, string> = {
ytdlpMissing: "O yt-dlp não foi encontrado neste computador. Abra Ajustes no Musike para instalar.",
ytdlpTimeout: "O yt-dlp demorou demais para responder.",
ytdlpCantRun: "Não foi possível executar o yt-dlp ({error}). Abra Ajustes no Musike.",
- botCheck: "O YouTube pediu verificação anti-bot. Configure YTDLP_EXTRA_ARGS com cookies (veja o README).",
+ botCheck: "O YouTube está pedindo para esta conexão provar que não é um robô. Se estiver usando VPN, desligue e tente de novo.",
videoUnavailable: "Vídeo indisponível no YouTube.",
ageRestricted: "Vídeo com restrição de idade. Requer cookies de uma conta logada.",
ytdlpFailed: "Falha no yt-dlp.",
diff --git a/server/src/ytdlp.ts b/server/src/ytdlp.ts
index 3c1cd34..38c9d90 100644
--- a/server/src/ytdlp.ts
+++ b/server/src/ytdlp.ts
@@ -4,6 +4,7 @@ import { mkdir, readdir, rename, rm, stat, utimes } from "node:fs/promises";
import path from "node:path";
import { ensureComponent } from "./bootstrap.js";
import { config } from "./config.js";
+import { DEFAULT_CLIENTS, directAudio, fetchRemoteClients } from "./directAudio.js";
import { tools } from "./tools.js";
import { msg } from "./i18n.js";
import { HttpError } from "./types.js";
@@ -86,7 +87,7 @@ function toHttpError(stderr: string): HttpError {
if (/confirm you.re not a bot|Sign in to confirm/i.test(line)) {
return new HttpError(503, msg("botCheck"), "bot_check");
}
- if (/Video unavailable|Private video|removed/i.test(line)) {
+ if (/Video unavailable|video is unavailable|Private video|removed/i.test(line)) {
return new HttpError(404, msg("videoUnavailable"));
}
if (/age-restricted|inappropriate|confirm your age/i.test(line)) {
@@ -138,6 +139,41 @@ function expiryOf(url: string): number {
const cache = new Map<string, Promise<Resolved>>();
const resolvedAt = new Map<string, Resolved>();
+// When yt-dlp fails, the clients to ask YouTube directly (see directAudio.ts), refreshed from the repository.
+// Read lazily: directAudio.ts and this module import each other through search.ts.
+let directClients: string[] | null = null;
+let directClientsAt = 0;
+
+async function clientsForDirect(): Promise<string[]> {
+ if (Date.now() - directClientsAt > 6 * 3600_000) {
+ directClientsAt = Date.now();
+ directClients = (await fetchRemoteClients()) ?? directClients;
+ }
+ return directClients ?? DEFAULT_CLIENTS;
+}
+
+/**
+ * Plan B for audio: YouTube's bot check stops yt-dlp on some connections (VPNs, shared networks), and a YouTube
+ * change can break it until it's updated. Asking YouTube for the audio directly often still works. Video stays
+ * yt-dlp's job.
+ */
+async function resolveDirect(id: string, ytdlpError: unknown): Promise<Resolved> {
+ // Removed, private or age-restricted videos won't play any other way either.
+ if (ytdlpError instanceof HttpError && (ytdlpError.status === 403 || ytdlpError.status === 404)) throw ytdlpError;
+ try {
+ const direct = await directAudio(id, await clientsForDirect());
+ return {
+ id,
+ title: direct.title,
+ duration: direct.duration,
+ audio: { formatId: "direct", url: direct.url, headers: {}, mime: direct.mime },
+ expiresAt: direct.expiresAt - 10 * 60_000,
+ };
+ } catch {
+ throw ytdlpError; // yt-dlp's error says more, and may offer the update
+ }
+}
+
export function resolveStreams(id: string): Promise<Resolved> {
const done = resolvedAt.get(id);
if (done && done.expiresAt > Date.now()) return Promise.resolve(done);
@@ -145,12 +181,12 @@ export function resolveStreams(id: string): Promise<Resolved> {
if (inflight) return inflight;
const job = run(["-J", "--no-playlist", "--no-warnings", `https://www.youtube.com/watch?v=${id}`], RESOLVE_TIMEOUT_MS)
- .then((stdout) => {
+ .then((stdout): Resolved => {
const info = JSON.parse(stdout) as { title: string; duration?: number; formats: RawFormat[] };
const audio = pickAudio(info.formats);
if (!audio) throw new HttpError(404, msg("noAudio"));
const video = pickVideo(info.formats);
- const resolved: Resolved = {
+ return {
id,
title: info.title,
duration: info.duration ?? 0,
@@ -158,6 +194,9 @@ export function resolveStreams(id: string): Promise<Resolved> {
video: video ? toStream(video, "video") : undefined,
expiresAt: expiryOf(audio.url!),
};
+ })
+ .catch((err) => resolveDirect(id, err))
+ .then((resolved) => {
resolvedAt.set(id, resolved);
return resolved;
})
diff --git a/web/src/native/streams.ts b/web/src/native/streams.ts
index 99b49aa..a573b84 100644
--- a/web/src/native/streams.ts
+++ b/web/src/native/streams.ts
@@ -1,33 +1,17 @@
+import { DEFAULT_CLIENTS, directAudio, fetchRemoteClients, validClients, type DirectAudio } from "../../../server/src/directAudio";
import { msg, tr } from "../../../server/src/i18n";
-import { text, withClient } from "../../../server/src/search";
import { getLang } from "../i18n";
import { ApiError } from "../lib/apiTypes";
/**
- * Resolves a track's audio on the phone, the job yt-dlp does on the server.
- *
- * YouTube only serves the first megabyte of a stream to most clients unless the request carries a proof-of-origin
- * token. A few clients don't need one; VISIONOS (the Apple Vision Pro app) is the one yt-dlp itself relies on, and
- * its URLs need no deciphering either. When YouTube changes that, the list of clients to try can be updated
- * remotely (mobile/streaming.json in the repository) without shipping a new app.
+ * Resolves a track's audio on the phone, the job yt-dlp does on the server: straight from YouTube's API
+ * (server/src/directAudio.ts). The list of clients to ask can be updated remotely; the last one received is kept.
*/
-const DEFAULT_CLIENTS = ["VISIONOS"];
-const REMOTE_CONFIG = "https://raw.githubusercontent.com/Ernani1234/musike/main/mobile/streaming.json";
const CLIENTS_KEY = "musike:stream-clients";
-interface Resolved {
- url: string;
- title: string;
- duration: number;
- expiresAt: number;
-}
-
-const cache = new Map<string, Resolved>();
-const inflight = new Map<string, Promise<Resolved>>();
-
-const validClients = (v: unknown): string[] | null =>
- Array.isArray(v) && v.length > 0 && v.every((c) => typeof c === "string" && /^[A-Z_]{2,30}$/.test(c)) ? (v as string[]) : null;
+const cache = new Map<string, DirectAudio>();
+const inflight = new Map<string, Promise<DirectAudio>>();
function storedClients(): string[] {
try {
@@ -39,56 +23,29 @@ function storedClients(): string[] {
let clients = storedClients();
-/** Picks up a newer client list in the background; the stored one (or the default) is used meanwhile. */
-async function refreshClients() {
+// Pick up a newer client list in the background; the stored one (or the default) is used meanwhile.
+void fetchRemoteClients().then((remote) => {
+ if (!remote) return;
+ clients = remote;
try {
- const res = await fetch(REMOTE_CONFIG, { signal: AbortSignal.timeout(6000) });
- const remote = validClients(((await res.json()) as { clients?: unknown }).clients);
- if (!remote) return;
- clients = remote;
localStorage.setItem(CLIENTS_KEY, JSON.stringify(remote));
} catch {
- // offline or no config yet: keep what we have
+ /* storage unavailable: keep it for this session */
}
-}
-void refreshClients();
+});
-async function resolve(id: string): Promise<Resolved> {
- let reason = "";
- for (const client of clients) {
- try {
- const info: any = await withClient((yt) => yt.getBasicInfo(id, { client: client as never }), getLang());
- const status = info.playability_status;
- if (status?.status && status.status !== "OK") {
- reason = text(status.reason) || reason;
- continue;
- }
- const formats: any[] = [...(info.streaming_data?.adaptive_formats ?? []), ...(info.streaming_data?.formats ?? [])].filter(
- (f) => f.has_audio && !f.has_video && typeof f.url === "string",
- );
- // AAC (m4a) first: every Android WebView plays it. Highest bitrate within the same kind.
- const best = formats.sort(
- (a, b) => Number(b.mime_type?.startsWith("audio/mp4")) - Number(a.mime_type?.startsWith("audio/mp4")) || (b.bitrate ?? 0) - (a.bitrate ?? 0),
- )[0];
- if (!best) continue;
- const expire = Number(new URL(best.url).searchParams.get("expire")) * 1000;
- const resolved: Resolved = {
- url: best.url,
- title: info.basic_info?.title ?? "",
- duration: info.basic_info?.duration ?? 0,
- expiresAt: expire || Date.now() + 3 * 3600_000,
- };
- cache.set(id, resolved);
- return resolved;
- } catch (e) {
- reason = (e as Error).message || reason;
- }
+async function resolve(id: string): Promise<DirectAudio> {
+ try {
+ const resolved = await directAudio(id, clients, getLang());
+ cache.set(id, resolved);
+ return resolved;
+ } catch (e) {
+ throw new ApiError(404, (e as Error).message || tr(getLang(), msg("noAudio")));
}
- throw new ApiError(404, reason || tr(getLang(), msg("noAudio")));
}
/** A track's stream, from cache while its URL is still good for a minute or more. */
-export function resolveAudio(id: string): Promise<Resolved> {
+export function resolveAudio(id: string): Promise<DirectAudio> {
const hit = cache.get(id);
if (hit && hit.expiresAt - Date.now() > 60_000) return Promise.resolve(hit);
let job = inflight.get(id);