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
e0994dfbc2
commit
771b005d7e
12 files changed
+647
-221
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.
|
- **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).
|
- **Volume** is applied client-side by the LiveKit connection (1–200).
|
||||||
- Radio metadata (StreamTitle) is read with **ffprobe** (`ffprobe-static`).
|
- 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. 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.
|
- **Bilibili playback (fully anonymous — no cookies)** — `%play https://www.bilibili.com/video/BV…` (b23.tv short links and `?p=` parts included) resolves the video through Bilibili's web API 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. Requests use Bilibili's WBI-signed endpoints (derived anonymously from the nav payload), which survive the HTTP 412 risk-control blocks that reject plain unsigned API calls on many hosting IPs; on any WBI failure the bot automatically retries through the legacy unsigned endpoints. Playurl calls carry the anonymous `try_look=1` flag and prefer the best DASH audio stream (~130–170 kbps AAC) — real DASH audio works without login — falling back to the html5 progressive mp4 for videos without DASH audio, and multi-segment progressive streams are served back-to-back through the proxy's concatenating mode with Range/seek support. 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. 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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+6
-10
@@ -6,8 +6,7 @@
|
|||||||
"Comment": "REST client options. 'timeout' is ms before a request to api.fluxer.app is aborted (default: 15000). Raise if you see DOMException AbortError in logs.",
|
"Comment": "REST client options. 'timeout' is ms before a request to api.fluxer.app is aborted (default: 15000). Raise if you see DOMException AbortError in logs.",
|
||||||
"timeout": 30000,
|
"timeout": 30000,
|
||||||
"retries": 3
|
"retries": 3
|
||||||
},
|
}
|
||||||
"Comment": "Client options passed to @fluxerjs/core 3.0. NOTE: cache limits live here. The built-in defaults are bounded (guilds 2000, channels 5000, users 10000, members 5000, messages 20). Do NOT set cache values to false \u2014 in 3.0 `false` means UNBOUNDED, not disabled, and will OOM the bot on large guild counts. To override, e.g. \"cache\": { \"users\": 20000 }."
|
|
||||||
},
|
},
|
||||||
"prefix": "your desired prefix (such as %)",
|
"prefix": "your desired prefix (such as %)",
|
||||||
"presenceInterval": null,
|
"presenceInterval": null,
|
||||||
@@ -24,7 +23,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"text": "Ping for Prefix",
|
"text": "Ping for Prefix",
|
||||||
"emoji_name": "\ud83c\udfa7",
|
"emoji_name": "Remix",
|
||||||
"activity": {
|
"activity": {
|
||||||
"name": "music",
|
"name": "music",
|
||||||
"type": 2
|
"type": 2
|
||||||
@@ -32,7 +31,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"text": "Ping for Prefix | By RedTech & NoLogicAlan",
|
"text": "Ping for Prefix | By RedTech & NoLogicAlan",
|
||||||
"emoji_name": "\ud83c\udfb6",
|
"emoji_name": "Remix",
|
||||||
"activity": {
|
"activity": {
|
||||||
"name": "RedTech & NoLogicAlan",
|
"name": "RedTech & NoLogicAlan",
|
||||||
"type": 2
|
"type": 2
|
||||||
@@ -51,14 +50,13 @@
|
|||||||
"bind": "127.0.0.1",
|
"bind": "127.0.0.1",
|
||||||
"port": 0,
|
"port": 0,
|
||||||
"advertiseHost": null,
|
"advertiseHost": null,
|
||||||
"cookie": null,
|
"Comment": "Bilibili video playback (%play https://www.bilibili.com/video/BV... , b23.tv short links and ?p= parts included) — fully anonymous, no cookies needed. The bot talks to Bilibili's WBI-signed web API (survives the HTTP 412 risk-control blocks that hit plain API calls on many hosting IPs), prefers anonymous DASH audio (~130-170 kbps) and falls back to the html5 progressive mp4 for videos without DASH audio. 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. buvid3/buvid4/b_nut device cookies are generated and managed automatically."
|
||||||
"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": {
|
"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:",
|
"message": "If you have radio stations you'd like to connect, add them to the array below. Radio stations must be rendered like following:",
|
||||||
"station": {
|
"station": {
|
||||||
"name": "zamrock",
|
"name": "zamrock",
|
||||||
"detailedName": "\u1614\u15e9\u15f0\u1614\u15e9\u15f0\u15b4O\u15b4\u14aaI\u15b4E",
|
"detailedName": "ZamRock Radio",
|
||||||
"thumbnail": "https://zamrock.net/wp-content/uploads/2024/06/Zamrock_rd_logo_0004-1.gif",
|
"thumbnail": "https://zamrock.net/wp-content/uploads/2024/06/Zamrock_rd_logo_0004-1.gif",
|
||||||
"url": "url to stream from; this will be kept private",
|
"url": "url to stream from; this will be kept private",
|
||||||
"description": "Genre: Zamrock, provided by [Zamrock.net](https://zamrock.net/)",
|
"description": "Genre: Zamrock, provided by [Zamrock.net](https://zamrock.net/)",
|
||||||
@@ -87,8 +85,7 @@
|
|||||||
"enabled": false,
|
"enabled": false,
|
||||||
"redis": {
|
"redis": {
|
||||||
"url": "redis://127.0.0.1:6379"
|
"url": "redis://127.0.0.1:6379"
|
||||||
},
|
}
|
||||||
"Comment": "Optional dashboard backend. When enabled, the bot speaks Redis RPC (request/response/info channels) with an external web frontend. Login codes are verified (bcrypt) from the MySQL login_codes table. Keep Redis network-isolated \u2014 the RPC channel has no shared secret."
|
|
||||||
},
|
},
|
||||||
"lastfm": {
|
"lastfm": {
|
||||||
"Comment": "Last.fm integration: auto-scrobble songs, play loved/top/recent tracks. Register at https://www.last.fm/api/account/create",
|
"Comment": "Last.fm integration: auto-scrobble songs, play loved/top/recent tracks. Register at https://www.last.fm/api/account/create",
|
||||||
@@ -144,7 +141,6 @@
|
|||||||
"playerSessionTimeout": 300000,
|
"playerSessionTimeout": 300000,
|
||||||
"intentionalLeaveTTL": 8000
|
"intentionalLeaveTTL": 8000
|
||||||
},
|
},
|
||||||
"sharding-Comment": "Optional process-level sharding (@fluxerjs/sharding 3.0, beta). Only read by 'node shard.mjs' / 'npm run shard' \u2014 plain 'npm start' ignores this block entirely. totalShards: total gateway shards (use an explicit number, never 'auto'); shardsPerProcess: how many shards each child process runs; respawn: restart dead children; spawnTimeout: ms to wait for a child's ready IPC; spawnDelay: ms between successive spawns. The FLUXER_TOTAL_SHARDS / FLUXER_SHARDS_PER_PROCESS env vars override the first two (handy for Docker). Sharding only matters at ~2500+ guilds; leave at defaults otherwise. Caveats: DMs only reach shard 0, and the dashboard is single-process-first.",
|
|
||||||
"sharding": {
|
"sharding": {
|
||||||
"totalShards": 1,
|
"totalShards": 1,
|
||||||
"shardsPerProcess": 1,
|
"shardsPerProcess": 1,
|
||||||
|
|||||||
@@ -120,7 +120,6 @@ class Remix {
|
|||||||
bind: config.bilibili?.bind ?? "127.0.0.1",
|
bind: config.bilibili?.bind ?? "127.0.0.1",
|
||||||
port: config.bilibili?.port ?? 0,
|
port: config.bilibili?.port ?? 0,
|
||||||
advertiseHost: config.bilibili?.advertiseHost ?? null,
|
advertiseHost: config.bilibili?.advertiseHost ?? null,
|
||||||
cookie: config.bilibili?.cookie ?? null,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%");
|
this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%");
|
||||||
|
|||||||
@@ -1,13 +1,21 @@
|
|||||||
/**
|
/**
|
||||||
* @module src/music/bilibili/BilibiliProxy
|
* @module src/music/bilibili/BilibiliProxy
|
||||||
* @description A tiny localhost HTTP proxy that lets the NodeLink/Lavalink
|
* @description A tiny localhost HTTP proxy that lets the NodeLink/Lavalink
|
||||||
* node fetch Bilibili CDN audio. Bilibili's DASH audio URLs (m4s) only
|
* node fetch Bilibili CDN audio. Bilibili's stream URLs (DASH m4s and
|
||||||
* respond to requests carrying a bilibili Referer and a browser User-Agent —
|
* progressive mp4/flv alike) only respond to requests carrying a bilibili
|
||||||
* headers an audio node cannot attach — so the bot signs the CDN URL with a
|
* Referer and a browser User-Agent — headers an audio node cannot attach —
|
||||||
* per-process HMAC key and hands the node
|
* so the bot signs the CDN URL with a per-process HMAC key and hands the
|
||||||
* `http://<host>:<port>/s?u=<cdn-url>&e=<expiry>&x=<hmac>` instead. The
|
* node `http://<host>:<port>/s?u=<cdn-url>&e=<expiry>&x=<hmac>` instead.
|
||||||
* proxy validates the signature, then streams the CDN response (including
|
*
|
||||||
* Range requests, which give seek support) with the right headers attached.
|
* Two serving modes:
|
||||||
|
* - `/s` — a single CDN URL: the proxy validates the signature, then
|
||||||
|
* streams the CDN response (including Range requests, which give seek
|
||||||
|
* support) with the right headers attached.
|
||||||
|
* - `/l` — a list of progressive segments: some playurl responses return
|
||||||
|
* the audio split over several durl segments; the proxy streams them
|
||||||
|
* back-to-back as one continuous body. Range requests are mapped across
|
||||||
|
* the concatenation using the segment sizes from the playurl payload,
|
||||||
|
* so seeking works in this mode too.
|
||||||
*
|
*
|
||||||
* The server starts lazily on the first Bilibili play and is unref'd, so it
|
* 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
|
* never delays startup or shutdown. Only URLs signed by this very process
|
||||||
@@ -16,7 +24,7 @@
|
|||||||
|
|
||||||
import http from "node:http";
|
import http from "node:http";
|
||||||
import crypto from "node:crypto";
|
import crypto from "node:crypto";
|
||||||
import { Readable } from "node:stream";
|
import { Readable, Transform } from "node:stream";
|
||||||
import { logger } from "../../core/Logger.mjs";
|
import { logger } from "../../core/Logger.mjs";
|
||||||
import { buildBilibiliCdnHeaders } from "./BilibiliResolver.mjs";
|
import { buildBilibiliCdnHeaders } from "./BilibiliResolver.mjs";
|
||||||
|
|
||||||
@@ -24,6 +32,8 @@ import { buildBilibiliCdnHeaders } from "./BilibiliResolver.mjs";
|
|||||||
const PROXY_TTL_MS = 6 * 60 * 60 * 1000;
|
const PROXY_TTL_MS = 6 * 60 * 60 * 1000;
|
||||||
/** @type {number} @description Timeout (ms) waiting for the CDN response headers. */
|
/** @type {number} @description Timeout (ms) waiting for the CDN response headers. */
|
||||||
const CDN_CONNECT_TIMEOUT_MS = 20_000;
|
const CDN_CONNECT_TIMEOUT_MS = 20_000;
|
||||||
|
/** @type {number} @description Maximum number of segments served through one list-mode URL. */
|
||||||
|
const MAX_SEGMENTS = 64;
|
||||||
|
|
||||||
/** @type {object} @description Effective proxy configuration (merged from config.json -> bilibili). */
|
/** @type {object} @description Effective proxy configuration (merged from config.json -> bilibili). */
|
||||||
const _cfg = {
|
const _cfg = {
|
||||||
@@ -144,7 +154,7 @@ export function resetBilibiliProxy() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HMAC-SHA256 signature binding a CDN URL to its expiry epoch.
|
* HMAC-SHA256 signature binding a payload to its expiry epoch.
|
||||||
* @param {string} target
|
* @param {string} target
|
||||||
* @param {number} expires
|
* @param {number} expires
|
||||||
* @returns {string}
|
* @returns {string}
|
||||||
@@ -168,13 +178,14 @@ function verifySignature(target, expires, sig) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sign a Bilibili CDN URL into a proxy URL the audio node can fetch. Starts
|
* Sign a single Bilibili CDN URL into a proxy URL the audio node can fetch.
|
||||||
* the proxy on first use. The HMAC is computed over the base64url-encoded
|
* Starts the proxy on first use. The HMAC is computed over the
|
||||||
* target exactly as it travels in the `u` query parameter, so verification
|
* base64url-encoded target exactly as it travels in the `u` query
|
||||||
* on the serving side never has to guess the encoding.
|
* parameter, so verification on the serving side never has to guess the
|
||||||
* @param {string} targetUrl - The raw CDN (m4s) URL from the playurl API.
|
* encoding.
|
||||||
|
* @param {string} targetUrl - The raw CDN (m4s / mp4) URL from the playurl API.
|
||||||
* @param {number} [ttlMs=PROXY_TTL_MS] - Signature lifetime.
|
* @param {number} [ttlMs=PROXY_TTL_MS] - Signature lifetime.
|
||||||
* @returns {Promise<string>} The signed proxy URL.
|
* @returns {Promise<string>} The signed proxy URL (`/s` mode).
|
||||||
*/
|
*/
|
||||||
export async function buildSignedProxyUrl(targetUrl, ttlMs = PROXY_TTL_MS) {
|
export async function buildSignedProxyUrl(targetUrl, ttlMs = PROXY_TTL_MS) {
|
||||||
const { port, host } = await ensureBilibiliProxy();
|
const { port, host } = await ensureBilibiliProxy();
|
||||||
@@ -185,9 +196,158 @@ export async function buildSignedProxyUrl(targetUrl, ttlMs = PROXY_TTL_MS) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Serve one proxy request: verify the signature, fetch the CDN URL with the
|
* Sign a multi-segment progressive stream into a concatenating proxy URL.
|
||||||
* Referer/UA headers Bilibili requires, and pipe the response through
|
* The payload carries each segment's CDN URL and byte size (plus up to four
|
||||||
* (status, content-type/length/range and Range semantics included).
|
* backup URLs); the `/l` handler streams the segments back-to-back and maps
|
||||||
|
* Range requests across the concatenation.
|
||||||
|
* @param {Array<{url: string, size: number, backupUrls?: Array<string>}>} segments
|
||||||
|
* @param {number} [ttlMs=PROXY_TTL_MS] - Signature lifetime.
|
||||||
|
* @returns {Promise<string>} The signed proxy URL (`/l` mode).
|
||||||
|
*/
|
||||||
|
export async function buildSignedListProxyUrl(segments, ttlMs = PROXY_TTL_MS) {
|
||||||
|
const { port, host } = await ensureBilibiliProxy();
|
||||||
|
const payload = JSON.stringify(
|
||||||
|
(Array.isArray(segments) ? segments : []).slice(0, MAX_SEGMENTS).map(s => ({
|
||||||
|
u: String(s?.url ?? ""),
|
||||||
|
s: Math.max(0, Math.floor(Number(s?.size) || 0)),
|
||||||
|
b: Array.isArray(s?.backupUrls)
|
||||||
|
? s.backupUrls.filter(u => typeof u === "string" && u.startsWith("http")).slice(0, 4)
|
||||||
|
: [],
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
const u = Buffer.from(payload, "utf8").toString("base64url");
|
||||||
|
const expires = Date.now() + ttlMs;
|
||||||
|
const x = signTarget(u, expires);
|
||||||
|
return "http://" + host + ":" + port + "/l?u=" + u + "&e=" + expires + "&x=" + x;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify a proxy request's signature and return its decoded payload.
|
||||||
|
* @param {URL} u - The parsed request URL.
|
||||||
|
* @returns {string} The base64-decoded `u` payload.
|
||||||
|
* @returns {null} when the signature/expiry check fails (response already sent).
|
||||||
|
*/
|
||||||
|
function checkSignature(u, res) {
|
||||||
|
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 null;
|
||||||
|
}
|
||||||
|
return uParam;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a `Range: bytes=a-b` header against a known total length.
|
||||||
|
* @param {string} header
|
||||||
|
* @param {number} total
|
||||||
|
* @returns {{start: number, end: number}|"invalid"|null} "invalid" means the
|
||||||
|
* header is syntactically valid but unsatisfiable (416); null means the
|
||||||
|
* header is absent or unparseable (serve 200 from byte 0).
|
||||||
|
*/
|
||||||
|
function parseByteRange(header, total) {
|
||||||
|
const m = /^bytes\s*=\s*(\d*)\s*-\s*(\d*)\s*$/.exec(String(header || ""));
|
||||||
|
if (!m) return null;
|
||||||
|
const [, a, b] = m;
|
||||||
|
if (a === "" && b === "") return null;
|
||||||
|
if (a === "") {
|
||||||
|
// suffix range: last N bytes
|
||||||
|
const n = Math.min(parseInt(b, 10), total);
|
||||||
|
return n <= 0 ? "invalid" : { start: total - n, end: total - 1 };
|
||||||
|
}
|
||||||
|
const start = parseInt(a, 10);
|
||||||
|
if (start >= total) return "invalid";
|
||||||
|
let end = b === "" ? total - 1 : Math.min(parseInt(b, 10), total - 1);
|
||||||
|
if (end < start) end = start;
|
||||||
|
return { start, end };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch one upstream (a segment URL, honoring mapped sub-ranges), trying
|
||||||
|
* backup URLs on connect failure.
|
||||||
|
* @param {{u: string, s: number, b: Array<string>}} seg
|
||||||
|
* @param {object} forwardHeaders - CDN headers (Referer/UA/cookie).
|
||||||
|
* @param {string|null} range - Range header for this segment or null.
|
||||||
|
* @param {AbortSignal} signal
|
||||||
|
* @returns {Promise<Response>}
|
||||||
|
* @throws {Error} when every candidate URL fails.
|
||||||
|
*/
|
||||||
|
async function fetchSegment(seg, forwardHeaders, range, signal) {
|
||||||
|
const candidates = [seg.u, ...seg.b];
|
||||||
|
let lastErr = null;
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const headers = { ...forwardHeaders };
|
||||||
|
if (range) headers.Range = range;
|
||||||
|
try {
|
||||||
|
return await fetch(candidate, { headers, redirect: "follow", signal });
|
||||||
|
} catch (e) {
|
||||||
|
lastErr = e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error("CDN fetch failed: " + (lastErr?.cause?.message || lastErr?.message || String(lastErr)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stream one upstream body into the response without ending it (list mode:
|
||||||
|
* further segments follow). Resolves when the source is exhausted or the
|
||||||
|
* byte cap is reached — whichever comes first. The cap guarantees the
|
||||||
|
* concatenation matches the declared segment sizes even when an upstream
|
||||||
|
* over-delivers (e.g. a CDN that ignores a Range request and answers with
|
||||||
|
* the full body): extra bytes are swallowed and the upstream is destroyed
|
||||||
|
* early to save bandwidth.
|
||||||
|
* @param {Response} upstream
|
||||||
|
* @param {http.ServerResponse} res
|
||||||
|
* @param {number} maxBytes - Exact number of bytes to deliver (< 0 = all).
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
function pipeSegmentBody(upstream, res, maxBytes) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (!upstream.body) { resolve(); return; }
|
||||||
|
const source = Readable.fromWeb(upstream.body);
|
||||||
|
let remaining = maxBytes >= 0 ? maxBytes : Number.POSITIVE_INFINITY;
|
||||||
|
let capped = false;
|
||||||
|
let settled = false;
|
||||||
|
const finish = (err) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
if (err && !capped) reject(err);
|
||||||
|
else resolve();
|
||||||
|
};
|
||||||
|
const gate = new Transform({
|
||||||
|
transform(chunk, _enc, cb) {
|
||||||
|
if (remaining <= 0) {
|
||||||
|
capped = true;
|
||||||
|
try { source.destroy(); } catch (_) {}
|
||||||
|
cb();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (chunk.length > remaining) {
|
||||||
|
capped = true;
|
||||||
|
const slice = chunk.subarray(0, remaining);
|
||||||
|
remaining = 0;
|
||||||
|
try { source.destroy(); } catch (_) {}
|
||||||
|
cb(null, slice);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
remaining -= chunk.length;
|
||||||
|
cb(null, chunk);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
gate.once("error", (e) => finish(e));
|
||||||
|
res.once("error", (e) => finish(e));
|
||||||
|
source.once("error", (e) => finish(e));
|
||||||
|
source.once("close", () => { if (capped) gate.end(); });
|
||||||
|
gate.once("end", () => finish());
|
||||||
|
source.pipe(gate);
|
||||||
|
gate.pipe(res, { end: false });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serve one proxy request: route to the single-URL (`/s`) or segment-list
|
||||||
|
* (`/l`) handler after signature verification.
|
||||||
* @param {http.IncomingMessage} req
|
* @param {http.IncomingMessage} req
|
||||||
* @param {http.ServerResponse} res
|
* @param {http.ServerResponse} res
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
@@ -205,23 +365,41 @@ async function handleProxyRequest(req, res) {
|
|||||||
res.end("bad request");
|
res.end("bad request");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (u.pathname !== "/s") {
|
if (u.pathname !== "/s" && u.pathname !== "/l") {
|
||||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
res.writeHead(404, { "Content-Type": "text/plain" });
|
||||||
res.end("not found");
|
res.end("not found");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uParam = u.searchParams.get("u");
|
const uParam = checkSignature(u, res);
|
||||||
const expires = Number(u.searchParams.get("e"));
|
if (uParam == null) return;
|
||||||
const sig = u.searchParams.get("x");
|
|
||||||
if (!uParam || !Number.isFinite(expires) || !sig || Date.now() >= expires || !verifySignature(uParam, expires, sig)) {
|
let payload;
|
||||||
res.writeHead(403, { "Content-Type": "text/plain" });
|
try { payload = Buffer.from(uParam, "base64url").toString("utf8"); } catch (_) {
|
||||||
res.end("forbidden");
|
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||||
|
res.end("bad target");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (u.pathname === "/s") {
|
||||||
|
await serveSingle(req, res, payload);
|
||||||
|
} else {
|
||||||
|
await serveSegmentList(req, res, payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `/s` mode: verify the target URL, fetch it 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
|
||||||
|
* @param {string} payload - The raw CDN URL.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async function serveSingle(req, res, payload) {
|
||||||
let targetUrl;
|
let targetUrl;
|
||||||
try { targetUrl = new URL(Buffer.from(uParam, "base64url").toString("utf8")); } catch (_) {
|
try { targetUrl = new URL(payload); } catch (_) {
|
||||||
res.writeHead(400, { "Content-Type": "text/plain" });
|
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||||
res.end("bad target");
|
res.end("bad target");
|
||||||
return;
|
return;
|
||||||
@@ -266,12 +444,8 @@ async function handleProxyRequest(req, res) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!upstream.body) {
|
|
||||||
res.end();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await new Promise((resolve, reject) => {
|
await new Promise((resolve, reject) => {
|
||||||
|
if (!upstream.body) { resolve(); return; }
|
||||||
const stream = Readable.fromWeb(upstream.body);
|
const stream = Readable.fromWeb(upstream.body);
|
||||||
stream.once("error", reject);
|
stream.once("error", reject);
|
||||||
res.once("error", reject);
|
res.once("error", reject);
|
||||||
@@ -280,3 +454,136 @@ async function handleProxyRequest(req, res) {
|
|||||||
res.once("finish", resolve);
|
res.once("finish", resolve);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `/l` mode: stream a list of progressive segments back-to-back as one
|
||||||
|
* continuous body. Range requests are mapped across the concatenation via
|
||||||
|
* the segment sizes; when any size is unknown, Range is ignored and the
|
||||||
|
* full stream is served (seeking then degrades to a full re-fetch, which
|
||||||
|
* still decodes correctly).
|
||||||
|
* @param {http.IncomingMessage} req
|
||||||
|
* @param {http.ServerResponse} res
|
||||||
|
* @param {string} payload - JSON array of {u, s, b} segments.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async function serveSegmentList(req, res, payload) {
|
||||||
|
let segs;
|
||||||
|
try {
|
||||||
|
segs = JSON.parse(payload);
|
||||||
|
} catch (_) {
|
||||||
|
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||||
|
res.end("bad target");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!Array.isArray(segs) || !segs.length || segs.length > MAX_SEGMENTS
|
||||||
|
|| !segs.every(s => typeof s?.u === "string" && /^https?:\/\//i.test(s.u) && Number.isFinite(s?.s))) {
|
||||||
|
res.writeHead(400, { "Content-Type": "text/plain" });
|
||||||
|
res.end("bad target list");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const knownSizes = segs.every(s => s.s > 0);
|
||||||
|
const offsets = [];
|
||||||
|
let total = 0;
|
||||||
|
for (const seg of segs) { offsets.push(total); total += seg.s; }
|
||||||
|
if (!knownSizes) total = -1;
|
||||||
|
|
||||||
|
let range = null;
|
||||||
|
if (knownSizes && req.headers.range) {
|
||||||
|
range = parseByteRange(req.headers.range, total);
|
||||||
|
if (range === "invalid") {
|
||||||
|
res.writeHead(416, { "Content-Range": "bytes */" + total });
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const forwardHeaders = await buildBilibiliCdnHeaders();
|
||||||
|
// One request-level abort controller: the client vanishing mid-list aborts
|
||||||
|
// the in-flight segment fetch; response lifecycle events never touch it.
|
||||||
|
const abort = new AbortController();
|
||||||
|
req.once("close", () => abort.abort());
|
||||||
|
|
||||||
|
if (req.method === "HEAD") {
|
||||||
|
const headers = { "Accept-Ranges": "bytes" };
|
||||||
|
if (total >= 0) headers["Content-Length"] = String(total);
|
||||||
|
res.writeHead(200, headers);
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open the first segment to learn the content-type before writing headers.
|
||||||
|
const start = range ? range.start : 0;
|
||||||
|
let firstIdx = 0;
|
||||||
|
if (range) {
|
||||||
|
while (firstIdx < segs.length - 1 && start >= offsets[firstIdx] + segs[firstIdx].s) firstIdx++;
|
||||||
|
}
|
||||||
|
|
||||||
|
let plannedLength = -1;
|
||||||
|
if (range) {
|
||||||
|
plannedLength = range.end - range.start + 1;
|
||||||
|
} else if (total >= 0) {
|
||||||
|
plannedLength = total;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let i = firstIdx; i < segs.length; i++) {
|
||||||
|
if (range && offsets[i] > range.end) break;
|
||||||
|
|
||||||
|
const seg = segs[i];
|
||||||
|
let segRange = null;
|
||||||
|
if (range) {
|
||||||
|
const localStart = Math.max(0, range.start - offsets[i]);
|
||||||
|
const localEnd = Math.min(range.end, offsets[i] + seg.s - 1) - offsets[i];
|
||||||
|
if (localEnd < localStart) continue;
|
||||||
|
segRange = "bytes=" + localStart + "-" + localEnd;
|
||||||
|
}
|
||||||
|
|
||||||
|
const timer = setTimeout(() => abort.abort(), CDN_CONNECT_TIMEOUT_MS);
|
||||||
|
let upstream;
|
||||||
|
try {
|
||||||
|
upstream = await fetchSegment(seg, forwardHeaders, segRange, abort.signal);
|
||||||
|
} catch (e) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
throw new Error("CDN fetch failed: " + (e?.cause?.message || e?.message || String(e)));
|
||||||
|
}
|
||||||
|
clearTimeout(timer);
|
||||||
|
|
||||||
|
if (!upstream.ok && upstream.status !== 206) {
|
||||||
|
try { upstream.body?.cancel?.(); } catch (_) {}
|
||||||
|
throw new Error("CDN returned HTTP " + upstream.status + " for segment " + (i + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i === firstIdx) {
|
||||||
|
const contentType = upstream.headers.get("content-type");
|
||||||
|
const headers = { "Accept-Ranges": "bytes" };
|
||||||
|
if (contentType) headers["Content-Type"] = contentType;
|
||||||
|
if (range) {
|
||||||
|
headers["Content-Range"] = "bytes " + range.start + "-" + range.end + "/" + total;
|
||||||
|
if (plannedLength >= 0) headers["Content-Length"] = String(plannedLength);
|
||||||
|
res.writeHead(206, headers);
|
||||||
|
} else {
|
||||||
|
if (plannedLength >= 0) headers["Content-Length"] = String(plannedLength);
|
||||||
|
res.writeHead(200, headers);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deliver exactly this segment's share: the requested sub-range when a
|
||||||
|
// Range was mapped, else the declared segment size (unknown -> all).
|
||||||
|
const cap = range
|
||||||
|
? (Number(segRange.split("-")[1]) - Number(segRange.split("-")[0]) + 1)
|
||||||
|
: (seg.s > 0 ? seg.s : -1);
|
||||||
|
try {
|
||||||
|
await pipeSegmentBody(upstream, res, cap);
|
||||||
|
} catch (_) {
|
||||||
|
try { res.destroy(); } catch (_) {}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (res.destroyed) return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.headersSent) {
|
||||||
|
// No segment was served (empty effective range) — send the empty 206.
|
||||||
|
res.writeHead(206, { "Content-Range": "bytes */" + total, "Content-Length": "0" });
|
||||||
|
}
|
||||||
|
res.end();
|
||||||
|
}
|
||||||
@@ -2,18 +2,25 @@
|
|||||||
* @module src/music/bilibili/BilibiliResolver
|
* @module src/music/bilibili/BilibiliResolver
|
||||||
* @description Bilibili video resolution: URL detection (BV/av ids, b23.tv /
|
* @description Bilibili video resolution: URL detection (BV/av ids, b23.tv /
|
||||||
* bili2233.cn short links, ?p= page selection), the public web API client
|
* bili2233.cn short links, ?p= page selection), the public web API client
|
||||||
* with a self-managed device fingerprint, DASH audio-stream selection (with
|
* for fully anonymous playback (no login cookies, ever), best-audio-stream
|
||||||
* a progressive mp4 fallback for anonymous playback), and internal track
|
* selection and internal track building.
|
||||||
* building.
|
|
||||||
*
|
*
|
||||||
* Bilibili's risk control (HTTP 412 / code -412) blocks browser-style
|
* Anonymous access strategy (empirically verified against the live API):
|
||||||
* requests that lack a device fingerprint, so the module bootstraps one per
|
* - Every request carries a self-managed device fingerprint: the finger/spi
|
||||||
* process: the finger/spi endpoint mints a fresh buvid3/buvid4 pair and a
|
* endpoint mints a fresh buvid3/buvid4 pair and a homepage GET contributes
|
||||||
* homepage GET contributes b_nut. A user cookie from config (SESSDATA etc.)
|
* b_nut. Risk-control blocks (HTTP 412 / code -412) trigger one shared
|
||||||
* is sanitized — placeholder-looking or malformed values are dropped with a
|
* fingerprint refresh and retry before giving up on an endpoint.
|
||||||
* log line instead of poisoning the request trust level — and layered on top
|
* - Requests prefer the WBI-signed endpoints (`/x/web-interface/wbi/view`,
|
||||||
* of the fingerprint, and every fingerprint-blocked request refreshes the
|
* `/x/player/wbi/playurl`): the mixin key is derived from the anonymous
|
||||||
* fingerprint and retries once before surfacing the config-cookie hint.
|
* nav payload's img/sub keys, and signed calls survive IP blocks that
|
||||||
|
* reject the legacy unsigned endpoints outright.
|
||||||
|
* - Every API failure on the WBI path falls back to the legacy unsigned
|
||||||
|
* endpoint once, so a bad key never breaks playback.
|
||||||
|
* - playurl asks for the DASH manifest (fnval=16) plus try_look=1 — anonymous
|
||||||
|
* callers receive real DASH audio streams (typically up to ~170 kbps AAC),
|
||||||
|
* a big step up from the old progressive-only fallback. When a video has no
|
||||||
|
* DASH audio, the html5 platform variant (platform=html5&high_quality=1)
|
||||||
|
* yields a progressive mp4 instead.
|
||||||
*
|
*
|
||||||
* The audio URLs Bilibili hands out only respond to requests carrying a
|
* 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
|
* bilibili Referer and a browser User-Agent, so the raw CDN URL is never
|
||||||
@@ -21,6 +28,7 @@
|
|||||||
* local proxy in {@link module:src/music/bilibili/BilibiliProxy}.
|
* local proxy in {@link module:src/music/bilibili/BilibiliProxy}.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import crypto from "node:crypto";
|
||||||
import { Utils } from "../../utils/Utils.mjs";
|
import { Utils } from "../../utils/Utils.mjs";
|
||||||
import { logger } from "../../core/Logger.mjs";
|
import { logger } from "../../core/Logger.mjs";
|
||||||
|
|
||||||
@@ -31,10 +39,16 @@ export const BILIBILI_REFERER = "https://www.bilibili.com/";
|
|||||||
/** @type {string} @description Page origin paired with the Referer on browser-style requests. */
|
/** @type {string} @description Page origin paired with the Referer on browser-style requests. */
|
||||||
const BILIBILI_ORIGIN = "https://www.bilibili.com";
|
const BILIBILI_ORIGIN = "https://www.bilibili.com";
|
||||||
|
|
||||||
/** @type {string} @description Video metadata endpoint (bvid= or aid=). */
|
/** @type {string} @description Anonymous nav endpoint carrying the WBI img/sub keys. */
|
||||||
|
const API_NAV = "https://api.bilibili.com/x/web-interface/nav";
|
||||||
|
/** @type {string} @description Video metadata endpoint — legacy (unsigned). */
|
||||||
const API_VIEW = "https://api.bilibili.com/x/web-interface/view";
|
const API_VIEW = "https://api.bilibili.com/x/web-interface/view";
|
||||||
/** @type {string} @description Playback URL endpoint (DASH manifest when fnval=16). */
|
/** @type {string} @description Video metadata endpoint — WBI-signed (preferred). */
|
||||||
|
const API_VIEW_WBI = "https://api.bilibili.com/x/web-interface/wbi/view";
|
||||||
|
/** @type {string} @description Playback URL endpoint — legacy (unsigned). */
|
||||||
const API_PLAYURL = "https://api.bilibili.com/x/player/playurl";
|
const API_PLAYURL = "https://api.bilibili.com/x/player/playurl";
|
||||||
|
/** @type {string} @description Playback URL endpoint — WBI-signed (preferred). */
|
||||||
|
const API_PLAYURL_WBI = "https://api.bilibili.com/x/player/wbi/playurl";
|
||||||
/** @type {string} @description Device-fingerprint endpoint returning a fresh buvid3/buvid4 pair. */
|
/** @type {string} @description Device-fingerprint endpoint returning a fresh buvid3/buvid4 pair. */
|
||||||
const API_FINGER_SPI = "https://api.bilibili.com/x/frontend/finger/spi";
|
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. */
|
/** @type {string} @description Homepage used to pick up buvid3/b_nut/buvid4 Set-Cookie values. */
|
||||||
@@ -57,6 +71,8 @@ const SHORTLINK_TIMEOUT_MS = 10_000;
|
|||||||
const BOOTSTRAP_TIMEOUT_MS = 10_000;
|
const BOOTSTRAP_TIMEOUT_MS = 10_000;
|
||||||
/** @type {number} @description Cool-down (ms) before retrying a risk-control-blocked request. */
|
/** @type {number} @description Cool-down (ms) before retrying a risk-control-blocked request. */
|
||||||
const BLOCK_RETRY_DELAY_MS = 1_200;
|
const BLOCK_RETRY_DELAY_MS = 1_200;
|
||||||
|
/** @type {number} @description Cool-down (ms) before retrying after a WBI signature rejection. */
|
||||||
|
const WBI_RETRY_DELAY_MS = 250;
|
||||||
/** @type {number} @description Minimum spacing (ms) between fingerprint refreshes. */
|
/** @type {number} @description Minimum spacing (ms) between fingerprint refreshes. */
|
||||||
const REFRESH_MIN_INTERVAL_MS = 2_500;
|
const REFRESH_MIN_INTERVAL_MS = 2_500;
|
||||||
/** @type {number} @description Maximum number of multi-page parts queued from one video. */
|
/** @type {number} @description Maximum number of multi-page parts queued from one video. */
|
||||||
@@ -104,17 +120,27 @@ const CDN_HEADERS = {
|
|||||||
/** @type {string} @description Error hint shown when Bilibili risk control blocks the server IP. */
|
/** @type {string} @description Error hint shown when Bilibili risk control blocks the server IP. */
|
||||||
const BLOCKED_HINT =
|
const BLOCKED_HINT =
|
||||||
"Bilibili blocked this server's requests (risk control, HTTP 412). " +
|
"Bilibili blocked this server's requests (risk control, HTTP 412). " +
|
||||||
"The bot manages its device fingerprint automatically, so a persistent block means Bilibili flagged " +
|
"The bot manages its device fingerprint and WBI request signatures automatically, so a persistent block means " +
|
||||||
"this hosting IP: copy your browser's cookie header into config.json -> bilibili.cookie " +
|
"Bilibili flagged this hosting IP: a different egress IP (VPN or proxy) may be required. " +
|
||||||
"(SESSDATA is the part that matters — buvid3/buvid4/b_nut are auto-generated, placeholder values are ignored) " +
|
"This bot plays Bilibili fully anonymously, so there is no cookie workaround.";
|
||||||
"and restart the bot. Shared-hosting IPs may stay blocked; a different egress IP may be required.";
|
|
||||||
|
|
||||||
/** @type {RegExp} @description Values that are clearly config-example placeholders rather than real cookies. */
|
/**
|
||||||
const PLACEHOLDER_RE =
|
* @type {Array<number>} @description Permutation used to derive the WBI mixin
|
||||||
/your[_\- ]|_here\b|\bplaceholder\b|\bexample\b|\bsample\b|\bdummy\b|\bfake\b|change[_\-]?me|\bfixme\b|\btodo\b|\bxxx\b|^\.{2,}$|^<[^>]*>$|\{\{|\}\}/i;
|
* key from the nav payload's img+sub keys. Only the first 32 positions are
|
||||||
|
* ever read (the mixin key is the first 32 characters of the permuted
|
||||||
|
* string); these 32 entries are the empirically verified prefix of the
|
||||||
|
* published table.
|
||||||
|
*/
|
||||||
|
const MIXIN_TAB = [
|
||||||
|
46, 47, 18, 2, 53, 8, 23, 32, 15, 50,
|
||||||
|
10, 31, 58, 3, 45, 35, 27, 43, 5, 49,
|
||||||
|
33, 9, 42, 19, 29, 28, 14, 39, 12, 38,
|
||||||
|
41, 13,
|
||||||
|
];
|
||||||
|
|
||||||
|
/** @type {RegExp} @description Characters stripped from values before WBI signing (per the published algorithm). */
|
||||||
|
const WBI_FILTER_RE = /[!'()*]/g;
|
||||||
|
|
||||||
/** @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). */
|
/** @type {object|null} @description Auto-managed device fingerprint (buvid3/buvid4/b_nut). */
|
||||||
let _fingerprint = null;
|
let _fingerprint = null;
|
||||||
/** @type {Promise|null} @description Memoized bootstrap run (best effort, never rejects). */
|
/** @type {Promise|null} @description Memoized bootstrap run (best effort, never rejects). */
|
||||||
@@ -123,70 +149,25 @@ let _bootstrapPromise = null;
|
|||||||
let _refreshPromise = null;
|
let _refreshPromise = null;
|
||||||
/** @type {number} @description Timestamp (ms) of the last fingerprint refresh trigger. */
|
/** @type {number} @description Timestamp (ms) of the last fingerprint refresh trigger. */
|
||||||
let _refreshGate = 0;
|
let _refreshGate = 0;
|
||||||
|
/** @type {{mixinKey: string, imgKey: string, subKey: string}|null} @description Cached WBI signing keys. */
|
||||||
|
let _wbiKeys = null;
|
||||||
|
/** @type {Promise|null} @description Memoized WBI key load. */
|
||||||
|
let _wbiPromise = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whether a cookie value is plausible for its (known) name. Unknown cookie
|
* Whether a device-cookie value is plausible (used when harvesting
|
||||||
* names only need a sane length and no control characters; known Bilibili
|
* Set-Cookie values from the homepage bootstrap).
|
||||||
* 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} name
|
||||||
* @param {string} value
|
* @param {string} value
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
function plausibleCookieValue(name, value) {
|
function plausibleDeviceValue(name, value) {
|
||||||
if (value.length > 512 || /[\x00-\x1f\x7f]/.test(value)) return false;
|
if (value.length > 512 || /[\x00-\x1f\x7f]/.test(value)) return false;
|
||||||
switch (name) {
|
switch (name) {
|
||||||
case "buvid3": return /^[A-Za-z0-9-]{16,}$/.test(value);
|
case "buvid3": return /^[A-Za-z0-9-]{16,}$/.test(value);
|
||||||
case "b_nut": return /^[0-9]{9,11}$/.test(value);
|
case "b_nut": return /^[0-9]{9,11}$/.test(value);
|
||||||
case "buvid4": return /^[A-Za-z0-9-+=]{20,}$/.test(value);
|
case "buvid4": return /^[A-Za-z0-9-+=]{20,}$/.test(value);
|
||||||
case "SESSDATA": return /^[A-Za-z0-9,.*%_+-]{16,}$/.test(value);
|
default: return false;
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -236,9 +217,9 @@ function bootstrapFingerprint() {
|
|||||||
if (eq > 0) jar[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim();
|
if (eq > 0) jar[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim();
|
||||||
}
|
}
|
||||||
try { res.body?.cancel?.(); } catch (_) {}
|
try { res.body?.cancel?.(); } catch (_) {}
|
||||||
if (!fp.buvid3 && plausibleCookieValue("buvid3", jar.buvid3 ?? "")) fp.buvid3 = jar.buvid3;
|
if (!fp.buvid3 && plausibleDeviceValue("buvid3", jar.buvid3 ?? "")) fp.buvid3 = jar.buvid3;
|
||||||
if (plausibleCookieValue("b_nut", jar.b_nut ?? "")) fp.b_nut = jar.b_nut;
|
if (!fp.b_nut && plausibleDeviceValue("b_nut", jar.b_nut ?? "")) fp.b_nut = jar.b_nut;
|
||||||
if (!fp.buvid4 && plausibleCookieValue("buvid4", jar.buvid4 ?? "")) fp.buvid4 = jar.buvid4;
|
if (!fp.buvid4 && plausibleDeviceValue("buvid4", jar.buvid4 ?? "")) fp.buvid4 = jar.buvid4;
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
return null;
|
return null;
|
||||||
})(),
|
})(),
|
||||||
@@ -253,14 +234,16 @@ function bootstrapFingerprint() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear the memoized device fingerprint and pending refresh state so the
|
* Clear the memoized device fingerprint, WBI keys and pending refresh state
|
||||||
* next request bootstraps a fresh one (used by tests to isolate scenarios).
|
* so the next request bootstraps everything fresh (used by tests).
|
||||||
*/
|
*/
|
||||||
export function resetBilibiliFingerprint() {
|
export function resetBilibiliFingerprint() {
|
||||||
_bootstrapPromise = null;
|
_bootstrapPromise = null;
|
||||||
_fingerprint = null;
|
_fingerprint = null;
|
||||||
_refreshPromise = null;
|
_refreshPromise = null;
|
||||||
_refreshGate = 0;
|
_refreshGate = 0;
|
||||||
|
_wbiKeys = null;
|
||||||
|
_wbiPromise = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -275,9 +258,9 @@ function refreshFingerprint() {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Shared cool-down + refresh for risk-control-blocked requests: one short
|
* Shared cool-down + refresh for risk-control-blocked requests: one short
|
||||||
* pause, then a single fingerprint refresh no matter how many requests were
|
* pause, then a single fingerprint refresh (and WBI key invalidation) no
|
||||||
* blocked at the same time (the refresh is rate-limited so parallel queue
|
* matter how many requests were blocked at the same time — the refresh is
|
||||||
* loads cannot hammer the fingerprint endpoint).
|
* rate-limited so parallel queue loads cannot hammer the endpoints.
|
||||||
* @returns {Promise<null>}
|
* @returns {Promise<null>}
|
||||||
*/
|
*/
|
||||||
function refreshAfterBlock() {
|
function refreshAfterBlock() {
|
||||||
@@ -287,6 +270,8 @@ function refreshAfterBlock() {
|
|||||||
_refreshPromise = (async () => {
|
_refreshPromise = (async () => {
|
||||||
await new Promise((r) => setTimeout(r, BLOCK_RETRY_DELAY_MS));
|
await new Promise((r) => setTimeout(r, BLOCK_RETRY_DELAY_MS));
|
||||||
logger.warn("[Bilibili] risk control block (412) — refreshing device fingerprint and retrying once");
|
logger.warn("[Bilibili] risk control block (412) — refreshing device fingerprint and retrying once");
|
||||||
|
_wbiKeys = null;
|
||||||
|
_wbiPromise = null;
|
||||||
await refreshFingerprint();
|
await refreshFingerprint();
|
||||||
})();
|
})();
|
||||||
}
|
}
|
||||||
@@ -294,32 +279,22 @@ function refreshAfterBlock() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The cookie sent on Bilibili requests: sanitized config pairs first, then
|
* The device-fingerprint cookie sent on Bilibili requests (buvid3/b_nut/
|
||||||
* fingerprint fill-ins for any device cookies the config did not validly
|
* buvid4 only — no login cookies exist in this module by design).
|
||||||
* provide. Returns null when neither source has anything.
|
|
||||||
* @returns {string|null}
|
* @returns {string|null}
|
||||||
*/
|
*/
|
||||||
function effectiveCookie() {
|
function effectiveCookie() {
|
||||||
|
if (!_fingerprint) return null;
|
||||||
const parts = [];
|
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"]) {
|
for (const name of ["buvid3", "b_nut", "buvid4"]) {
|
||||||
if (!seen.has(name) && _fingerprint[name]) parts.push(name + "=" + _fingerprint[name]);
|
if (_fingerprint[name]) parts.push(name + "=" + _fingerprint[name]);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return parts.length ? parts.join("; ") : null;
|
return parts.length ? parts.join("; ") : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build the header set for Bilibili API requests: the browser-exact UA /
|
* Build the header set for Bilibili API requests: the browser-exact UA /
|
||||||
* Referer / Origin / Sec-Fetch set plus the effective cookie (config pairs
|
* Referer / Origin / Sec-Fetch set plus the device fingerprint cookie.
|
||||||
* layered over the auto-managed device fingerprint).
|
|
||||||
* @returns {Promise<object>}
|
* @returns {Promise<object>}
|
||||||
*/
|
*/
|
||||||
async function biliRequestHeaders() {
|
async function biliRequestHeaders() {
|
||||||
@@ -331,9 +306,7 @@ async function biliRequestHeaders() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build the header set the local proxy forwards to Bilibili CDN hosts. Same
|
* Build the header set the local proxy forwards to Bilibili CDN hosts.
|
||||||
* trust rules as the API headers: the sanitized config cookie layered over
|
|
||||||
* the auto-managed device fingerprint.
|
|
||||||
* @returns {Promise<object>}
|
* @returns {Promise<object>}
|
||||||
*/
|
*/
|
||||||
export async function buildBilibiliCdnHeaders() {
|
export async function buildBilibiliCdnHeaders() {
|
||||||
@@ -344,6 +317,73 @@ export async function buildBilibiliCdnHeaders() {
|
|||||||
return headers;
|
return headers;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load the WBI signing keys: the anonymous nav endpoint reports code -101
|
||||||
|
* ("not logged in") but still carries data.wbi_img with the img/sub key
|
||||||
|
* pair, from which the mixin key is derived through the published
|
||||||
|
* permutation table. Keys are cached for the process lifetime and only
|
||||||
|
* invalidated reactively (signature rejections / risk-control blocks).
|
||||||
|
* @returns {Promise<{mixinKey: string, imgKey: string, subKey: string}>}
|
||||||
|
* @throws {Error} when nav is unreachable or carries no wbi_img payload.
|
||||||
|
*/
|
||||||
|
async function loadWbiKeys() {
|
||||||
|
if (_wbiKeys) return _wbiKeys;
|
||||||
|
if (_wbiPromise) return _wbiPromise;
|
||||||
|
_wbiPromise = (async () => {
|
||||||
|
const headers = await biliRequestHeaders();
|
||||||
|
const res = await fetch(API_NAV, {
|
||||||
|
headers,
|
||||||
|
redirect: "follow",
|
||||||
|
signal: AbortSignal.timeout(API_TIMEOUT_MS),
|
||||||
|
});
|
||||||
|
if (res.status !== 200) {
|
||||||
|
try { res.body?.cancel?.(); } catch (_) {}
|
||||||
|
throw new Error("WBI nav HTTP " + res.status);
|
||||||
|
}
|
||||||
|
const body = await res.json();
|
||||||
|
const img = body?.data?.wbi_img?.img_url;
|
||||||
|
const sub = body?.data?.wbi_img?.sub_url;
|
||||||
|
if (typeof img !== "string" || typeof sub !== "string" || !img || !sub) {
|
||||||
|
throw new Error("WBI nav payload has no wbi_img (code " + body?.code + ")");
|
||||||
|
}
|
||||||
|
const imgKey = new URL(img).pathname.split("/").pop().split(".")[0];
|
||||||
|
const subKey = new URL(sub).pathname.split("/").pop().split(".")[0];
|
||||||
|
const raw = imgKey + subKey;
|
||||||
|
if (raw.length < 32) throw new Error("WBI keys too short");
|
||||||
|
const mixinKey = MIXIN_TAB.map((i) => raw[i]).join("").slice(0, 32);
|
||||||
|
if (mixinKey.length !== 32) throw new Error("WBI mixin key derivation failed");
|
||||||
|
_wbiKeys = { mixinKey, imgKey, subKey };
|
||||||
|
logger.player("[Bilibili] WBI signing keys ready (anonymous)");
|
||||||
|
return _wbiKeys;
|
||||||
|
})().catch((e) => {
|
||||||
|
_wbiPromise = null;
|
||||||
|
throw e;
|
||||||
|
});
|
||||||
|
return _wbiPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sign API params for a WBI endpoint: values are sanitized, `wts` is added,
|
||||||
|
* pairs are sorted by key, and `w_rid` is the MD5 of the query string plus
|
||||||
|
* the mixin key — the published web-client algorithm.
|
||||||
|
* @param {object} params
|
||||||
|
* @returns {string} The signed query string (w_rid included).
|
||||||
|
*/
|
||||||
|
function signWbiParams(params) {
|
||||||
|
const keys = _wbiKeys;
|
||||||
|
if (!keys) throw new Error("WBI keys not loaded");
|
||||||
|
const merged = { ...params, wts: Math.floor(Date.now() / 1000) };
|
||||||
|
const clean = {};
|
||||||
|
for (const [k, v] of Object.entries(merged)) {
|
||||||
|
clean[k] = String(v).replace(WBI_FILTER_RE, "");
|
||||||
|
}
|
||||||
|
const qs = Object.keys(clean).sort()
|
||||||
|
.map((k) => encodeURIComponent(k) + "=" + encodeURIComponent(clean[k]))
|
||||||
|
.join("&");
|
||||||
|
const wRid = crypto.createHash("md5").update(qs + keys.mixinKey, "utf8").digest("hex");
|
||||||
|
return qs + "&w_rid=" + wRid;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Turn a Bilibili API error code into a user-readable message.
|
* Turn a Bilibili API error code into a user-readable message.
|
||||||
* @param {number} code
|
* @param {number} code
|
||||||
@@ -360,46 +400,111 @@ function describeApiError(code, message) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GET a Bilibili API endpoint and return its `data` payload, mapping HTTP
|
* One raw GET against api.bilibili.com.
|
||||||
* 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
|
* @param {string} url
|
||||||
* @returns {Promise<object>}
|
* @returns {Promise<{status: number, body: object|null}>}
|
||||||
* @throws {Error} with a user-readable message on network/HTTP/API errors.
|
* @throws {Error} on network failure.
|
||||||
*/
|
*/
|
||||||
async function biliJson(url) {
|
async function rawGet(url) {
|
||||||
for (let attempt = 0; ; attempt++) {
|
|
||||||
const headers = await biliRequestHeaders();
|
const headers = await biliRequestHeaders();
|
||||||
let res;
|
const res = await fetch(url, { headers, redirect: "follow", signal: AbortSignal.timeout(API_TIMEOUT_MS) });
|
||||||
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) {
|
if (res.status !== 200) {
|
||||||
try { res.body?.cancel?.(); } catch (_) {}
|
try { res.body?.cancel?.(); } catch (_) {}
|
||||||
throw new Error("Bilibili API HTTP " + res.status);
|
return { status: res.status, body: null };
|
||||||
}
|
}
|
||||||
let body;
|
let body;
|
||||||
try {
|
try {
|
||||||
body = await res.json();
|
body = await res.json();
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
throw new Error("Bilibili API returned invalid JSON");
|
return { status: -1, body: null };
|
||||||
}
|
}
|
||||||
if (body.code === -412) {
|
return { status: 200, body };
|
||||||
if (attempt === 0) { await refreshAfterBlock(); continue; }
|
|
||||||
throw new Error(BLOCKED_HINT);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read one JSON API response: HTTP 200 + body code 0 returns `data`.
|
||||||
|
* @param {{status: number, body: object|null}} r
|
||||||
|
* @returns {object} The `data` payload.
|
||||||
|
* @throws {Error} with a user-readable message for HTTP/transport/API errors.
|
||||||
|
*/
|
||||||
|
function unwrap(r) {
|
||||||
|
if (r.status !== 200) throw new Error("Bilibili API HTTP " + r.status);
|
||||||
|
const body = r.body;
|
||||||
|
if (!body) throw new Error("Bilibili API returned invalid JSON");
|
||||||
if (body.code !== 0) throw new Error(describeApiError(body.code, body.message));
|
if (body.code !== 0) throw new Error(describeApiError(body.code, body.message));
|
||||||
if (!body.data) throw new Error("Bilibili API returned no data");
|
if (!body.data) throw new Error("Bilibili API returned no data");
|
||||||
return body.data;
|
return body.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET a Bilibili API endpoint anonymously and return its `data` payload.
|
||||||
|
* The WBI-signed endpoint is tried first (it survives IP blocks that reject
|
||||||
|
* legacy unsigned calls); risk-control blocks and signature rejections
|
||||||
|
* trigger one refresh + retry; hard WBI failures fall back to the legacy
|
||||||
|
* unsigned endpoint, whose own errors are surfaced to the user.
|
||||||
|
* @param {string} wbiUrl - Full WBI endpoint base URL.
|
||||||
|
* @param {string} legacyUrl - Full legacy endpoint base URL.
|
||||||
|
* @param {object} params - Query parameters (signed for WBI, plain for legacy).
|
||||||
|
* @returns {Promise<object>} The endpoint's `data` payload.
|
||||||
|
* @throws {Error} with a user-readable message on network/HTTP/API errors.
|
||||||
|
*/
|
||||||
|
async function biliApiGet(wbiUrl, legacyUrl, params) {
|
||||||
|
// --- WBI-signed attempt (with one reactive refresh + retry) ---
|
||||||
|
for (let attempt = 0; attempt < 2; attempt++) {
|
||||||
|
let keys;
|
||||||
|
try {
|
||||||
|
keys = await loadWbiKeys();
|
||||||
|
} catch (_) {
|
||||||
|
break; // no keys -> legacy path
|
||||||
|
}
|
||||||
|
let r;
|
||||||
|
try {
|
||||||
|
r = await rawGet(wbiUrl + "?" + signWbiParams(params));
|
||||||
|
} catch (e) {
|
||||||
|
if (attempt === 0) continue; // transient network error -> retry once with fresh signature (wts changes)
|
||||||
|
break; // legacy path
|
||||||
|
}
|
||||||
|
if (r.status === 412 || r.body?.code === -412) {
|
||||||
|
if (attempt === 0) { await refreshAfterBlock(); continue; }
|
||||||
|
break; // blocked even signed -> try legacy
|
||||||
|
}
|
||||||
|
if (r.body?.code === -403) {
|
||||||
|
// Either a WBI signature rejection or a region-locked video: refresh
|
||||||
|
// the keys once; if it persists, the legacy endpoint below decides.
|
||||||
|
if (attempt === 0) {
|
||||||
|
_wbiKeys = null;
|
||||||
|
_wbiPromise = null;
|
||||||
|
await new Promise((r2) => setTimeout(r2, WBI_RETRY_DELAY_MS));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break; // legacy decides (region-locked videos fail there too)
|
||||||
|
}
|
||||||
|
if (r.status === 200 && r.body) {
|
||||||
|
if (r.body.code === 0) {
|
||||||
|
if (r.body.data) return r.body.data;
|
||||||
|
break; // code 0 without data -> legacy path
|
||||||
|
}
|
||||||
|
// A definite business error is trustworthy — surface it directly.
|
||||||
|
throw new Error(describeApiError(r.body.code, r.body.message));
|
||||||
|
}
|
||||||
|
break; // unexpected status -> legacy path
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Legacy unsigned attempt (with one fingerprint refresh + retry) ---
|
||||||
|
const qs = new URLSearchParams(params).toString();
|
||||||
|
for (let attempt = 0; ; attempt++) {
|
||||||
|
let r;
|
||||||
|
try {
|
||||||
|
r = await rawGet(legacyUrl + "?" + qs);
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error("Bilibili API unreachable: " + (e?.cause?.message || e?.message || String(e)));
|
||||||
|
}
|
||||||
|
if (r.status === 412 || r.body?.code === -412) {
|
||||||
|
if (attempt === 0) { await refreshAfterBlock(); continue; }
|
||||||
|
throw new Error(BLOCKED_HINT);
|
||||||
|
}
|
||||||
|
return unwrap(r);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -484,37 +589,39 @@ async function normalizeBilibiliUrl(str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch video metadata for a parsed reference.
|
* Fetch video metadata for a parsed reference (WBI-signed view, legacy
|
||||||
|
* fallback).
|
||||||
* @param {{kind: string, id: string}} ref
|
* @param {{kind: string, id: string}} ref
|
||||||
* @returns {Promise<object>} The view API `data` payload.
|
* @returns {Promise<object>} The view API `data` payload.
|
||||||
*/
|
*/
|
||||||
export async function fetchBilibiliView(ref) {
|
export async function fetchBilibiliView(ref) {
|
||||||
const params = ref.kind === "bvid" ? { bvid: ref.id } : { aid: String(ref.id) };
|
const params = ref.kind === "bvid" ? { bvid: ref.id } : { aid: String(ref.id) };
|
||||||
return biliJson(API_VIEW + "?" + new URLSearchParams(params));
|
return biliApiGet(API_VIEW_WBI, API_VIEW, params);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch the playback manifest for one video page. Default mode requests the
|
* Fetch the playback manifest for one video page (WBI-signed playurl,
|
||||||
* DASH manifest (fnval=16); html5 mode requests the anonymous-friendly
|
* legacy fallback). Both modes carry try_look=1, the anonymous
|
||||||
* progressive mp4 (durl) used as a second chance when no DASH audio stream
|
* watch-anyway flag. Default mode requests the DASH manifest (fnval=16),
|
||||||
* is available (DASH requires a login cookie).
|
* which anonymously includes real DASH audio streams; html5 mode requests
|
||||||
|
* the progressive mp4 (durl) used when a video has no DASH audio.
|
||||||
* @param {{bvid?: string, aid?: number|string, cid: number|string}} meta
|
* @param {{bvid?: string, aid?: number|string, cid: number|string}} meta
|
||||||
* @param {{html5?: boolean}} [opts]
|
* @param {{mode?: "dash"|"html5"}} [opts]
|
||||||
* @returns {Promise<object>} The playurl API `data` payload.
|
* @returns {Promise<object>} The playurl API `data` payload.
|
||||||
*/
|
*/
|
||||||
export async function fetchBilibiliPlayUrl(meta, opts = {}) {
|
export async function fetchBilibiliPlayUrl(meta, opts = {}) {
|
||||||
const params = opts.html5
|
const params = opts.mode === "html5"
|
||||||
? { cid: String(meta.cid), platform: "html5", high_quality: "1" }
|
? { cid: String(meta.cid), platform: "html5", high_quality: "1", try_look: "1" }
|
||||||
: { cid: String(meta.cid), fnval: "16", fourk: "1" };
|
: { cid: String(meta.cid), fnval: "16", fourk: "1", try_look: "1" };
|
||||||
if (meta.bvid) params.bvid = meta.bvid;
|
if (meta.bvid) params.bvid = meta.bvid;
|
||||||
else if (meta.aid != null) params.aid = String(meta.aid);
|
else if (meta.aid != null) params.aid = String(meta.aid);
|
||||||
return biliJson(API_PLAYURL + "?" + new URLSearchParams(params));
|
return biliApiGet(API_PLAYURL_WBI, API_PLAYURL, params);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pick the best DASH audio stream from a playurl payload: all audio
|
* Pick the best DASH audio stream from a playurl payload: all audio
|
||||||
* variants (plain, flac, dolby when a login cookie unlocks them) are
|
* variants are candidates and the highest-bandwidth entry wins. Anonymous
|
||||||
* candidates and the highest-bandwidth entry wins.
|
* calls return the regular AAC tiers here (empirically up to ~170 kbps).
|
||||||
* @param {object} data - playurl `data` payload.
|
* @param {object} data - playurl `data` payload.
|
||||||
* @returns {object|null} The chosen audio stream entry, or null.
|
* @returns {object|null} The chosen audio stream entry, or null.
|
||||||
*/
|
*/
|
||||||
@@ -530,22 +637,25 @@ export function pickBestAudioStream(data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pick the progressive (non-DASH) fallback stream from a playurl payload: a
|
* Pick the progressive (non-DASH) fallback streams from a playurl payload:
|
||||||
* single-segment durl mp4/flv whose audio the node can decode directly.
|
* the durl entries (mp4/flv) whose audio the node can decode directly.
|
||||||
* Zero or multiple segments yield null — multi-segment progressive streams
|
* All segments are returned — a single segment is served through the plain
|
||||||
* cannot be chained through one proxy URL.
|
* proxy URL, multiple segments through the list/concatenating proxy mode.
|
||||||
* @param {object} data - playurl `data` payload.
|
* @param {object} data - playurl `data` payload.
|
||||||
* @returns {{url: string, backupUrls: Array<string>}|null}
|
* @returns {{segments: Array<{url: string, size: number, backupUrls: Array<string>}>}|null}
|
||||||
*/
|
*/
|
||||||
export function pickProgressiveStream(data) {
|
export function pickProgressiveSegments(data) {
|
||||||
const durl = Array.isArray(data?.durl) ? data.durl : null;
|
const durl = Array.isArray(data?.durl) ? data.durl : null;
|
||||||
if (!durl || durl.length !== 1) return null;
|
if (!durl || !durl.length) return null;
|
||||||
const seg = durl[0];
|
const segments = [];
|
||||||
|
for (const seg of durl) {
|
||||||
if (typeof seg?.url !== "string" || !seg.url.startsWith("http")) return null;
|
if (typeof seg?.url !== "string" || !seg.url.startsWith("http")) return null;
|
||||||
const backupUrls = Array.isArray(seg.backup_url)
|
const backupUrls = Array.isArray(seg.backup_url)
|
||||||
? seg.backup_url.filter(u => typeof u === "string" && u.startsWith("http"))
|
? seg.backup_url.filter(u => typeof u === "string" && u.startsWith("http"))
|
||||||
: [];
|
: [];
|
||||||
return { url: seg.url, backupUrls };
|
segments.push({ url: seg.url, size: Math.floor(Number(seg.size) || 0), backupUrls });
|
||||||
|
}
|
||||||
|
return segments.length ? { segments } : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,24 +1,28 @@
|
|||||||
/**
|
/**
|
||||||
* @module src/music/bilibili
|
* @module src/music/bilibili
|
||||||
* @description Bilibili playback support barrel: URL detection, video/page
|
* @description Bilibili playback support barrel: URL detection, video/page
|
||||||
* resolution via the public web API, best-audio-stream selection, and the
|
* resolution via the public web API (fully anonymous — no login cookies),
|
||||||
* signed local proxy that lets the audio node fetch Bilibili CDN streams.
|
* 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()
|
* Flow: `%play https://www.bilibili.com/video/BV…` → SearchMixin.play()
|
||||||
* detects the link → resolveBilibiliVideo() builds queueable track(s) → at
|
* detects the link → resolveBilibiliVideo() builds queueable track(s) → at
|
||||||
* playback time getBilibiliStreamUrl() re-resolves a fresh DASH audio URL
|
* playback time getBilibiliStreamUrl() re-resolves a fresh stream (the URLs
|
||||||
* (they expire) and wraps it in a signed proxy URL → the existing
|
* expire) and wraps it in a signed proxy URL → the existing
|
||||||
* Lavalink/NodeLink resolve-through pipeline decodes it like any other
|
* Lavalink/NodeLink resolve-through pipeline decodes it like any other
|
||||||
* direct audio stream.
|
* direct audio stream. Anonymous DASH audio is preferred; videos without
|
||||||
|
* DASH audio fall back to the html5 progressive mp4, with multi-segment
|
||||||
|
* streams served through the concatenating proxy mode.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import {
|
import {
|
||||||
bilibiliEnabled,
|
bilibiliEnabled,
|
||||||
buildSignedProxyUrl,
|
buildSignedProxyUrl,
|
||||||
|
buildSignedListProxyUrl,
|
||||||
configureBilibiliProxy,
|
configureBilibiliProxy,
|
||||||
ensureBilibiliProxy,
|
ensureBilibiliProxy,
|
||||||
} from "./BilibiliProxy.mjs";
|
} from "./BilibiliProxy.mjs";
|
||||||
import { fetchBilibiliPlayUrl, pickBestAudioStream, pickProgressiveStream, setBilibiliCookie } from "./BilibiliResolver.mjs";
|
import { fetchBilibiliPlayUrl, pickBestAudioStream, pickProgressiveSegments } from "./BilibiliResolver.mjs";
|
||||||
import { logger } from "../../core/Logger.mjs";
|
import { logger } from "../../core/Logger.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -30,23 +34,21 @@ import { logger } from "../../core/Logger.mjs";
|
|||||||
* @param {number} [section.port=0] - Proxy listen port (0 = ephemeral).
|
* @param {number} [section.port=0] - Proxy listen port (0 = ephemeral).
|
||||||
* @param {string} [section.advertiseHost] - Host the audio node uses to
|
* @param {string} [section.advertiseHost] - Host the audio node uses to
|
||||||
* reach the proxy when it runs on another machine/container.
|
* 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 = {}) {
|
export function configureBilibili(section = {}) {
|
||||||
setBilibiliCookie(section.cookie ?? null);
|
|
||||||
configureBilibiliProxy(section);
|
configureBilibiliProxy(section);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve a fresh, playable stream URL for a queued Bilibili track.
|
* 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
|
* 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
|
* (and every seek/loop) rather than at queue time. Selection order,
|
||||||
* re-queried, the best DASH audio stream picked, and the CDN URL wrapped in
|
* fully anonymous:
|
||||||
* a signed proxy URL the audio node can fetch with the right Referer/UA.
|
* 1. DASH audio from the fnval=16 playurl (best quality, ~130-170 kbps);
|
||||||
* When Bilibili returns no DASH audio (anonymous playback — DASH requires
|
* 2. progressive durl segments from that same payload;
|
||||||
* a login cookie), a single-segment progressive mp4 is used instead, asking
|
* 3. html5-platform progressive mp4 (single or multi segment).
|
||||||
* the anonymous-friendly html5 playurl variant as a second chance.
|
* Single segments go through the plain `/s` proxy URL, multi-segment
|
||||||
|
* streams through the concatenating `/l` proxy URL.
|
||||||
* @param {object} track - Internal track with a `bilibili` metadata field.
|
* @param {object} track - Internal track with a `bilibili` metadata field.
|
||||||
* @returns {Promise<{url: string, backupUrls: Array<string>}>}
|
* @returns {Promise<{url: string, backupUrls: Array<string>}>}
|
||||||
* @throws {Error} with a user-readable message when resolution fails.
|
* @throws {Error} with a user-readable message when resolution fails.
|
||||||
@@ -61,6 +63,7 @@ export async function getBilibiliStreamUrl(track) {
|
|||||||
}
|
}
|
||||||
await ensureBilibiliProxy();
|
await ensureBilibiliProxy();
|
||||||
|
|
||||||
|
// 1. Anonymous DASH audio.
|
||||||
const data = await fetchBilibiliPlayUrl(meta);
|
const data = await fetchBilibiliPlayUrl(meta);
|
||||||
const best = pickBestAudioStream(data);
|
const best = pickBestAudioStream(data);
|
||||||
if (best?.baseUrl) {
|
if (best?.baseUrl) {
|
||||||
@@ -69,26 +72,37 @@ export async function getBilibiliStreamUrl(track) {
|
|||||||
return { url, backupUrls: Array.isArray(best.backupUrl) ? best.backupUrl : [] };
|
return { url, backupUrls: Array.isArray(best.backupUrl) ? best.backupUrl : [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
let progressive = pickProgressiveStream(data);
|
// 2. Progressive segments from the DASH-mode payload.
|
||||||
|
let progressive = pickProgressiveSegments(data);
|
||||||
|
|
||||||
|
// 3. html5-platform progressive mp4 as the second chance.
|
||||||
if (!progressive) {
|
if (!progressive) {
|
||||||
const html5 = await fetchBilibiliPlayUrl(meta, { html5: true });
|
const html5 = await fetchBilibiliPlayUrl(meta, { mode: "html5" });
|
||||||
progressive = pickProgressiveStream(html5);
|
progressive = pickProgressiveSegments(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)");
|
if (progressive) {
|
||||||
|
if (progressive.segments.length === 1) {
|
||||||
|
const seg = progressive.segments[0];
|
||||||
|
const url = await buildSignedProxyUrl(seg.url);
|
||||||
|
logger.player("[Bilibili] no DASH audio — using progressive mp4: " + url.substring(0, 60) + "...");
|
||||||
|
return { url, backupUrls: seg.backupUrls };
|
||||||
|
}
|
||||||
|
const url = await buildSignedListProxyUrl(progressive.segments);
|
||||||
|
logger.player("[Bilibili] no DASH audio — using " + progressive.segments.length + " progressive segments: " + url.substring(0, 60) + "...");
|
||||||
|
return { url, backupUrls: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error("Bilibili returned no playable audio stream for this video (it may be region-locked, premium-only, or deleted)");
|
||||||
}
|
}
|
||||||
|
|
||||||
export { isBilibiliUrl, parseBilibiliVideoRef, resolveBilibiliVideo } from "./BilibiliResolver.mjs";
|
export { isBilibiliUrl, parseBilibiliVideoRef, resolveBilibiliVideo } from "./BilibiliResolver.mjs";
|
||||||
export { setBilibiliCookie, resetBilibiliFingerprint, BILIBILI_UA, BILIBILI_REFERER } from "./BilibiliResolver.mjs";
|
export { resetBilibiliFingerprint, BILIBILI_UA, BILIBILI_REFERER } from "./BilibiliResolver.mjs";
|
||||||
export {
|
export {
|
||||||
bilibiliEnabled,
|
bilibiliEnabled,
|
||||||
bilibiliProxyInfo,
|
bilibiliProxyInfo,
|
||||||
ensureBilibiliProxy,
|
ensureBilibiliProxy,
|
||||||
resetBilibiliProxy,
|
resetBilibiliProxy,
|
||||||
buildSignedProxyUrl,
|
buildSignedProxyUrl,
|
||||||
|
buildSignedListProxyUrl,
|
||||||
} from "./BilibiliProxy.mjs";
|
} from "./BilibiliProxy.mjs";
|
||||||
@@ -365,7 +365,7 @@
|
|||||||
"loadError": "حدث خطأ أثناء تحميل المقطع.",
|
"loadError": "حدث خطأ أثناء تحميل المقطع.",
|
||||||
"searchingProvider": "جارٍ البحث في {{provider}}...",
|
"searchingProvider": "جارٍ البحث في {{provider}}...",
|
||||||
"bilibiliResolving": "📺 جارٍ تحليل فيديو Bilibili...",
|
"bilibiliResolving": "📺 جارٍ تحليل فيديو Bilibili...",
|
||||||
"bilibiliNoAudio": "❌ لا يوجد صوت قابل للتشغيل لـ **{{title}}** — قد يكون الفيديو مقفلًا جغرافيًا أو مدفوعًا أو يتطلب كوكيز تسجيل الدخول (config.json → bilibili.cookie).",
|
"bilibiliNoAudio": "❌ لا يوجد صوت قابل للتشغيل لـ **{{title}}** — قد يكون الفيديو مقفلًا جغرافيًا أو مدفوعًا أو محذوفًا.",
|
||||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||||
"bilibiliDisabled": "❌ تشغيل Bilibili معطل (config.json → bilibili.enabled)."
|
"bilibiliDisabled": "❌ تشغيل Bilibili معطل (config.json → bilibili.enabled)."
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -365,7 +365,7 @@
|
|||||||
"loadError": "هەڵەیەک ڕوویدا لە کاتی بارکردنی تراک.",
|
"loadError": "هەڵەیەک ڕوویدا لە کاتی بارکردنی تراک.",
|
||||||
"searchingProvider": "گەڕان لە {{provider}}...",
|
"searchingProvider": "گەڕان لە {{provider}}...",
|
||||||
"bilibiliResolving": "📺 ڤیدیۆی Bilibili چارەسەر دەکرێت...",
|
"bilibiliResolving": "📺 ڤیدیۆی Bilibili چارەسەر دەکرێت...",
|
||||||
"bilibiliNoAudio": "❌ هیچ دەنگێکی لێدراو نییە بۆ **{{title}}** — لەوانەیە ڤیدیۆکە بە ناوچە دەبەسترێت، پارەدار بێت یان پێویستی بە کوکی چوونەژوورەوە هەبێت (config.json → bilibili.cookie).",
|
"bilibiliNoAudio": "❌ هیچ دەنگێکی لێدراو نییە بۆ **{{title}}** — لەوانەیە ڤیدیۆکە بە ناوچە دەبەسترێت، پارەدار بێت یان سڕدرابێتەوە.",
|
||||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||||
"bilibiliDisabled": "❌ لێدانی Bilibili ناچالاک کراوە (config.json → bilibili.enabled)."
|
"bilibiliDisabled": "❌ لێدانی Bilibili ناچالاک کراوە (config.json → bilibili.enabled)."
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -365,7 +365,7 @@
|
|||||||
"loadError": "Beim Laden des Tracks ist ein Fehler aufgetreten.",
|
"loadError": "Beim Laden des Tracks ist ein Fehler aufgetreten.",
|
||||||
"searchingProvider": "Suche auf {{provider}}...",
|
"searchingProvider": "Suche auf {{provider}}...",
|
||||||
"bilibiliResolving": "📺 Bilibili-Video wird aufgelöst...",
|
"bilibiliResolving": "📺 Bilibili-Video wird aufgelöst...",
|
||||||
"bilibiliNoAudio": "❌ Kein abspielbares Audio für **{{title}}** — das Video ist möglicherweise regional gesperrt, kostenpflichtig oder braucht einen Login-Cookie (config.json → bilibili.cookie).",
|
"bilibiliNoAudio": "❌ Kein abspielbares Audio für **{{title}}** — das Video ist möglicherweise regional gesperrt, kostenpflichtig oder gelöscht.",
|
||||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||||
"bilibiliDisabled": "❌ Bilibili-Wiedergabe ist deaktiviert (config.json → bilibili.enabled)."
|
"bilibiliDisabled": "❌ Bilibili-Wiedergabe ist deaktiviert (config.json → bilibili.enabled)."
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -473,7 +473,7 @@
|
|||||||
"loadError": "An error occurred while loading the track.",
|
"loadError": "An error occurred while loading the track.",
|
||||||
"searchingProvider": "Searching {{provider}}...",
|
"searchingProvider": "Searching {{provider}}...",
|
||||||
"bilibiliResolving": "📺 Resolving Bilibili video...",
|
"bilibiliResolving": "📺 Resolving Bilibili video...",
|
||||||
"bilibiliNoAudio": "❌ No playable audio for **{{title}}** — the video may be region-locked, premium-only, or need a login cookie (config.json → bilibili.cookie).",
|
"bilibiliNoAudio": "❌ No playable audio for **{{title}}** — the video may be region-locked, premium-only, or deleted.",
|
||||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||||
"bilibiliDisabled": "❌ Bilibili playback is disabled (config.json → bilibili.enabled)."
|
"bilibiliDisabled": "❌ Bilibili playback is disabled (config.json → bilibili.enabled)."
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -365,7 +365,7 @@
|
|||||||
"loadError": "Ocorreu um erro ao carregar a faixa.",
|
"loadError": "Ocorreu um erro ao carregar a faixa.",
|
||||||
"searchingProvider": "Buscando no {{provider}}...",
|
"searchingProvider": "Buscando no {{provider}}...",
|
||||||
"bilibiliResolving": "📺 Resolvendo vídeo do Bilibili...",
|
"bilibiliResolving": "📺 Resolvendo vídeo do Bilibili...",
|
||||||
"bilibiliNoAudio": "❌ Nenhum áudio reproduzível para **{{title}}** — o vídeo pode estar bloqueado por região, ser pago ou exigir um cookie de login (config.json → bilibili.cookie).",
|
"bilibiliNoAudio": "❌ Nenhum áudio reproduzível para **{{title}}** — o vídeo pode estar bloqueado por região, ser pago ou ter sido excluído.",
|
||||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||||
"bilibiliDisabled": "❌ A reprodução do Bilibili está desativada (config.json → bilibili.enabled)."
|
"bilibiliDisabled": "❌ A reprodução do Bilibili está desativada (config.json → bilibili.enabled)."
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -462,7 +462,7 @@
|
|||||||
"loadError": "Parça yüklenirken bir hata oluştu.",
|
"loadError": "Parça yüklenirken bir hata oluştu.",
|
||||||
"searchingProvider": "{{provider}} aranıyor...",
|
"searchingProvider": "{{provider}} aranıyor...",
|
||||||
"bilibiliResolving": "📺 Bilibili videosu çözümleniyor...",
|
"bilibiliResolving": "📺 Bilibili videosu çözümleniyor...",
|
||||||
"bilibiliNoAudio": "❌ **{{title}}** için çalınabilir ses yok — video bölge kilitli, ücretli olabilir veya giriş çerezi gerektirebilir (config.json → bilibili.cookie).",
|
"bilibiliNoAudio": "❌ **{{title}}** için çalınabilir ses yok — video bölge kilitli, ücretli olabilir veya silinmiş olabilir.",
|
||||||
"bilibiliError": "❌ Bilibili: {{message}}",
|
"bilibiliError": "❌ Bilibili: {{message}}",
|
||||||
"bilibiliDisabled": "❌ Bilibili oynatma devre dışı (config.json → bilibili.enabled)."
|
"bilibiliDisabled": "❌ Bilibili oynatma devre dışı (config.json → bilibili.enabled)."
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in new issue
Block a user