mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
...
This commit is contained in:
1 parent
7f1d076902
commit
e0994dfbc2
4 files changed
+361
-103
No files matched your search
@@ -112,7 +112,7 @@ A few things worth knowing:
|
||||
- **Filters** (bassboost, nightcore, etc.) are applied server-side by NodeLink, so they take effect on the next track that starts.
|
||||
- **Volume** is applied client-side by the LiveKit connection (1–200).
|
||||
- Radio metadata (StreamTitle) is read with **ffprobe** (`ffprobe-static`).
|
||||
- **Bilibili playback** — `%play https://www.bilibili.com/video/BV…` (b23.tv short links and `?p=` parts included) resolves the video through Bilibili's web API, picks the best DASH audio stream, and feeds it to the node through a signed localhost proxy that attaches the Referer/User-Agent headers Bilibili's CDN requires. Multi-part videos queue like a playlist. If Bilibili risk-control blocks your hosting IP (HTTP 412), set `bilibili.cookie` in config.json to a logged-in browser cookie string. The proxy binds `127.0.0.1` by default — set `bilibili.advertiseHost` (and `bind: "0.0.0.0"`) when your node runs on another machine.
|
||||
- **Bilibili playback** — `%play https://www.bilibili.com/video/BV…` (b23.tv short links and `?p=` parts included) resolves the video through Bilibili's web API, picks the best DASH audio stream, and feeds it to the node through a signed localhost proxy that attaches the Referer/User-Agent headers Bilibili's CDN requires. Multi-part videos queue like a playlist. The bot generates and manages its Bilibili device fingerprint (buvid3/buvid4/b_nut) automatically and retries once with a fresh fingerprint when risk control interferes; anonymous playback falls back to a progressive mp4, and if Bilibili risk-control blocks your hosting IP anyway (HTTP 412), set `bilibili.cookie` in config.json to your logged-in browser's cookie header — SESSDATA is the part that matters (placeholder values are ignored). The proxy binds `127.0.0.1` by default — set `bilibili.advertiseHost` (and `bind: "0.0.0.0"`) when your node runs on another machine.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@
|
||||
"port": 0,
|
||||
"advertiseHost": null,
|
||||
"cookie": null,
|
||||
"Comment": "Bilibili video playback (%play https://www.bilibili.com/video/BV... , b23.tv short links and ?p= parts included). Bilibili's CDN only serves audio to requests with a bilibili Referer, so the bot runs a tiny local HTTP proxy that adds those headers and hands a signed URL to your NodeLink/Lavalink node. Defaults work when the node runs on the same host as the bot (nodelink.host = localhost). bind/port: what the proxy listens on (port 0 = pick a free port). advertiseHost: the host your audio node should use to reach the proxy — set it (e.g. your bot's LAN IP or Docker service name, and bind 0.0.0.0) only when the node runs on a different machine. cookie: optional browser cookie string (SESSDATA=...; buvid3=...) — unlocks higher audio quality and fixes 'Bilibili blocked this server's requests (HTTP 412)' on flagged hosting IPs; copy it from a logged-in browser's devtools."
|
||||
"Comment": "Bilibili video playback (%play https://www.bilibili.com/video/BV... , b23.tv short links and ?p= parts included). Bilibili's CDN only serves audio to requests with a bilibili Referer, so the bot runs a tiny local HTTP proxy that adds those headers and hands a signed URL to your NodeLink/Lavalink node. Defaults work when the node runs on the same host as the bot (nodelink.host = localhost). bind/port: what the proxy listens on (port 0 = pick a free port). advertiseHost: the host your audio node should use to reach the proxy — set it (e.g. your bot's LAN IP or Docker service name, and bind 0.0.0.0) only when the node runs on a different machine. cookie: optional browser cookie string from a logged-in browser — SESSDATA is the only part that matters (it unlocks higher audio quality and fixes 'Bilibili blocked this server's requests (HTTP 412)' on flagged hosting IPs). buvid3/buvid4/b_nut device cookies are generated and managed automatically; if you paste them anyway, placeholder-looking or malformed values are ignored. Copy the whole cookie header from your browser's devtools."
|
||||
},
|
||||
"comment-radio": {
|
||||
"message": "If you have radio stations you'd like to connect, add them to the array below. Radio stations must be rendered like following:",
|
||||
|
||||
@@ -2,8 +2,18 @@
|
||||
* @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.
|
||||
* with a self-managed device fingerprint, DASH audio-stream selection (with
|
||||
* a progressive mp4 fallback for anonymous playback), and internal track
|
||||
* building.
|
||||
*
|
||||
* Bilibili's risk control (HTTP 412 / code -412) blocks browser-style
|
||||
* requests that lack a device fingerprint, so the module bootstraps one per
|
||||
* process: the finger/spi endpoint mints a fresh buvid3/buvid4 pair and a
|
||||
* homepage GET contributes b_nut. A user cookie from config (SESSDATA etc.)
|
||||
* is sanitized — placeholder-looking or malformed values are dropped with a
|
||||
* log line instead of poisoning the request trust level — and layered on top
|
||||
* of the fingerprint, and every fingerprint-blocked request refreshes the
|
||||
* fingerprint and retries once before surfacing the config-cookie hint.
|
||||
*
|
||||
* 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
|
||||
@@ -15,26 +25,21 @@ 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";
|
||||
export const BILIBILI_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.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 Page origin paired with the Referer on browser-style requests. */
|
||||
const BILIBILI_ORIGIN = "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. */
|
||||
/** @type {string} @description Device-fingerprint endpoint returning a fresh buvid3/buvid4 pair. */
|
||||
const API_FINGER_SPI = "https://api.bilibili.com/x/frontend/finger/spi";
|
||||
/** @type {string} @description Homepage used to pick up buvid3/b_nut/buvid4 Set-Cookie values. */
|
||||
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",
|
||||
@@ -44,55 +49,203 @@ const BILIBILI_HOSTS = new Set([
|
||||
"bili2233.cn",
|
||||
]);
|
||||
|
||||
/** @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 fingerprint bootstrap requests. */
|
||||
const BOOTSTRAP_TIMEOUT_MS = 10_000;
|
||||
/** @type {number} @description Cool-down (ms) before retrying a risk-control-blocked request. */
|
||||
const BLOCK_RETRY_DELAY_MS = 1_200;
|
||||
/** @type {number} @description Minimum spacing (ms) between fingerprint refreshes. */
|
||||
const REFRESH_MIN_INTERVAL_MS = 2_500;
|
||||
/** @type {number} @description Maximum number of multi-page parts queued from one video. */
|
||||
const MAX_PAGES = 200;
|
||||
|
||||
/** @type {object} @description Browser-exact header set for api.bilibili.com fetch calls. */
|
||||
const API_HEADERS = {
|
||||
"User-Agent": BILIBILI_UA,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
||||
"Referer": BILIBILI_REFERER,
|
||||
"Origin": BILIBILI_ORIGIN,
|
||||
"sec-ch-ua": '"Chromium";v="137", "Google Chrome";v="137", "Not-A.Brand";v="99"',
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-platform": '"Windows"',
|
||||
"sec-fetch-dest": "empty",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-site": "same-site",
|
||||
};
|
||||
|
||||
/** @type {object} @description Navigation header set for the homepage bootstrap request. */
|
||||
const NAV_HEADERS = {
|
||||
"User-Agent": BILIBILI_UA,
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
||||
"sec-fetch-dest": "document",
|
||||
"sec-fetch-mode": "navigate",
|
||||
"sec-fetch-site": "none",
|
||||
"sec-fetch-user": "?1",
|
||||
"Upgrade-Insecure-Requests": "1",
|
||||
};
|
||||
|
||||
/** @type {object} @description Header set the local proxy forwards to Bilibili CDN hosts. */
|
||||
const CDN_HEADERS = {
|
||||
"User-Agent": BILIBILI_UA,
|
||||
"Accept": "*/*",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
||||
"Referer": BILIBILI_REFERER,
|
||||
"Origin": BILIBILI_ORIGIN,
|
||||
"sec-fetch-dest": "empty",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-site": "cross-site",
|
||||
};
|
||||
|
||||
/** @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.";
|
||||
"The bot manages its device fingerprint automatically, so a persistent block means Bilibili flagged " +
|
||||
"this hosting IP: copy your browser's cookie header into config.json -> bilibili.cookie " +
|
||||
"(SESSDATA is the part that matters — buvid3/buvid4/b_nut are auto-generated, placeholder values are ignored) " +
|
||||
"and restart the bot. Shared-hosting IPs may stay blocked; a different egress IP may be required.";
|
||||
|
||||
/** @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 {RegExp} @description Values that are clearly config-example placeholders rather than real cookies. */
|
||||
const PLACEHOLDER_RE =
|
||||
/your[_\- ]|_here\b|\bplaceholder\b|\bexample\b|\bsample\b|\bdummy\b|\bfake\b|change[_\-]?me|\bfixme\b|\btodo\b|\bxxx\b|^\.{2,}$|^<[^>]*>$|\{\{|\}\}/i;
|
||||
|
||||
/** @type {Map<string,string>|null} @description Sanitized cookie pairs from config (SESSDATA etc.). */
|
||||
let _userCookiePairs = null;
|
||||
/** @type {object|null} @description Auto-managed device fingerprint (buvid3/buvid4/b_nut). */
|
||||
let _fingerprint = null;
|
||||
/** @type {Promise|null} @description Memoized bootstrap run (best effort, never rejects). */
|
||||
let _bootstrapPromise = null;
|
||||
/** @type {Promise|null} @description Shared cool-down + refresh promise for blocked requests. */
|
||||
let _refreshPromise = null;
|
||||
/** @type {number} @description Timestamp (ms) of the last fingerprint refresh trigger. */
|
||||
let _refreshGate = 0;
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Whether a cookie value is plausible for its (known) name. Unknown cookie
|
||||
* names only need a sane length and no control characters; known Bilibili
|
||||
* cookie names get their real format so garbage (e.g. a placeholder pasted
|
||||
* from a config example) never rides along on a request.
|
||||
* @param {string} name
|
||||
* @param {string} value
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function setBilibiliCookie(cookie) {
|
||||
_cookieOverride = cookie ? String(cookie).trim() : null;
|
||||
function plausibleCookieValue(name, value) {
|
||||
if (value.length > 512 || /[\x00-\x1f\x7f]/.test(value)) return false;
|
||||
switch (name) {
|
||||
case "buvid3": return /^[A-Za-z0-9-]{16,}$/.test(value);
|
||||
case "b_nut": return /^[0-9]{9,11}$/.test(value);
|
||||
case "buvid4": return /^[A-Za-z0-9-+=]{20,}$/.test(value);
|
||||
case "SESSDATA": return /^[A-Za-z0-9,.*%_+-]{16,}$/.test(value);
|
||||
case "bili_jct":
|
||||
case "DedeUserIDCKMd5": return /^[0-9a-fA-F]{32}$/.test(value);
|
||||
case "DedeUserID": return /^[0-9]{3,20}$/.test(value);
|
||||
default: return value.length >= 4;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Sanitize a user-supplied cookie string: split on ";", drop pairs whose
|
||||
* name or value is malformed, obviously a placeholder, or implausible for a
|
||||
* known Bilibili cookie name (those would lower the request trust level
|
||||
* instead of raising it). Real browser cookie headers pass untouched.
|
||||
* @param {string|null} str
|
||||
* @returns {{pairs: Map<string,string>, dropped: Array<string>}}
|
||||
*/
|
||||
function sanitizeCookieString(str) {
|
||||
const pairs = new Map();
|
||||
const dropped = [];
|
||||
if (!str || typeof str !== "string") return { pairs, dropped };
|
||||
for (const chunk of str.split(";")) {
|
||||
const pair = chunk.trim();
|
||||
if (!pair) continue;
|
||||
const eq = pair.indexOf("=");
|
||||
const name = eq > 0 ? pair.slice(0, eq).trim() : "";
|
||||
const value = eq > 0 ? pair.slice(eq + 1).trim() : "";
|
||||
if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) { dropped.push(pair.slice(0, 24) || "(empty)"); continue; }
|
||||
if (!value || PLACEHOLDER_RE.test(value) || !plausibleCookieValue(name, value)) { dropped.push(name); continue; }
|
||||
pairs.set(name, value);
|
||||
}
|
||||
return { pairs, dropped };
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a user-provided cookie string (from config.json -> bilibili.cookie).
|
||||
* Valid pairs (SESSDATA, bili_jct, DedeUserID, ...) are layered on top of
|
||||
* the auto-managed device fingerprint; placeholder-looking or malformed
|
||||
* values are dropped with a log line instead of poisoning every request.
|
||||
* @param {string|null} cookie
|
||||
*/
|
||||
export function setBilibiliCookie(cookie) {
|
||||
const { pairs, dropped } = sanitizeCookieString(cookie);
|
||||
_userCookiePairs = pairs.size ? pairs : null;
|
||||
if (dropped.length) {
|
||||
logger.warn("[Bilibili] cookie: ignoring " + dropped.join(", ")
|
||||
+ " (placeholder-looking or malformed; buvid3/buvid4/b_nut are generated automatically)");
|
||||
} else if (_userCookiePairs) {
|
||||
logger.player("[Bilibili] cookie: using " + [..._userCookiePairs.keys()].join(", ") + " from config");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The auto-managed device fingerprint. Bilibili's risk control expects to
|
||||
* see buvid3 (and friends) on browser-style requests; the finger/spi
|
||||
* endpoint mints a fresh pair even from IPs the WAF already distrusts, and
|
||||
* the homepage GET contributes b_nut. Best effort: on total failure requests
|
||||
* simply go out without a fingerprint.
|
||||
* @returns {Promise<null>}
|
||||
*/
|
||||
function bootstrapCookies() {
|
||||
function bootstrapFingerprint() {
|
||||
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 */
|
||||
const fp = {};
|
||||
await Promise.all([
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch(API_FINGER_SPI, {
|
||||
headers: { ...API_HEADERS },
|
||||
redirect: "follow",
|
||||
signal: AbortSignal.timeout(BOOTSTRAP_TIMEOUT_MS),
|
||||
});
|
||||
if (res.status === 200) {
|
||||
const body = await res.json();
|
||||
if (body?.code === 0 && body.data) {
|
||||
if (typeof body.data.b_3 === "string" && body.data.b_3) fp.buvid3 = body.data.b_3;
|
||||
if (typeof body.data.b_4 === "string" && body.data.b_4) fp.buvid4 = body.data.b_4;
|
||||
}
|
||||
} else {
|
||||
try { res.body?.cancel?.(); } catch (_) {}
|
||||
}
|
||||
} catch (_) {}
|
||||
return null;
|
||||
})(),
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch(BOOTSTRAP_URL, {
|
||||
headers: { ...NAV_HEADERS },
|
||||
redirect: "follow",
|
||||
signal: AbortSignal.timeout(BOOTSTRAP_TIMEOUT_MS),
|
||||
});
|
||||
const jar = {};
|
||||
for (const raw of res.headers.getSetCookie?.() ?? []) {
|
||||
const pair = raw.split(";")[0].trim();
|
||||
const eq = pair.indexOf("=");
|
||||
if (eq > 0) jar[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim();
|
||||
}
|
||||
try { res.body?.cancel?.(); } catch (_) {}
|
||||
if (!fp.buvid3 && plausibleCookieValue("buvid3", jar.buvid3 ?? "")) fp.buvid3 = jar.buvid3;
|
||||
if (plausibleCookieValue("b_nut", jar.b_nut ?? "")) fp.b_nut = jar.b_nut;
|
||||
if (!fp.buvid4 && plausibleCookieValue("buvid4", jar.buvid4 ?? "")) fp.buvid4 = jar.buvid4;
|
||||
} catch (_) {}
|
||||
return null;
|
||||
})(),
|
||||
]);
|
||||
_fingerprint = Object.keys(fp).length ? fp : null;
|
||||
if (_fingerprint) {
|
||||
logger.player("[Bilibili] device fingerprint ready: " + Object.keys(_fingerprint).join(","));
|
||||
}
|
||||
return null;
|
||||
})();
|
||||
@@ -100,36 +253,93 @@ function bootstrapCookies() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the header set for Bilibili API requests (UA, Referer, Accept and
|
||||
* the effective cookie: config override, else the bootstrapped buvid pair).
|
||||
* Clear the memoized device fingerprint and pending refresh state so the
|
||||
* next request bootstraps a fresh one (used by tests to isolate scenarios).
|
||||
*/
|
||||
export function resetBilibiliFingerprint() {
|
||||
_bootstrapPromise = null;
|
||||
_fingerprint = null;
|
||||
_refreshPromise = null;
|
||||
_refreshGate = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-bootstrap the device fingerprint right now — a fresh buvid3 often
|
||||
* lifts a transient risk-control block.
|
||||
* @returns {Promise<null>}
|
||||
*/
|
||||
function refreshFingerprint() {
|
||||
_bootstrapPromise = null;
|
||||
return bootstrapFingerprint();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared cool-down + refresh for risk-control-blocked requests: one short
|
||||
* pause, then a single fingerprint refresh no matter how many requests were
|
||||
* blocked at the same time (the refresh is rate-limited so parallel queue
|
||||
* loads cannot hammer the fingerprint endpoint).
|
||||
* @returns {Promise<null>}
|
||||
*/
|
||||
function refreshAfterBlock() {
|
||||
const now = Date.now();
|
||||
if (!_refreshPromise || now - _refreshGate >= REFRESH_MIN_INTERVAL_MS) {
|
||||
_refreshGate = now;
|
||||
_refreshPromise = (async () => {
|
||||
await new Promise((r) => setTimeout(r, BLOCK_RETRY_DELAY_MS));
|
||||
logger.warn("[Bilibili] risk control block (412) — refreshing device fingerprint and retrying once");
|
||||
await refreshFingerprint();
|
||||
})();
|
||||
}
|
||||
return _refreshPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* The cookie sent on Bilibili requests: sanitized config pairs first, then
|
||||
* fingerprint fill-ins for any device cookies the config did not validly
|
||||
* provide. Returns null when neither source has anything.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
function effectiveCookie() {
|
||||
const parts = [];
|
||||
const seen = new Set();
|
||||
if (_userCookiePairs) {
|
||||
for (const [name, value] of _userCookiePairs) {
|
||||
parts.push(name + "=" + value);
|
||||
seen.add(name);
|
||||
}
|
||||
}
|
||||
if (_fingerprint) {
|
||||
for (const name of ["buvid3", "b_nut", "buvid4"]) {
|
||||
if (!seen.has(name) && _fingerprint[name]) parts.push(name + "=" + _fingerprint[name]);
|
||||
}
|
||||
}
|
||||
return parts.length ? parts.join("; ") : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the header set for Bilibili API requests: the browser-exact UA /
|
||||
* Referer / Origin / Sec-Fetch set plus the effective cookie (config pairs
|
||||
* layered over the auto-managed device fingerprint).
|
||||
* @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;
|
||||
await bootstrapFingerprint();
|
||||
const headers = { ...API_HEADERS };
|
||||
const cookie = effectiveCookie();
|
||||
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.
|
||||
* Build the header set the local proxy forwards to Bilibili CDN hosts. Same
|
||||
* trust rules as the API headers: the sanitized config cookie layered over
|
||||
* the auto-managed device fingerprint.
|
||||
* @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;
|
||||
await bootstrapFingerprint();
|
||||
const headers = { ...CDN_HEADERS };
|
||||
const cookie = effectiveCookie();
|
||||
if (cookie) headers.Cookie = cookie;
|
||||
return headers;
|
||||
}
|
||||
@@ -151,36 +361,45 @@ function describeApiError(code, message) {
|
||||
|
||||
/**
|
||||
* GET a Bilibili API endpoint and return its `data` payload, mapping HTTP
|
||||
* status and body error codes to readable messages.
|
||||
* status and body error codes to readable messages. Risk-control blocks
|
||||
* (HTTP 412 or body code -412) refresh the device fingerprint and retry
|
||||
* exactly once before surfacing the config-cookie hint.
|
||||
* @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)));
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
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 (_) {}
|
||||
if (attempt === 0) { await refreshAfterBlock(); continue; }
|
||||
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 === -412) {
|
||||
if (attempt === 0) { await refreshAfterBlock(); continue; }
|
||||
throw new Error(BLOCKED_HINT);
|
||||
}
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -275,12 +494,18 @@ export async function fetchBilibiliView(ref) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the playback manifest (DASH when fnval=16) for one video page.
|
||||
* Fetch the playback manifest for one video page. Default mode requests the
|
||||
* DASH manifest (fnval=16); html5 mode requests the anonymous-friendly
|
||||
* progressive mp4 (durl) used as a second chance when no DASH audio stream
|
||||
* is available (DASH requires a login cookie).
|
||||
* @param {{bvid?: string, aid?: number|string, cid: number|string}} meta
|
||||
* @param {{html5?: boolean}} [opts]
|
||||
* @returns {Promise<object>} The playurl API `data` payload.
|
||||
*/
|
||||
export async function fetchBilibiliPlayUrl(meta) {
|
||||
const params = { cid: String(meta.cid), fnval: "16", fourk: "1" };
|
||||
export async function fetchBilibiliPlayUrl(meta, opts = {}) {
|
||||
const params = opts.html5
|
||||
? { cid: String(meta.cid), platform: "html5", high_quality: "1" }
|
||||
: { 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));
|
||||
@@ -304,6 +529,25 @@ export function pickBestAudioStream(data) {
|
||||
return usable[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the progressive (non-DASH) fallback stream from a playurl payload: a
|
||||
* single-segment durl mp4/flv whose audio the node can decode directly.
|
||||
* Zero or multiple segments yield null — multi-segment progressive streams
|
||||
* cannot be chained through one proxy URL.
|
||||
* @param {object} data - playurl `data` payload.
|
||||
* @returns {{url: string, backupUrls: Array<string>}|null}
|
||||
*/
|
||||
export function pickProgressiveStream(data) {
|
||||
const durl = Array.isArray(data?.durl) ? data.durl : null;
|
||||
if (!durl || durl.length !== 1) return null;
|
||||
const seg = durl[0];
|
||||
if (typeof seg?.url !== "string" || !seg.url.startsWith("http")) return null;
|
||||
const backupUrls = Array.isArray(seg.backup_url)
|
||||
? seg.backup_url.filter(u => typeof u === "string" && u.startsWith("http"))
|
||||
: [];
|
||||
return { url: seg.url, backupUrls };
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the https page URL for a video (optionally a specific part).
|
||||
* @param {string} bvid
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
configureBilibiliProxy,
|
||||
ensureBilibiliProxy,
|
||||
} from "./BilibiliProxy.mjs";
|
||||
import { fetchBilibiliPlayUrl, pickBestAudioStream, setBilibiliCookie } from "./BilibiliResolver.mjs";
|
||||
import { fetchBilibiliPlayUrl, pickBestAudioStream, pickProgressiveStream, setBilibiliCookie } from "./BilibiliResolver.mjs";
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
|
||||
/**
|
||||
@@ -42,8 +42,11 @@ export function configureBilibili(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.
|
||||
* re-queried, the best DASH audio stream picked, and the CDN URL wrapped in
|
||||
* a signed proxy URL the audio node can fetch with the right Referer/UA.
|
||||
* When Bilibili returns no DASH audio (anonymous playback — DASH requires
|
||||
* a login cookie), a single-segment progressive mp4 is used instead, asking
|
||||
* the anonymous-friendly html5 playurl variant as a second chance.
|
||||
* @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.
|
||||
@@ -60,17 +63,28 @@ export async function getBilibiliStreamUrl(track) {
|
||||
|
||||
const data = await fetchBilibiliPlayUrl(meta);
|
||||
const best = pickBestAudioStream(data);
|
||||
if (!best?.baseUrl) {
|
||||
throw new Error("Bilibili returned no playable audio stream for this video");
|
||||
if (best?.baseUrl) {
|
||||
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 : [] };
|
||||
}
|
||||
|
||||
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 : [] };
|
||||
let progressive = pickProgressiveStream(data);
|
||||
if (!progressive) {
|
||||
const html5 = await fetchBilibiliPlayUrl(meta, { html5: true });
|
||||
progressive = pickProgressiveStream(html5);
|
||||
}
|
||||
if (progressive) {
|
||||
const url = await buildSignedProxyUrl(progressive.url);
|
||||
logger.player("[Bilibili] no DASH audio — using progressive mp4 (a browser cookie in config.json -> bilibili.cookie unlocks full-quality audio): " + url.substring(0, 60) + "...");
|
||||
return { url, backupUrls: progressive.backupUrls };
|
||||
}
|
||||
|
||||
throw new Error("Bilibili returned no playable audio stream for this video (anonymous playback is limited — a browser cookie in config.json -> bilibili.cookie unlocks full-quality audio)");
|
||||
}
|
||||
|
||||
export { isBilibiliUrl, parseBilibiliVideoRef, resolveBilibiliVideo } from "./BilibiliResolver.mjs";
|
||||
export { setBilibiliCookie, BILIBILI_UA, BILIBILI_REFERER } from "./BilibiliResolver.mjs";
|
||||
export { setBilibiliCookie, resetBilibiliFingerprint, BILIBILI_UA, BILIBILI_REFERER } from "./BilibiliResolver.mjs";
|
||||
export {
|
||||
bilibiliEnabled,
|
||||
bilibiliProxyInfo,
|
||||
|
||||
Reference in new issue
Block a user