mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
...
This commit is contained in:
1 parent
3043a755ee
commit
7f1d076902
17 files changed
+944
-46
No files matched your search
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* @module src/music/bilibili/BilibiliProxy
|
||||
* @description A tiny localhost HTTP proxy that lets the NodeLink/Lavalink
|
||||
* node fetch Bilibili CDN audio. Bilibili's DASH audio URLs (m4s) only
|
||||
* respond to requests carrying a bilibili Referer and a browser User-Agent —
|
||||
* headers an audio node cannot attach — so the bot signs the CDN URL with a
|
||||
* per-process HMAC key and hands the node
|
||||
* `http://<host>:<port>/s?u=<cdn-url>&e=<expiry>&x=<hmac>` instead. The
|
||||
* proxy validates the signature, then streams the CDN response (including
|
||||
* Range requests, which give seek support) with the right headers attached.
|
||||
*
|
||||
* The server starts lazily on the first Bilibili play and is unref'd, so it
|
||||
* never delays startup or shutdown. Only URLs signed by this very process
|
||||
* can pass through — the HMAC key is random per boot.
|
||||
*/
|
||||
|
||||
import http from "node:http";
|
||||
import crypto from "node:crypto";
|
||||
import { Readable } from "node:stream";
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { buildBilibiliCdnHeaders } from "./BilibiliResolver.mjs";
|
||||
|
||||
/** @type {number} @description How long a signed proxy URL stays valid (Bilibili CDN URLs themselves expire). */
|
||||
const PROXY_TTL_MS = 6 * 60 * 60 * 1000;
|
||||
/** @type {number} @description Timeout (ms) waiting for the CDN response headers. */
|
||||
const CDN_CONNECT_TIMEOUT_MS = 20_000;
|
||||
|
||||
/** @type {object} @description Effective proxy configuration (merged from config.json -> bilibili). */
|
||||
const _cfg = {
|
||||
enabled: true,
|
||||
bind: "127.0.0.1",
|
||||
port: 0,
|
||||
advertiseHost: null,
|
||||
};
|
||||
|
||||
/** @type {http.Server|null} @description The lazily-started proxy server (unref'd). */
|
||||
let _server = null;
|
||||
/** @type {Buffer|null} @description Per-process HMAC signing key. */
|
||||
let _key = null;
|
||||
/** @type {Promise|null} @description Memoized server start (idempotent). */
|
||||
let _starting = null;
|
||||
|
||||
/**
|
||||
* Merge the config.json `bilibili` section into the proxy configuration.
|
||||
* @param {object} [section]
|
||||
* @param {boolean} [section.enabled=true] - false disables Bilibili playback.
|
||||
* @param {string} [section.bind="127.0.0.1"] - Address the proxy listens on.
|
||||
* @param {number} [section.port=0] - Listen port (0 = pick a free port).
|
||||
* @param {string} [section.advertiseHost] - Host the audio node should use
|
||||
* to reach the proxy (defaults to the bind address; set when the node runs
|
||||
* on another machine/container).
|
||||
*/
|
||||
export function configureBilibiliProxy(section = {}) {
|
||||
if (section.bind != null) _cfg.bind = String(section.bind);
|
||||
if (section.port != null) _cfg.port = Number(section.port) || 0;
|
||||
if (section.advertiseHost != null) _cfg.advertiseHost = String(section.advertiseHost);
|
||||
if (section.enabled != null) _cfg.enabled = section.enabled !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Bilibili playback is enabled in config.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function bilibiliEnabled() {
|
||||
return _cfg.enabled === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The host:port pair advertised to the audio node. 0.0.0.0 binds are
|
||||
* advertised as 127.0.0.1 unless an explicit advertiseHost was configured.
|
||||
* @returns {string}
|
||||
*/
|
||||
function advertiseHost() {
|
||||
if (_cfg.advertiseHost) return _cfg.advertiseHost;
|
||||
return _cfg.bind === "0.0.0.0" || _cfg.bind === "::" ? "127.0.0.1" : _cfg.bind;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the proxy server (once per process) and return its listening info.
|
||||
* @returns {Promise<{port: number, host: string}>}
|
||||
*/
|
||||
export function ensureBilibiliProxy() {
|
||||
if (_starting) return _starting;
|
||||
_starting = new Promise((resolve, reject) => {
|
||||
try {
|
||||
_key = crypto.randomBytes(32);
|
||||
const server = http.createServer((req, res) => {
|
||||
handleProxyRequest(req, res).catch(err => {
|
||||
logger.warn("[BilibiliProxy] request failed: " + (err?.message || err));
|
||||
try {
|
||||
if (!res.headersSent) res.writeHead(502, { "Content-Type": "text/plain" });
|
||||
res.end("bilibili proxy error: " + (err?.message || err));
|
||||
} catch (_) {}
|
||||
});
|
||||
});
|
||||
server.on("clientError", (_err, socket) => {
|
||||
try { socket.destroy(); } catch (_) {}
|
||||
});
|
||||
server.listen(_cfg.port, _cfg.bind, () => {
|
||||
const addr = server.address();
|
||||
_server = server;
|
||||
const port = typeof addr === "object" && addr ? addr.port : _cfg.port;
|
||||
logger.player("[BilibiliProxy] listening on " + _cfg.bind + ":" + port + " (advertised as " + advertiseHost() + ")");
|
||||
resolve({ port, host: advertiseHost() });
|
||||
});
|
||||
server.once("error", (err) => {
|
||||
_starting = null;
|
||||
reject(new Error("bilibili proxy failed to listen on " + _cfg.bind + ":" + _cfg.port + ": " + err.message));
|
||||
});
|
||||
server.unref?.();
|
||||
} catch (e) {
|
||||
_starting = null;
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
return _starting;
|
||||
}
|
||||
|
||||
/**
|
||||
* Current proxy info (without starting it).
|
||||
* @returns {{port: number, host: string}|null}
|
||||
*/
|
||||
export function bilibiliProxyInfo() {
|
||||
if (!_server) return null;
|
||||
const addr = _server.address();
|
||||
const port = typeof addr === "object" && addr ? addr.port : _cfg.port;
|
||||
return { port, host: advertiseHost() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the proxy and clear its key (used by tests and reconfiguration).
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export function resetBilibiliProxy() {
|
||||
const server = _server;
|
||||
_server = null;
|
||||
_starting = null;
|
||||
_key = null;
|
||||
if (!server) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
try { server.close(() => resolve()); } catch (_) { resolve(); }
|
||||
try { server.closeAllConnections?.(); } catch (_) {}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* HMAC-SHA256 signature binding a CDN URL to its expiry epoch.
|
||||
* @param {string} target
|
||||
* @param {number} expires
|
||||
* @returns {string}
|
||||
*/
|
||||
function signTarget(target, expires) {
|
||||
return crypto.createHmac("sha256", _key).update(target + "." + expires).digest("hex");
|
||||
}
|
||||
|
||||
/**
|
||||
* Constant-time signature verification.
|
||||
* @param {string} target
|
||||
* @param {number} expires
|
||||
* @param {string} sig
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function verifySignature(target, expires, sig) {
|
||||
if (!_key) return false;
|
||||
const expected = Buffer.from(signTarget(target, expires), "utf8");
|
||||
const provided = Buffer.from(String(sig ?? ""), "utf8");
|
||||
return expected.length === provided.length && crypto.timingSafeEqual(expected, provided);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a Bilibili CDN URL into a proxy URL the audio node can fetch. Starts
|
||||
* the proxy on first use. The HMAC is computed over the base64url-encoded
|
||||
* target exactly as it travels in the `u` query parameter, so verification
|
||||
* on the serving side never has to guess the encoding.
|
||||
* @param {string} targetUrl - The raw CDN (m4s) URL from the playurl API.
|
||||
* @param {number} [ttlMs=PROXY_TTL_MS] - Signature lifetime.
|
||||
* @returns {Promise<string>} The signed proxy URL.
|
||||
*/
|
||||
export async function buildSignedProxyUrl(targetUrl, ttlMs = PROXY_TTL_MS) {
|
||||
const { port, host } = await ensureBilibiliProxy();
|
||||
const expires = Date.now() + ttlMs;
|
||||
const u = Buffer.from(String(targetUrl), "utf8").toString("base64url");
|
||||
const x = signTarget(u, expires);
|
||||
return "http://" + host + ":" + port + "/s?u=" + u + "&e=" + expires + "&x=" + x;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve one proxy request: verify the signature, fetch the CDN URL with the
|
||||
* Referer/UA headers Bilibili requires, and pipe the response through
|
||||
* (status, content-type/length/range and Range semantics included).
|
||||
* @param {http.IncomingMessage} req
|
||||
* @param {http.ServerResponse} res
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function handleProxyRequest(req, res) {
|
||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||
res.writeHead(405, { "Content-Type": "text/plain" });
|
||||
res.end("method not allowed");
|
||||
return;
|
||||
}
|
||||
|
||||
let u;
|
||||
try { u = new URL(req.url ?? "/", "http://localhost"); } catch (_) {
|
||||
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||
res.end("bad request");
|
||||
return;
|
||||
}
|
||||
if (u.pathname !== "/s") {
|
||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||
res.end("not found");
|
||||
return;
|
||||
}
|
||||
|
||||
const uParam = u.searchParams.get("u");
|
||||
const expires = Number(u.searchParams.get("e"));
|
||||
const sig = u.searchParams.get("x");
|
||||
if (!uParam || !Number.isFinite(expires) || !sig || Date.now() >= expires || !verifySignature(uParam, expires, sig)) {
|
||||
res.writeHead(403, { "Content-Type": "text/plain" });
|
||||
res.end("forbidden");
|
||||
return;
|
||||
}
|
||||
|
||||
let targetUrl;
|
||||
try { targetUrl = new URL(Buffer.from(uParam, "base64url").toString("utf8")); } catch (_) {
|
||||
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||
res.end("bad target");
|
||||
return;
|
||||
}
|
||||
if (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:") {
|
||||
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||
res.end("bad target protocol");
|
||||
return;
|
||||
}
|
||||
|
||||
const forwardHeaders = await buildBilibiliCdnHeaders();
|
||||
if (req.headers.range) forwardHeaders.Range = req.headers.range;
|
||||
|
||||
const abort = new AbortController();
|
||||
const connectTimer = setTimeout(() => abort.abort(), CDN_CONNECT_TIMEOUT_MS);
|
||||
req.once("close", () => abort.abort());
|
||||
|
||||
let upstream;
|
||||
try {
|
||||
upstream = await fetch(targetUrl.href, {
|
||||
method: req.method === "HEAD" ? "HEAD" : "GET",
|
||||
headers: forwardHeaders,
|
||||
redirect: "follow",
|
||||
signal: abort.signal,
|
||||
});
|
||||
} catch (e) {
|
||||
clearTimeout(connectTimer);
|
||||
throw new Error("CDN fetch failed: " + (e?.cause?.message || e?.message || String(e)));
|
||||
}
|
||||
clearTimeout(connectTimer);
|
||||
|
||||
const headers = {};
|
||||
for (const name of ["content-type", "content-length", "content-range", "accept-ranges"]) {
|
||||
const v = upstream.headers.get(name);
|
||||
if (v != null) headers[name] = v;
|
||||
}
|
||||
res.writeHead(upstream.status, headers);
|
||||
|
||||
if (req.method === "HEAD") {
|
||||
try { upstream.body?.cancel?.(); } catch (_) {}
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!upstream.body) {
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
const stream = Readable.fromWeb(upstream.body);
|
||||
stream.once("error", reject);
|
||||
res.once("error", reject);
|
||||
res.once("close", () => { abort.abort(); resolve(); });
|
||||
stream.pipe(res);
|
||||
res.once("finish", resolve);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
/**
|
||||
* @module src/music/bilibili/BilibiliResolver
|
||||
* @description Bilibili video resolution: URL detection (BV/av ids, b23.tv /
|
||||
* bili2233.cn short links, ?p= page selection), the public web API client
|
||||
* (view + playurl with browser-style headers and an automatic buvid
|
||||
* bootstrap), DASH audio-stream selection, and internal track building.
|
||||
*
|
||||
* The audio URLs Bilibili hands out only respond to requests carrying a
|
||||
* bilibili Referer and a browser User-Agent, so the raw CDN URL is never
|
||||
* handed to the audio pipeline directly — playback goes through the signed
|
||||
* local proxy in {@link module:src/music/bilibili/BilibiliProxy}.
|
||||
*/
|
||||
|
||||
import { Utils } from "../../utils/Utils.mjs";
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
|
||||
/** @type {string} @description Browser User-Agent required by Bilibili API and CDN endpoints. */
|
||||
export const BILIBILI_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";
|
||||
/** @type {string} @description Referer required by Bilibili CDN endpoints. */
|
||||
export const BILIBILI_REFERER = "https://www.bilibili.com/";
|
||||
|
||||
/** @type {string} @description Video metadata endpoint (bvid= or aid=). */
|
||||
const API_VIEW = "https://api.bilibili.com/x/web-interface/view";
|
||||
/** @type {string} @description Playback URL endpoint (DASH manifest when fnval=16). */
|
||||
const API_PLAYURL = "https://api.bilibili.com/x/player/playurl";
|
||||
/** @type {string} @description Homepage used once per process to bootstrap buvid3/b_nut cookies. */
|
||||
const BOOTSTRAP_URL = "https://www.bilibili.com/";
|
||||
|
||||
/** @type {number} @description Timeout (ms) for Bilibili API requests. */
|
||||
const API_TIMEOUT_MS = 15_000;
|
||||
/** @type {number} @description Timeout (ms) for short-link redirect resolution. */
|
||||
const SHORTLINK_TIMEOUT_MS = 10_000;
|
||||
/** @type {number} @description Timeout (ms) for the one-shot cookie bootstrap. */
|
||||
const BOOTSTRAP_TIMEOUT_MS = 10_000;
|
||||
/** @type {number} @description Maximum number of multi-page parts queued from one video. */
|
||||
const MAX_PAGES = 200;
|
||||
|
||||
/** @type {Set<string>} @description Bilibili hosts whose /video/ links the bot plays. */
|
||||
const BILIBILI_HOSTS = new Set([
|
||||
"bilibili.com",
|
||||
"www.bilibili.com",
|
||||
"m.bilibili.com",
|
||||
"b23.tv",
|
||||
"bili2233.cn",
|
||||
]);
|
||||
|
||||
/** @type {string} @description Error hint shown when Bilibili risk control blocks the server IP. */
|
||||
const BLOCKED_HINT =
|
||||
"Bilibili blocked this server's requests (risk control, HTTP 412). " +
|
||||
"Add a cookie string from a logged-in browser to config.json -> bilibili.cookie and restart the bot.";
|
||||
|
||||
/** @type {string|null} @description Optional cookie string from config (SESSDATA etc.), overrides the bootstrap. */
|
||||
let _cookieOverride = null;
|
||||
/** @type {string|null} @description buvid3/b_nut cookies picked up from the homepage bootstrap. */
|
||||
let _bootstrappedCookie = null;
|
||||
/** @type {Promise|null} @description Memoized bootstrap run (best effort, never rejects). */
|
||||
let _bootstrapPromise = null;
|
||||
|
||||
/**
|
||||
* Set a user-provided cookie string (from config.json -> bilibili.cookie).
|
||||
* Sent on every Bilibili API and CDN request; unlocks higher audio quality
|
||||
* and works around IP-level risk-control blocks.
|
||||
* @param {string|null} cookie
|
||||
*/
|
||||
export function setBilibiliCookie(cookie) {
|
||||
_cookieOverride = cookie ? String(cookie).trim() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One best-effort homepage GET per process: Bilibili's risk control expects
|
||||
* to see the buvid3/b_nut cookies the homepage sets, so picking them up
|
||||
* raises the request trust level at zero cost.
|
||||
* @returns {Promise<null>}
|
||||
*/
|
||||
function bootstrapCookies() {
|
||||
if (_bootstrapPromise) return _bootstrapPromise;
|
||||
_bootstrapPromise = (async () => {
|
||||
try {
|
||||
const res = await fetch(BOOTSTRAP_URL, {
|
||||
headers: { "User-Agent": BILIBILI_UA, "Accept": "text/html,application/xhtml+xml,*/*" },
|
||||
redirect: "follow",
|
||||
signal: AbortSignal.timeout(BOOTSTRAP_TIMEOUT_MS),
|
||||
});
|
||||
const parts = [];
|
||||
for (const raw of res.headers.getSetCookie?.() ?? []) {
|
||||
const pair = raw.split(";")[0].trim();
|
||||
if (/^(buvid3|b_nut|buvid4)=/.test(pair)) parts.push(pair);
|
||||
}
|
||||
try { res.body?.cancel?.(); } catch (_) {}
|
||||
if (parts.length) {
|
||||
_bootstrappedCookie = parts.join("; ");
|
||||
logger.player("[Bilibili] bootstrapped cookies: " + parts.map(p => p.split("=")[0]).join(","));
|
||||
}
|
||||
} catch (_) {
|
||||
/* best effort only — plain headerless requests still work on most IPs */
|
||||
}
|
||||
return null;
|
||||
})();
|
||||
return _bootstrapPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the header set for Bilibili API requests (UA, Referer, Accept and
|
||||
* the effective cookie: config override, else the bootstrapped buvid pair).
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
async function biliRequestHeaders() {
|
||||
if (!_cookieOverride) await bootstrapCookies();
|
||||
const headers = {
|
||||
"User-Agent": BILIBILI_UA,
|
||||
"Referer": BILIBILI_REFERER,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Language": "en-US,en;q=0.9",
|
||||
};
|
||||
const cookie = _cookieOverride || _bootstrappedCookie;
|
||||
if (cookie) headers.Cookie = cookie;
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the header set the local proxy forwards to Bilibili CDN hosts.
|
||||
* Same trust rules as the API headers: config cookie overrides bootstrap.
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
export async function buildBilibiliCdnHeaders() {
|
||||
if (!_cookieOverride) await bootstrapCookies();
|
||||
const headers = {
|
||||
"User-Agent": BILIBILI_UA,
|
||||
"Referer": BILIBILI_REFERER,
|
||||
"Accept": "*/*",
|
||||
};
|
||||
const cookie = _cookieOverride || _bootstrappedCookie;
|
||||
if (cookie) headers.Cookie = cookie;
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a Bilibili API error code into a user-readable message.
|
||||
* @param {number} code
|
||||
* @param {string} message
|
||||
* @returns {string}
|
||||
*/
|
||||
function describeApiError(code, message) {
|
||||
if (code === -412) return BLOCKED_HINT;
|
||||
if (code === -404 || code === 404 || code === -400) return "video not found (it may be private, deleted, or the link is wrong)";
|
||||
if (code === -403 || code === 403) return "this video is region-locked or private";
|
||||
if (code === 62002 || code === 62004) return "this video is not publicly visible";
|
||||
if (code === 62012) return "this video is only visible to its uploader";
|
||||
return "Bilibili API error " + code + (message ? ": " + message : "");
|
||||
}
|
||||
|
||||
/**
|
||||
* GET a Bilibili API endpoint and return its `data` payload, mapping HTTP
|
||||
* status and body error codes to readable messages.
|
||||
* @param {string} url
|
||||
* @returns {Promise<object>}
|
||||
* @throws {Error} with a user-readable message on network/HTTP/API errors.
|
||||
*/
|
||||
async function biliJson(url) {
|
||||
const headers = await biliRequestHeaders();
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, { headers, redirect: "follow", signal: AbortSignal.timeout(API_TIMEOUT_MS) });
|
||||
} catch (e) {
|
||||
throw new Error("Bilibili API unreachable: " + (e?.cause?.message || e?.message || String(e)));
|
||||
}
|
||||
if (res.status === 412) {
|
||||
try { res.body?.cancel?.(); } catch (_) {}
|
||||
throw new Error(BLOCKED_HINT);
|
||||
}
|
||||
if (res.status !== 200) {
|
||||
try { res.body?.cancel?.(); } catch (_) {}
|
||||
throw new Error("Bilibili API HTTP " + res.status);
|
||||
}
|
||||
let body;
|
||||
try {
|
||||
body = await res.json();
|
||||
} catch (_) {
|
||||
throw new Error("Bilibili API returned invalid JSON");
|
||||
}
|
||||
if (body.code !== 0) throw new Error(describeApiError(body.code, body.message));
|
||||
if (!body.data) throw new Error("Bilibili API returned no data");
|
||||
return body.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a string is an HTTP(S) URL on a known Bilibili host
|
||||
* (www./m. bilibili.com or the b23.tv / bili2233.cn shorteners).
|
||||
* @param {string} str
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isBilibiliUrl(str) {
|
||||
if (!str || typeof str !== "string") return false;
|
||||
const trimmed = str.trim();
|
||||
if (!/^https?:\/\//i.test(trimmed)) return false;
|
||||
try {
|
||||
const u = new URL(trimmed);
|
||||
return BILIBILI_HOSTS.has(u.hostname.toLowerCase());
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the video reference (BV/av id plus optional ?p= page) from a URL
|
||||
* on a Bilibili host. BV ids are case-sensitive and preserved verbatim.
|
||||
* @param {string} urlStr
|
||||
* @returns {{kind: "bvid"|"aid", id: string, page: number|null}|null}
|
||||
*/
|
||||
export function parseBilibiliVideoRef(urlStr) {
|
||||
let u;
|
||||
try { u = new URL(String(urlStr)); } catch (_) { return null; }
|
||||
if (!BILIBILI_HOSTS.has(u.hostname.toLowerCase())) return null;
|
||||
const m = u.pathname.match(/\/video\/(BV[0-9A-Za-z]{8,12}|av(\d+))/i);
|
||||
if (!m) return null;
|
||||
const raw = m[1];
|
||||
const isAv = /^av/i.test(raw);
|
||||
const pageRaw = u.searchParams.get("p");
|
||||
const page = pageRaw && /^\d+$/.test(pageRaw) ? Math.max(1, parseInt(pageRaw, 10)) : null;
|
||||
return { kind: isAv ? "aid" : "bvid", id: isAv ? m[2] : raw, page };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve b23.tv / bili2233.cn short links to their final URL by following
|
||||
* redirects. Falls back to the short URL itself when resolution fails (the
|
||||
* view API then produces the real error). Non-bilibili redirects (bangumi,
|
||||
* space, etc.) yield null — only /video/ pages are playable.
|
||||
* @param {URL} u
|
||||
* @returns {Promise<string|null>}
|
||||
*/
|
||||
async function resolveShortLink(u) {
|
||||
try {
|
||||
const res = await fetch(u.href, {
|
||||
headers: { "User-Agent": BILIBILI_UA, "Accept": "text/html,*/*" },
|
||||
redirect: "follow",
|
||||
signal: AbortSignal.timeout(SHORTLINK_TIMEOUT_MS),
|
||||
});
|
||||
const finalUrl = res.url || u.href;
|
||||
try { res.body?.cancel?.(); } catch (_) {}
|
||||
let final;
|
||||
try { final = new URL(finalUrl); } catch (_) { return null; }
|
||||
if (!BILIBILI_HOSTS.has(final.hostname.toLowerCase())) return null;
|
||||
return final.href;
|
||||
} catch (_) {
|
||||
return u.href;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize any accepted Bilibili link to its canonical URL form: short
|
||||
* hosts are expanded, other hosts pass through. Returns null when the
|
||||
* string is not a URL on a Bilibili host.
|
||||
* @param {string} str
|
||||
* @returns {Promise<string|null>}
|
||||
*/
|
||||
async function normalizeBilibiliUrl(str) {
|
||||
const trimmed = String(str ?? "").trim();
|
||||
if (!/^https?:\/\//i.test(trimmed)) return null;
|
||||
let u;
|
||||
try { u = new URL(trimmed); } catch (_) { return null; }
|
||||
const host = u.hostname.toLowerCase();
|
||||
if (!BILIBILI_HOSTS.has(host)) return null;
|
||||
if (host === "b23.tv" || host === "bili2233.cn") return resolveShortLink(u);
|
||||
return u.href;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch video metadata for a parsed reference.
|
||||
* @param {{kind: string, id: string}} ref
|
||||
* @returns {Promise<object>} The view API `data` payload.
|
||||
*/
|
||||
export async function fetchBilibiliView(ref) {
|
||||
const params = ref.kind === "bvid" ? { bvid: ref.id } : { aid: String(ref.id) };
|
||||
return biliJson(API_VIEW + "?" + new URLSearchParams(params));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the playback manifest (DASH when fnval=16) for one video page.
|
||||
* @param {{bvid?: string, aid?: number|string, cid: number|string}} meta
|
||||
* @returns {Promise<object>} The playurl API `data` payload.
|
||||
*/
|
||||
export async function fetchBilibiliPlayUrl(meta) {
|
||||
const params = { cid: String(meta.cid), fnval: "16", fourk: "1" };
|
||||
if (meta.bvid) params.bvid = meta.bvid;
|
||||
else if (meta.aid != null) params.aid = String(meta.aid);
|
||||
return biliJson(API_PLAYURL + "?" + new URLSearchParams(params));
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the best DASH audio stream from a playurl payload: all audio
|
||||
* variants (plain, flac, dolby when a login cookie unlocks them) are
|
||||
* candidates and the highest-bandwidth entry wins.
|
||||
* @param {object} data - playurl `data` payload.
|
||||
* @returns {object|null} The chosen audio stream entry, or null.
|
||||
*/
|
||||
export function pickBestAudioStream(data) {
|
||||
const dash = data?.dash;
|
||||
const candidates = [];
|
||||
if (Array.isArray(dash?.audio)) candidates.push(...dash.audio);
|
||||
if (Array.isArray(dash?.flac?.audio)) candidates.push(...dash.flac.audio);
|
||||
if (Array.isArray(dash?.dolby?.audio)) candidates.push(...dash.dolby.audio);
|
||||
const usable = candidates.filter(a => typeof a?.baseUrl === "string" && a.baseUrl.startsWith("http"));
|
||||
usable.sort((a, b) => (b.bandwidth || 0) - (a.bandwidth || 0));
|
||||
return usable[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the https page URL for a video (optionally a specific part).
|
||||
* @param {string} bvid
|
||||
* @param {number|null} page
|
||||
* @returns {string}
|
||||
*/
|
||||
function pageUrl(bvid, page) {
|
||||
return page && page > 1
|
||||
? "https://www.bilibili.com/video/" + bvid + "?p=" + page
|
||||
: "https://www.bilibili.com/video/" + bvid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Force https on Bilibili asset URLs (thumbnails come back as http://).
|
||||
* @param {string|null} url
|
||||
* @returns {string|null}
|
||||
*/
|
||||
function httpsify(url) {
|
||||
if (typeof url !== "string" || !url) return null;
|
||||
return url.replace(/^http:\/\//i, "https://");
|
||||
}
|
||||
|
||||
/**
|
||||
* Build one internal track object for a single video page.
|
||||
* @param {object} opts - { bvid, aid, cid, page, partTitle, title, durationSec, thumbnail, owner }
|
||||
* @returns {object}
|
||||
*/
|
||||
function buildTrack(opts) {
|
||||
const { bvid, aid, cid, page, partTitle, title, durationSec, thumbnail, owner } = opts;
|
||||
const displayTitle = partTitle && partTitle !== title ? title + " [P" + page + ": " + partTitle + "]" : title;
|
||||
const ms = Math.max(0, Math.floor(Number(durationSec) || 0) * 1000);
|
||||
const authorUrl = owner?.mid ? "https://space.bilibili.com/" + owner.mid : null;
|
||||
return {
|
||||
type: "bilibili",
|
||||
videoId: bvid,
|
||||
encoded: "",
|
||||
sourceName: "bilibili",
|
||||
title: displayTitle,
|
||||
url: pageUrl(bvid, page),
|
||||
thumbnail: httpsify(thumbnail),
|
||||
spotifyUrl: null,
|
||||
artist: owner?.name ?? null,
|
||||
author: { name: owner?.name ?? "Unknown", url: authorUrl },
|
||||
artists: null,
|
||||
_durationMs: ms,
|
||||
duration: { timestamp: Utils.prettifyMS(ms), seconds: Math.floor(ms / 1000) },
|
||||
bilibili: { bvid, aid: aid ?? null, cid, page: page || 1 },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a view API payload into queueable tracks.
|
||||
* Requested page: exactly that part. Multi-page video without a page: every
|
||||
* part (capped at {@link MAX_PAGES}), matching the YouTube playlist UX.
|
||||
* @param {object} data - view API `data` payload.
|
||||
* @param {number|null} requestedPage
|
||||
* @returns {{video: object, tracks: Array<object>}}
|
||||
*/
|
||||
function buildBilibiliResult(data, requestedPage) {
|
||||
const bvid = data.bvid;
|
||||
const aid = data.aid ?? null;
|
||||
const title = String(data.title ?? "Bilibili video");
|
||||
const pic = httpsify(data.pic);
|
||||
const owner = data.owner ?? null;
|
||||
const pages = Array.isArray(data.pages) ? data.pages : [];
|
||||
|
||||
const base = { bvid, aid, title, thumbnail: pic, owner };
|
||||
const video = { ...base, url: pageUrl(bvid, null), durationSec: data.duration ?? 0 };
|
||||
|
||||
if (requestedPage != null) {
|
||||
if (pages.length > 1) {
|
||||
const page = pages.find(p => Number(p.page) === requestedPage)
|
||||
?? (requestedPage >= 1 && requestedPage <= pages.length ? pages[requestedPage - 1] : null);
|
||||
if (!page) throw new Error("this video has " + pages.length + " part(s) — there is no part " + requestedPage);
|
||||
return { video, tracks: [buildTrack({
|
||||
...base, cid: page.cid, page: Number(page.page) || requestedPage,
|
||||
partTitle: page.part, durationSec: page.duration ?? data.duration,
|
||||
})] };
|
||||
}
|
||||
if (requestedPage > 1) throw new Error("this video has a single part — there is no part " + requestedPage);
|
||||
}
|
||||
|
||||
if (pages.length > 1) {
|
||||
const tracks = pages.slice(0, MAX_PAGES).map(p => buildTrack({
|
||||
...base, cid: p.cid, page: Number(p.page) || 1,
|
||||
partTitle: p.part, durationSec: p.duration ?? data.duration,
|
||||
}));
|
||||
return { video, tracks };
|
||||
}
|
||||
|
||||
return {
|
||||
video,
|
||||
tracks: [buildTrack({
|
||||
...base, cid: data.cid, page: 1, partTitle: null, durationSec: data.duration ?? 0,
|
||||
})],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Full resolution pipeline for a pasted Bilibili link: normalize (expand
|
||||
* short links), parse the video reference, fetch metadata, build tracks.
|
||||
* @param {string} input - The raw query string (a Bilibili URL).
|
||||
* @returns {Promise<{video: object, tracks: Array<object>}>}
|
||||
* @throws {Error} with a user-readable message when the link is not a
|
||||
* playable video, the API fails, or the video is unavailable.
|
||||
*/
|
||||
export async function resolveBilibiliVideo(input) {
|
||||
const normalized = await normalizeBilibiliUrl(input);
|
||||
if (!normalized) throw new Error("not a Bilibili link");
|
||||
const ref = parseBilibiliVideoRef(normalized);
|
||||
if (!ref) throw new Error("only Bilibili video links are supported (…/video/BV… or …/video/av…)");
|
||||
const data = await fetchBilibiliView(ref);
|
||||
logger.player("[Bilibili] resolved " + (ref.kind === "bvid" ? ref.id : "av" + ref.id) + ": " + data.title);
|
||||
return buildBilibiliResult(data, ref.page);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* @module src/music/bilibili
|
||||
* @description Bilibili playback support barrel: URL detection, video/page
|
||||
* resolution via the public web API, best-audio-stream selection, and the
|
||||
* signed local proxy that lets the audio node fetch Bilibili CDN streams.
|
||||
*
|
||||
* Flow: `%play https://www.bilibili.com/video/BV…` → SearchMixin.play()
|
||||
* detects the link → resolveBilibiliVideo() builds queueable track(s) → at
|
||||
* playback time getBilibiliStreamUrl() re-resolves a fresh DASH audio URL
|
||||
* (they expire) and wraps it in a signed proxy URL → the existing
|
||||
* Lavalink/NodeLink resolve-through pipeline decodes it like any other
|
||||
* direct audio stream.
|
||||
*/
|
||||
|
||||
import {
|
||||
bilibiliEnabled,
|
||||
buildSignedProxyUrl,
|
||||
configureBilibiliProxy,
|
||||
ensureBilibiliProxy,
|
||||
} from "./BilibiliProxy.mjs";
|
||||
import { fetchBilibiliPlayUrl, pickBestAudioStream, setBilibiliCookie } from "./BilibiliResolver.mjs";
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* Configure Bilibili support from the config.json `bilibili` section.
|
||||
* Called once at bot startup; every field is optional.
|
||||
* @param {object} [section] - config.json -> bilibili
|
||||
* @param {boolean} [section.enabled=true] - false disables Bilibili playback.
|
||||
* @param {string} [section.bind="127.0.0.1"] - Proxy listen address.
|
||||
* @param {number} [section.port=0] - Proxy listen port (0 = ephemeral).
|
||||
* @param {string} [section.advertiseHost] - Host the audio node uses to
|
||||
* reach the proxy when it runs on another machine/container.
|
||||
* @param {string} [section.cookie] - Browser cookie string (SESSDATA etc.);
|
||||
* unlocks higher audio quality and works around IP blocks.
|
||||
*/
|
||||
export function configureBilibili(section = {}) {
|
||||
setBilibiliCookie(section.cookie ?? null);
|
||||
configureBilibiliProxy(section);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a fresh, playable stream URL for a queued Bilibili track.
|
||||
* DASH audio URLs expire after a few hours, so this runs at every play
|
||||
* (and every seek/loop) rather than at queue time: the playurl API is
|
||||
* re-queried, the best audio stream picked, and the CDN URL wrapped in a
|
||||
* signed proxy URL the audio node can fetch with the right Referer/UA.
|
||||
* @param {object} track - Internal track with a `bilibili` metadata field.
|
||||
* @returns {Promise<{url: string, backupUrls: Array<string>}>}
|
||||
* @throws {Error} with a user-readable message when resolution fails.
|
||||
*/
|
||||
export async function getBilibiliStreamUrl(track) {
|
||||
const meta = track?.bilibili;
|
||||
if (!meta || (!meta.bvid && meta.aid == null) || meta.cid == null) {
|
||||
throw new Error("track is missing Bilibili stream metadata");
|
||||
}
|
||||
if (!bilibiliEnabled()) {
|
||||
throw new Error("Bilibili playback is disabled in config.json -> bilibili.enabled");
|
||||
}
|
||||
await ensureBilibiliProxy();
|
||||
|
||||
const data = await fetchBilibiliPlayUrl(meta);
|
||||
const best = pickBestAudioStream(data);
|
||||
if (!best?.baseUrl) {
|
||||
throw new Error("Bilibili returned no playable audio stream for this video");
|
||||
}
|
||||
|
||||
const url = await buildSignedProxyUrl(best.baseUrl);
|
||||
logger.player("[Bilibili] audio stream ready (bandwidth " + (best.bandwidth || "?") + "): " + url.substring(0, 60) + "...");
|
||||
return { url, backupUrls: Array.isArray(best.backupUrl) ? best.backupUrl : [] };
|
||||
}
|
||||
|
||||
export { isBilibiliUrl, parseBilibiliVideoRef, resolveBilibiliVideo } from "./BilibiliResolver.mjs";
|
||||
export { setBilibiliCookie, BILIBILI_UA, BILIBILI_REFERER } from "./BilibiliResolver.mjs";
|
||||
export {
|
||||
bilibiliEnabled,
|
||||
bilibiliProxyInfo,
|
||||
ensureBilibiliProxy,
|
||||
resetBilibiliProxy,
|
||||
buildSignedProxyUrl,
|
||||
} from "./BilibiliProxy.mjs";
|
||||
Reference in new issue
Block a user