From 771b005d7e6293e1462429ef6439f86c0a6641e1 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Sat, 12 Sep 2026 01:21:05 +0300 Subject: [PATCH] ... --- README.md | 2 +- config_example.json | 16 +- src/core/Bot.mjs | 1 - src/music/bilibili/BilibiliProxy.mjs | 369 ++++++++++++++++++-- src/music/bilibili/BilibiliResolver.mjs | 430 +++++++++++++++--------- src/music/bilibili/index.mjs | 64 ++-- storage/locales/bot/ar-SA.json | 2 +- storage/locales/bot/ckb.json | 2 +- storage/locales/bot/de-DE.json | 2 +- storage/locales/bot/en.json | 2 +- storage/locales/bot/pt-BR.json | 2 +- storage/locales/bot/tr.json | 2 +- 12 files changed, 660 insertions(+), 234 deletions(-) diff --git a/README.md b/README.md index 492bf67..5fc223a 100644 --- a/README.md +++ b/README.md @@ -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. 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. --- diff --git a/config_example.json b/config_example.json index 2ad010d..17bbd37 100644 --- a/config_example.json +++ b/config_example.json @@ -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.", "timeout": 30000, "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 %)", "presenceInterval": null, @@ -24,7 +23,7 @@ }, { "text": "Ping for Prefix", - "emoji_name": "\ud83c\udfa7", + "emoji_name": "Remix", "activity": { "name": "music", "type": 2 @@ -32,7 +31,7 @@ }, { "text": "Ping for Prefix | By RedTech & NoLogicAlan", - "emoji_name": "\ud83c\udfb6", + "emoji_name": "Remix", "activity": { "name": "RedTech & NoLogicAlan", "type": 2 @@ -51,14 +50,13 @@ "bind": "127.0.0.1", "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 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": "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-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:", "station": { "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", "url": "url to stream from; this will be kept private", "description": "Genre: Zamrock, provided by [Zamrock.net](https://zamrock.net/)", @@ -87,8 +85,7 @@ "enabled": false, "redis": { "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": { "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, "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": { "totalShards": 1, "shardsPerProcess": 1, diff --git a/src/core/Bot.mjs b/src/core/Bot.mjs index 4d4c71c..5f76cd6 100644 --- a/src/core/Bot.mjs +++ b/src/core/Bot.mjs @@ -120,7 +120,6 @@ class Remix { bind: config.bilibili?.bind ?? "127.0.0.1", port: config.bilibili?.port ?? 0, advertiseHost: config.bilibili?.advertiseHost ?? null, - cookie: config.bilibili?.cookie ?? null, }); this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%"); diff --git a/src/music/bilibili/BilibiliProxy.mjs b/src/music/bilibili/BilibiliProxy.mjs index 7e6bb51..f14d9f7 100644 --- a/src/music/bilibili/BilibiliProxy.mjs +++ b/src/music/bilibili/BilibiliProxy.mjs @@ -1,13 +1,21 @@ /** * @module src/music/bilibili/BilibiliProxy * @description A tiny localhost HTTP proxy that lets the NodeLink/Lavalink - * node fetch Bilibili CDN audio. Bilibili's DASH audio URLs (m4s) only - * respond to requests carrying a bilibili Referer and a browser User-Agent — - * headers an audio node cannot attach — so the bot signs the CDN URL with a - * per-process HMAC key and hands the node - * `http://:/s?u=&e=&x=` instead. The - * proxy validates the signature, then streams the CDN response (including - * Range requests, which give seek support) with the right headers attached. + * node fetch Bilibili CDN audio. Bilibili's stream URLs (DASH m4s and + * progressive mp4/flv alike) only respond to requests carrying a bilibili + * Referer and a browser User-Agent — headers an audio node cannot attach — + * so the bot signs the CDN URL with a per-process HMAC key and hands the + * node `http://:/s?u=&e=&x=` instead. + * + * 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 * never delays startup or shutdown. Only URLs signed by this very process @@ -16,7 +24,7 @@ import http from "node:http"; import crypto from "node:crypto"; -import { Readable } from "node:stream"; +import { Readable, Transform } from "node:stream"; import { logger } from "../../core/Logger.mjs"; import { buildBilibiliCdnHeaders } from "./BilibiliResolver.mjs"; @@ -24,6 +32,8 @@ import { buildBilibiliCdnHeaders } from "./BilibiliResolver.mjs"; const PROXY_TTL_MS = 6 * 60 * 60 * 1000; /** @type {number} @description Timeout (ms) waiting for the CDN response headers. */ const CDN_CONNECT_TIMEOUT_MS = 20_000; +/** @type {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). */ 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 {number} expires * @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 - * the proxy on first use. The HMAC is computed over the base64url-encoded - * target exactly as it travels in the `u` query parameter, so verification - * on the serving side never has to guess the encoding. - * @param {string} targetUrl - The raw CDN (m4s) URL from the playurl API. + * Sign a single Bilibili CDN URL into a proxy URL the audio node can fetch. + * Starts the proxy on first use. The HMAC is computed over the + * base64url-encoded target exactly as it travels in the `u` query + * parameter, so verification on the serving side never has to guess the + * encoding. + * @param {string} targetUrl - The raw CDN (m4s / mp4) URL from the playurl API. * @param {number} [ttlMs=PROXY_TTL_MS] - Signature lifetime. - * @returns {Promise} The signed proxy URL. + * @returns {Promise} The signed proxy URL (`/s` mode). */ export async function buildSignedProxyUrl(targetUrl, ttlMs = PROXY_TTL_MS) { 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 - * Referer/UA headers Bilibili requires, and pipe the response through - * (status, content-type/length/range and Range semantics included). + * Sign a multi-segment progressive stream into a concatenating proxy URL. + * The payload carries each segment's CDN URL and byte size (plus up to four + * 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}>} segments + * @param {number} [ttlMs=PROXY_TTL_MS] - Signature lifetime. + * @returns {Promise} 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}} 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} + * @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} + */ +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.ServerResponse} res * @returns {Promise} @@ -205,23 +365,41 @@ async function handleProxyRequest(req, res) { res.end("bad request"); return; } - if (u.pathname !== "/s") { + if (u.pathname !== "/s" && u.pathname !== "/l") { res.writeHead(404, { "Content-Type": "text/plain" }); res.end("not found"); return; } - const uParam = u.searchParams.get("u"); - const expires = Number(u.searchParams.get("e")); - const sig = u.searchParams.get("x"); - if (!uParam || !Number.isFinite(expires) || !sig || Date.now() >= expires || !verifySignature(uParam, expires, sig)) { - res.writeHead(403, { "Content-Type": "text/plain" }); - res.end("forbidden"); + const uParam = checkSignature(u, res); + if (uParam == null) return; + + let payload; + try { payload = Buffer.from(uParam, "base64url").toString("utf8"); } catch (_) { + res.writeHead(400, { "Content-Type": "text/plain" }); + res.end("bad target"); 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} + */ +async function serveSingle(req, res, payload) { 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.end("bad target"); return; @@ -266,12 +444,8 @@ async function handleProxyRequest(req, res) { return; } - if (!upstream.body) { - res.end(); - return; - } - await new Promise((resolve, reject) => { + if (!upstream.body) { resolve(); return; } const stream = Readable.fromWeb(upstream.body); stream.once("error", reject); res.once("error", reject); @@ -280,3 +454,136 @@ async function handleProxyRequest(req, res) { 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} + */ +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(); +} diff --git a/src/music/bilibili/BilibiliResolver.mjs b/src/music/bilibili/BilibiliResolver.mjs index a7a6f94..6e4e16a 100644 --- a/src/music/bilibili/BilibiliResolver.mjs +++ b/src/music/bilibili/BilibiliResolver.mjs @@ -2,18 +2,25 @@ * @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 - * with a self-managed device fingerprint, DASH audio-stream selection (with - * a progressive mp4 fallback for anonymous playback), and internal track - * building. + * for fully anonymous playback (no login cookies, ever), best-audio-stream + * selection 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. + * Anonymous access strategy (empirically verified against the live API): + * - Every request carries a self-managed device fingerprint: the finger/spi + * endpoint mints a fresh buvid3/buvid4 pair and a homepage GET contributes + * b_nut. Risk-control blocks (HTTP 412 / code -412) trigger one shared + * fingerprint refresh and retry before giving up on an endpoint. + * - Requests prefer the WBI-signed endpoints (`/x/web-interface/wbi/view`, + * `/x/player/wbi/playurl`): the mixin key is derived from the anonymous + * 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 * 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}. */ +import crypto from "node:crypto"; import { Utils } from "../../utils/Utils.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. */ 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"; -/** @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"; +/** @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. */ 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. */ @@ -57,6 +71,8 @@ const SHORTLINK_TIMEOUT_MS = 10_000; 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 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. */ const REFRESH_MIN_INTERVAL_MS = 2_500; /** @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. */ const BLOCKED_HINT = "Bilibili blocked this server's requests (risk control, HTTP 412). " + - "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."; + "The bot manages its device fingerprint and WBI request signatures automatically, so a persistent block means " + + "Bilibili flagged this hosting IP: a different egress IP (VPN or proxy) may be required. " + + "This bot plays Bilibili fully anonymously, so there is no cookie workaround."; -/** @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 {Array} @description Permutation used to derive the WBI mixin + * 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|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). */ @@ -123,70 +149,25 @@ let _bootstrapPromise = null; let _refreshPromise = null; /** @type {number} @description Timestamp (ms) of the last fingerprint refresh trigger. */ 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 - * 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. + * Whether a device-cookie value is plausible (used when harvesting + * Set-Cookie values from the homepage bootstrap). * @param {string} name * @param {string} value * @returns {boolean} */ -function plausibleCookieValue(name, value) { +function plausibleDeviceValue(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; - } -} - -/** - * 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, dropped: Array}} - */ -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"); + 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); + default: return false; } } @@ -236,9 +217,9 @@ function bootstrapFingerprint() { 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; + if (!fp.buvid3 && plausibleDeviceValue("buvid3", jar.buvid3 ?? "")) fp.buvid3 = jar.buvid3; + if (!fp.b_nut && plausibleDeviceValue("b_nut", jar.b_nut ?? "")) fp.b_nut = jar.b_nut; + if (!fp.buvid4 && plausibleDeviceValue("buvid4", jar.buvid4 ?? "")) fp.buvid4 = jar.buvid4; } catch (_) {} return null; })(), @@ -253,14 +234,16 @@ function bootstrapFingerprint() { } /** - * Clear the memoized device fingerprint and pending refresh state so the - * next request bootstraps a fresh one (used by tests to isolate scenarios). + * Clear the memoized device fingerprint, WBI keys and pending refresh state + * so the next request bootstraps everything fresh (used by tests). */ export function resetBilibiliFingerprint() { _bootstrapPromise = null; _fingerprint = null; _refreshPromise = null; _refreshGate = 0; + _wbiKeys = null; + _wbiPromise = null; } /** @@ -275,9 +258,9 @@ function refreshFingerprint() { /** * 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). + * pause, then a single fingerprint refresh (and WBI key invalidation) no + * matter how many requests were blocked at the same time — the refresh is + * rate-limited so parallel queue loads cannot hammer the endpoints. * @returns {Promise} */ function refreshAfterBlock() { @@ -287,6 +270,8 @@ function refreshAfterBlock() { _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"); + _wbiKeys = null; + _wbiPromise = null; await refreshFingerprint(); })(); } @@ -294,32 +279,22 @@ function refreshAfterBlock() { } /** - * 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. + * The device-fingerprint cookie sent on Bilibili requests (buvid3/b_nut/ + * buvid4 only — no login cookies exist in this module by design). * @returns {string|null} */ function effectiveCookie() { + if (!_fingerprint) return null; 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]); - } + for (const name of ["buvid3", "b_nut", "buvid4"]) { + if (_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). + * Referer / Origin / Sec-Fetch set plus the device fingerprint cookie. * @returns {Promise} */ async function biliRequestHeaders() { @@ -331,9 +306,7 @@ async function biliRequestHeaders() { } /** - * 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. + * Build the header set the local proxy forwards to Bilibili CDN hosts. * @returns {Promise} */ export async function buildBilibiliCdnHeaders() { @@ -344,6 +317,73 @@ export async function buildBilibiliCdnHeaders() { 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. * @param {number} code @@ -360,45 +400,110 @@ function describeApiError(code, message) { } /** - * GET a Bilibili API endpoint and return its `data` payload, mapping HTTP - * 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. + * One raw GET against api.bilibili.com. * @param {string} url - * @returns {Promise} + * @returns {Promise<{status: number, body: object|null}>} + * @throws {Error} on network failure. + */ +async function rawGet(url) { + const headers = await biliRequestHeaders(); + const res = await fetch(url, { headers, redirect: "follow", signal: AbortSignal.timeout(API_TIMEOUT_MS) }); + if (res.status !== 200) { + try { res.body?.cancel?.(); } catch (_) {} + return { status: res.status, body: null }; + } + let body; + try { + body = await res.json(); + } catch (_) { + return { status: -1, body: null }; + } + return { status: 200, body }; +} + +/** + * 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.data) throw new Error("Bilibili API returned no 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} The endpoint's `data` payload. * @throws {Error} with a user-readable message on network/HTTP/API errors. */ -async function biliJson(url) { - for (let attempt = 0; ; attempt++) { - const headers = await biliRequestHeaders(); - let res; +async function biliApiGet(wbiUrl, legacyUrl, params) { + // --- WBI-signed attempt (with one reactive refresh + retry) --- + for (let attempt = 0; attempt < 2; attempt++) { + let keys; try { - res = await fetch(url, { headers, redirect: "follow", signal: AbortSignal.timeout(API_TIMEOUT_MS) }); + 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 (res.status === 412) { - try { res.body?.cancel?.(); } catch (_) {} + if (r.status === 412 || r.body?.code === -412) { 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; + 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 * @returns {Promise} The view API `data` payload. */ export async function fetchBilibiliView(ref) { const params = ref.kind === "bvid" ? { bvid: ref.id } : { aid: String(ref.id) }; - return biliJson(API_VIEW + "?" + new URLSearchParams(params)); + return biliApiGet(API_VIEW_WBI, API_VIEW, params); } /** - * 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). + * Fetch the playback manifest for one video page (WBI-signed playurl, + * legacy fallback). Both modes carry try_look=1, the anonymous + * watch-anyway flag. Default mode requests the DASH manifest (fnval=16), + * 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 {{html5?: boolean}} [opts] + * @param {{mode?: "dash"|"html5"}} [opts] * @returns {Promise} The playurl API `data` payload. */ 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" }; + const params = opts.mode === "html5" + ? { cid: String(meta.cid), platform: "html5", high_quality: "1", try_look: "1" } + : { cid: String(meta.cid), fnval: "16", fourk: "1", try_look: "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)); + return biliApiGet(API_PLAYURL_WBI, API_PLAYURL, params); } /** * Pick the best DASH audio stream from a playurl payload: all audio - * variants (plain, flac, dolby when a login cookie unlocks them) are - * candidates and the highest-bandwidth entry wins. + * variants are candidates and the highest-bandwidth entry wins. Anonymous + * calls return the regular AAC tiers here (empirically up to ~170 kbps). * @param {object} data - playurl `data` payload. * @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 - * 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. + * Pick the progressive (non-DASH) fallback streams from a playurl payload: + * the durl entries (mp4/flv) whose audio the node can decode directly. + * All segments are returned — a single segment is served through the plain + * proxy URL, multiple segments through the list/concatenating proxy mode. * @param {object} data - playurl `data` payload. - * @returns {{url: string, backupUrls: Array}|null} + * @returns {{segments: Array<{url: string, size: number, backupUrls: Array}>}|null} */ -export function pickProgressiveStream(data) { +export function pickProgressiveSegments(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 }; + if (!durl || !durl.length) return null; + const segments = []; + for (const seg of durl) { + 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")) + : []; + segments.push({ url: seg.url, size: Math.floor(Number(seg.size) || 0), backupUrls }); + } + return segments.length ? { segments } : null; } /** diff --git a/src/music/bilibili/index.mjs b/src/music/bilibili/index.mjs index 359772d..e926340 100644 --- a/src/music/bilibili/index.mjs +++ b/src/music/bilibili/index.mjs @@ -1,24 +1,28 @@ /** * @module src/music/bilibili * @description Bilibili playback support barrel: URL detection, video/page - * resolution via the public web API, best-audio-stream selection, and the - * signed local proxy that lets the audio node fetch Bilibili CDN streams. + * resolution via the public web API (fully anonymous — no login cookies), + * best-audio-stream selection, and the signed local proxy that lets the + * audio node fetch Bilibili CDN streams. * * Flow: `%play https://www.bilibili.com/video/BV…` → SearchMixin.play() * detects the link → resolveBilibiliVideo() builds queueable track(s) → at - * playback time getBilibiliStreamUrl() re-resolves a fresh DASH audio URL - * (they expire) and wraps it in a signed proxy URL → the existing + * playback time getBilibiliStreamUrl() re-resolves a fresh stream (the URLs + * expire) and wraps it in a signed proxy URL → the existing * 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 { bilibiliEnabled, buildSignedProxyUrl, + buildSignedListProxyUrl, configureBilibiliProxy, ensureBilibiliProxy, } from "./BilibiliProxy.mjs"; -import { fetchBilibiliPlayUrl, pickBestAudioStream, pickProgressiveStream, setBilibiliCookie } from "./BilibiliResolver.mjs"; +import { fetchBilibiliPlayUrl, pickBestAudioStream, pickProgressiveSegments } from "./BilibiliResolver.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 {string} [section.advertiseHost] - Host the audio node uses to * reach the proxy when it runs on another machine/container. - * @param {string} [section.cookie] - Browser cookie string (SESSDATA etc.); - * unlocks higher audio quality and works around IP blocks. */ export function configureBilibili(section = {}) { - setBilibiliCookie(section.cookie ?? null); configureBilibiliProxy(section); } /** * Resolve a fresh, playable stream URL for a queued Bilibili track. * DASH audio URLs expire after a few hours, so this runs at every play - * (and every seek/loop) rather than at queue time: the playurl API is - * re-queried, the best 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. + * (and every seek/loop) rather than at queue time. Selection order, + * fully anonymous: + * 1. DASH audio from the fnval=16 playurl (best quality, ~130-170 kbps); + * 2. progressive durl segments from that same payload; + * 3. html5-platform progressive mp4 (single or multi segment). + * 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. * @returns {Promise<{url: string, backupUrls: Array}>} * @throws {Error} with a user-readable message when resolution fails. @@ -61,6 +63,7 @@ export async function getBilibiliStreamUrl(track) { } await ensureBilibiliProxy(); + // 1. Anonymous DASH audio. const data = await fetchBilibiliPlayUrl(meta); const best = pickBestAudioStream(data); if (best?.baseUrl) { @@ -69,26 +72,37 @@ export async function getBilibiliStreamUrl(track) { 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) { - 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 }; + const html5 = await fetchBilibiliPlayUrl(meta, { mode: "html5" }); + progressive = pickProgressiveSegments(html5); } - 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 { setBilibiliCookie, resetBilibiliFingerprint, BILIBILI_UA, BILIBILI_REFERER } from "./BilibiliResolver.mjs"; +export { resetBilibiliFingerprint, BILIBILI_UA, BILIBILI_REFERER } from "./BilibiliResolver.mjs"; export { bilibiliEnabled, bilibiliProxyInfo, ensureBilibiliProxy, resetBilibiliProxy, buildSignedProxyUrl, + buildSignedListProxyUrl, } from "./BilibiliProxy.mjs"; diff --git a/storage/locales/bot/ar-SA.json b/storage/locales/bot/ar-SA.json index b00f797..1349158 100644 --- a/storage/locales/bot/ar-SA.json +++ b/storage/locales/bot/ar-SA.json @@ -365,7 +365,7 @@ "loadError": "حدث خطأ أثناء تحميل المقطع.", "searchingProvider": "جارٍ البحث في {{provider}}...", "bilibiliResolving": "📺 جارٍ تحليل فيديو Bilibili...", - "bilibiliNoAudio": "❌ لا يوجد صوت قابل للتشغيل لـ **{{title}}** — قد يكون الفيديو مقفلًا جغرافيًا أو مدفوعًا أو يتطلب كوكيز تسجيل الدخول (config.json → bilibili.cookie).", + "bilibiliNoAudio": "❌ لا يوجد صوت قابل للتشغيل لـ **{{title}}** — قد يكون الفيديو مقفلًا جغرافيًا أو مدفوعًا أو محذوفًا.", "bilibiliError": "❌ Bilibili: {{message}}", "bilibiliDisabled": "❌ تشغيل Bilibili معطل (config.json → bilibili.enabled)." }, diff --git a/storage/locales/bot/ckb.json b/storage/locales/bot/ckb.json index 10d9f41..059750e 100644 --- a/storage/locales/bot/ckb.json +++ b/storage/locales/bot/ckb.json @@ -365,7 +365,7 @@ "loadError": "هەڵەیەک ڕوویدا لە کاتی بارکردنی تراک.", "searchingProvider": "گەڕان لە {{provider}}...", "bilibiliResolving": "📺 ڤیدیۆی Bilibili چارەسەر دەکرێت...", - "bilibiliNoAudio": "❌ هیچ دەنگێکی لێدراو نییە بۆ **{{title}}** — لەوانەیە ڤیدیۆکە بە ناوچە دەبەسترێت، پارەدار بێت یان پێویستی بە کوکی چوونەژوورەوە هەبێت (config.json → bilibili.cookie).", + "bilibiliNoAudio": "❌ هیچ دەنگێکی لێدراو نییە بۆ **{{title}}** — لەوانەیە ڤیدیۆکە بە ناوچە دەبەسترێت، پارەدار بێت یان سڕدرابێتەوە.", "bilibiliError": "❌ Bilibili: {{message}}", "bilibiliDisabled": "❌ لێدانی Bilibili ناچالاک کراوە (config.json → bilibili.enabled)." }, diff --git a/storage/locales/bot/de-DE.json b/storage/locales/bot/de-DE.json index 71990bd..a1d9a78 100644 --- a/storage/locales/bot/de-DE.json +++ b/storage/locales/bot/de-DE.json @@ -365,7 +365,7 @@ "loadError": "Beim Laden des Tracks ist ein Fehler aufgetreten.", "searchingProvider": "Suche auf {{provider}}...", "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}}", "bilibiliDisabled": "❌ Bilibili-Wiedergabe ist deaktiviert (config.json → bilibili.enabled)." }, diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index 504d1ee..ca97f8e 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -473,7 +473,7 @@ "loadError": "An error occurred while loading the track.", "searchingProvider": "Searching {{provider}}...", "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}}", "bilibiliDisabled": "❌ Bilibili playback is disabled (config.json → bilibili.enabled)." }, diff --git a/storage/locales/bot/pt-BR.json b/storage/locales/bot/pt-BR.json index 2635798..604f144 100644 --- a/storage/locales/bot/pt-BR.json +++ b/storage/locales/bot/pt-BR.json @@ -365,7 +365,7 @@ "loadError": "Ocorreu um erro ao carregar a faixa.", "searchingProvider": "Buscando no {{provider}}...", "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}}", "bilibiliDisabled": "❌ A reprodução do Bilibili está desativada (config.json → bilibili.enabled)." }, diff --git a/storage/locales/bot/tr.json b/storage/locales/bot/tr.json index 11e5ff1..7a2f5bb 100644 --- a/storage/locales/bot/tr.json +++ b/storage/locales/bot/tr.json @@ -462,7 +462,7 @@ "loadError": "Parça yüklenirken bir hata oluştu.", "searchingProvider": "{{provider}} aranıyor...", "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}}", "bilibiliDisabled": "❌ Bilibili oynatma devre dışı (config.json → bilibili.enabled)." },