diff --git a/README.md b/README.md index 167712e..69d6cc3 100644 --- a/README.md +++ b/README.md @@ -112,13 +112,14 @@ A few things worth knowing: - **Filters** (bassboost, nightcore, etc.) are applied server-side by NodeLink, so they take effect on the next track that starts. - **Volume** is applied client-side by the LiveKit connection (1–200). - Radio metadata (StreamTitle) is read with **ffprobe** (`ffprobe-static`). +- **Bilibili playback** — `%play https://www.bilibili.com/video/BV…` (b23.tv short links and `?p=` parts included) resolves the video through Bilibili's web API, picks the best DASH audio stream, and feeds it to the node through a signed localhost proxy that attaches the Referer/User-Agent headers Bilibili's CDN requires. Multi-part videos queue like a playlist. If Bilibili risk-control blocks your hosting IP (HTTP 412), set `bilibili.cookie` in config.json to a logged-in browser cookie string. The proxy binds `127.0.0.1` by default — set `bilibili.advertiseHost` (and `bind: "0.0.0.0"`) when your node runs on another machine. --- ## Features - **High-quality audio playback** — NodeLink streaming with a zero-re-encode WebM/Opus pipeline, published over LiveKit -- **Multi-source search** — YouTube, YT Music, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bandcamp and 40+ more provider prefixes, plus direct URLs +- **Multi-source search** — YouTube, YT Music, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bandcamp and 40+ more provider prefixes, plus direct URLs and Bilibili videos - **24/7 mode** — keep the bot in a voice channel permanently, with staggered auto-rejoin on boot and rejoin retries on connection loss - **Interactive emoji player** — reaction-based control panel with live progress, lyrics viewer, and a filter submenu - **Lyrics** — synced lyrics via NodeLink diff --git a/commands/eval.mjs b/commands/eval.mjs index 7afa627..744f8e7 100644 --- a/commands/eval.mjs +++ b/commands/eval.mjs @@ -158,10 +158,6 @@ async function runEval(expression, context) { ? `return (${expression});` : expression; - // Build the async function via the AsyncFunction constructor instead of eval(), - // and shadow dangerous globals as parameters so evaluated code cannot trivially - // reach the Node.js runtime (require, process.binding, etc.) even if owner - // credentials are compromised. const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor; result = await new AsyncFunction("process", "require", "module", "global", "globalThis", "__dirname", "__filename", code).call(context); type = result === null ? "null" : typeof result; @@ -315,4 +311,4 @@ export async function run(msg, data) { }); resetTimer(); -} +} \ No newline at end of file diff --git a/commands/play.mjs b/commands/play.mjs index 3661bb0..0e8a0f2 100644 --- a/commands/play.mjs +++ b/commands/play.mjs @@ -1,7 +1,7 @@ /** * @module commands/play * @description Play a song or playlist from a URL or search query. - * Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and Last.fm integration. + * Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bilibili, and Last.fm integration. */ import { CommandBuilder } from "../src/commands/index.mjs"; @@ -159,8 +159,8 @@ export const command = new CommandBuilder() .setCategory("music") .setDescription( "Play a song or playlist from a URL or search query.\n" + - "Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and more.\n" + - "Also accepts direct audio URLs (MP3, OGG, AAC, radio streams).\n" + + "Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bilibili, and more.\n" + + "Also accepts direct audio URLs (MP3, OGG, AAC, radio streams) and Bilibili video links (incl. b23.tv and ?p= parts).\n" + "Default search: YouTube Music. Use `-p ` or inline prefix e.g. `sp: blinding lights`.", "commands.play" ) @@ -170,6 +170,7 @@ export const command = new CommandBuilder() "$prefixplay dz: get lucky", "$prefixplay -p yt take over league of legends", "$prefixplay https://open.spotify.com/track/...", + "$prefixplay https://www.bilibili.com/video/BV1y7bg6kEhY", "$prefixplay https://example.com/stream.mp3", "$prefixplay https://radio.example.com:8000/live", "$prefixplay https://www.last.fm/music/Drake/_/Make+Them+Cry", diff --git a/config_example.json b/config_example.json index c301341..488abcb 100644 --- a/config_example.json +++ b/config_example.json @@ -46,6 +46,14 @@ "requestTimeout": 60000, "Comment": "requestTimeout: ms before a NodeLink HTTP request is aborted. Default: 60000 (60s). Raise if you see 'NodeLink request timeout' errors. All audio sources (Spotify, Deezer, Apple Music, etc.) are resolved by NodeLink, so configure source credentials in nodelink.config.json, not here." }, + "bilibili": { + "enabled": true, + "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 (SESSDATA=...; buvid3=...) — unlocks higher audio quality and fixes 'Bilibili blocked this server's requests (HTTP 412)' on flagged hosting IPs; copy it from a logged-in browser's devtools." + }, "comment-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": { diff --git a/src/core/Bot.mjs b/src/core/Bot.mjs index f624277..4d4c71c 100644 --- a/src/core/Bot.mjs +++ b/src/core/Bot.mjs @@ -26,6 +26,7 @@ import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs"; import { LastFmManager } from "../services/lastfm/LastFmManager.mjs"; import { FluxerListManager } from "../services/FluxerListManager.mjs"; import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs"; +import { configureBilibili } from "../music/bilibili/index.mjs"; import { applyMixins } from "../utils/mixins.mjs"; import BotVoiceMixin from "./BotVoiceMixin.mjs"; @@ -114,6 +115,14 @@ class Remix { setGlobalColor(config.embedColor); + configureBilibili({ + enabled: config.bilibili?.enabled !== false, + 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 : "%"); this.locale.load(); diff --git a/src/music/bilibili/BilibiliProxy.mjs b/src/music/bilibili/BilibiliProxy.mjs new file mode 100644 index 0000000..7e6bb51 --- /dev/null +++ b/src/music/bilibili/BilibiliProxy.mjs @@ -0,0 +1,282 @@ +/** + * @module src/music/bilibili/BilibiliProxy + * @description A tiny localhost HTTP proxy that lets the NodeLink/Lavalink + * node fetch Bilibili CDN audio. Bilibili's DASH audio URLs (m4s) only + * respond to requests carrying a bilibili Referer and a browser User-Agent — + * headers an audio node cannot attach — so the bot signs the CDN URL with a + * per-process HMAC key and hands the node + * `http://:/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. + * + * The server starts lazily on the first Bilibili play and is unref'd, so it + * never delays startup or shutdown. Only URLs signed by this very process + * can pass through — the HMAC key is random per boot. + */ + +import http from "node:http"; +import crypto from "node:crypto"; +import { Readable } from "node:stream"; +import { logger } from "../../core/Logger.mjs"; +import { buildBilibiliCdnHeaders } from "./BilibiliResolver.mjs"; + +/** @type {number} @description How long a signed proxy URL stays valid (Bilibili CDN URLs themselves expire). */ +const PROXY_TTL_MS = 6 * 60 * 60 * 1000; +/** @type {number} @description Timeout (ms) waiting for the CDN response headers. */ +const CDN_CONNECT_TIMEOUT_MS = 20_000; + +/** @type {object} @description Effective proxy configuration (merged from config.json -> bilibili). */ +const _cfg = { + enabled: true, + bind: "127.0.0.1", + port: 0, + advertiseHost: null, +}; + +/** @type {http.Server|null} @description The lazily-started proxy server (unref'd). */ +let _server = null; +/** @type {Buffer|null} @description Per-process HMAC signing key. */ +let _key = null; +/** @type {Promise|null} @description Memoized server start (idempotent). */ +let _starting = null; + +/** + * Merge the config.json `bilibili` section into the proxy configuration. + * @param {object} [section] + * @param {boolean} [section.enabled=true] - false disables Bilibili playback. + * @param {string} [section.bind="127.0.0.1"] - Address the proxy listens on. + * @param {number} [section.port=0] - Listen port (0 = pick a free port). + * @param {string} [section.advertiseHost] - Host the audio node should use + * to reach the proxy (defaults to the bind address; set when the node runs + * on another machine/container). + */ +export function configureBilibiliProxy(section = {}) { + if (section.bind != null) _cfg.bind = String(section.bind); + if (section.port != null) _cfg.port = Number(section.port) || 0; + if (section.advertiseHost != null) _cfg.advertiseHost = String(section.advertiseHost); + if (section.enabled != null) _cfg.enabled = section.enabled !== false; +} + +/** + * Whether Bilibili playback is enabled in config. + * @returns {boolean} + */ +export function bilibiliEnabled() { + return _cfg.enabled === true; +} + +/** + * The host:port pair advertised to the audio node. 0.0.0.0 binds are + * advertised as 127.0.0.1 unless an explicit advertiseHost was configured. + * @returns {string} + */ +function advertiseHost() { + if (_cfg.advertiseHost) return _cfg.advertiseHost; + return _cfg.bind === "0.0.0.0" || _cfg.bind === "::" ? "127.0.0.1" : _cfg.bind; +} + +/** + * Start the proxy server (once per process) and return its listening info. + * @returns {Promise<{port: number, host: string}>} + */ +export function ensureBilibiliProxy() { + if (_starting) return _starting; + _starting = new Promise((resolve, reject) => { + try { + _key = crypto.randomBytes(32); + const server = http.createServer((req, res) => { + handleProxyRequest(req, res).catch(err => { + logger.warn("[BilibiliProxy] request failed: " + (err?.message || err)); + try { + if (!res.headersSent) res.writeHead(502, { "Content-Type": "text/plain" }); + res.end("bilibili proxy error: " + (err?.message || err)); + } catch (_) {} + }); + }); + server.on("clientError", (_err, socket) => { + try { socket.destroy(); } catch (_) {} + }); + server.listen(_cfg.port, _cfg.bind, () => { + const addr = server.address(); + _server = server; + const port = typeof addr === "object" && addr ? addr.port : _cfg.port; + logger.player("[BilibiliProxy] listening on " + _cfg.bind + ":" + port + " (advertised as " + advertiseHost() + ")"); + resolve({ port, host: advertiseHost() }); + }); + server.once("error", (err) => { + _starting = null; + reject(new Error("bilibili proxy failed to listen on " + _cfg.bind + ":" + _cfg.port + ": " + err.message)); + }); + server.unref?.(); + } catch (e) { + _starting = null; + reject(e); + } + }); + return _starting; +} + +/** + * Current proxy info (without starting it). + * @returns {{port: number, host: string}|null} + */ +export function bilibiliProxyInfo() { + if (!_server) return null; + const addr = _server.address(); + const port = typeof addr === "object" && addr ? addr.port : _cfg.port; + return { port, host: advertiseHost() }; +} + +/** + * Stop the proxy and clear its key (used by tests and reconfiguration). + * @returns {Promise} + */ +export function resetBilibiliProxy() { + const server = _server; + _server = null; + _starting = null; + _key = null; + if (!server) return Promise.resolve(); + return new Promise((resolve) => { + try { server.close(() => resolve()); } catch (_) { resolve(); } + try { server.closeAllConnections?.(); } catch (_) {} + }); +} + +/** + * HMAC-SHA256 signature binding a CDN URL to its expiry epoch. + * @param {string} target + * @param {number} expires + * @returns {string} + */ +function signTarget(target, expires) { + return crypto.createHmac("sha256", _key).update(target + "." + expires).digest("hex"); +} + +/** + * Constant-time signature verification. + * @param {string} target + * @param {number} expires + * @param {string} sig + * @returns {boolean} + */ +function verifySignature(target, expires, sig) { + if (!_key) return false; + const expected = Buffer.from(signTarget(target, expires), "utf8"); + const provided = Buffer.from(String(sig ?? ""), "utf8"); + return expected.length === provided.length && crypto.timingSafeEqual(expected, provided); +} + +/** + * Sign a Bilibili CDN URL into a proxy URL the audio node can fetch. Starts + * the proxy on first use. The HMAC is computed over the base64url-encoded + * target exactly as it travels in the `u` query parameter, so verification + * on the serving side never has to guess the encoding. + * @param {string} targetUrl - The raw CDN (m4s) URL from the playurl API. + * @param {number} [ttlMs=PROXY_TTL_MS] - Signature lifetime. + * @returns {Promise} The signed proxy URL. + */ +export async function buildSignedProxyUrl(targetUrl, ttlMs = PROXY_TTL_MS) { + const { port, host } = await ensureBilibiliProxy(); + const expires = Date.now() + ttlMs; + const u = Buffer.from(String(targetUrl), "utf8").toString("base64url"); + const x = signTarget(u, expires); + return "http://" + host + ":" + port + "/s?u=" + u + "&e=" + expires + "&x=" + x; +} + +/** + * Serve one proxy request: verify the signature, fetch the CDN URL with the + * Referer/UA headers Bilibili requires, and pipe the response through + * (status, content-type/length/range and Range semantics included). + * @param {http.IncomingMessage} req + * @param {http.ServerResponse} res + * @returns {Promise} + */ +async function handleProxyRequest(req, res) { + if (req.method !== "GET" && req.method !== "HEAD") { + res.writeHead(405, { "Content-Type": "text/plain" }); + res.end("method not allowed"); + return; + } + + let u; + try { u = new URL(req.url ?? "/", "http://localhost"); } catch (_) { + res.writeHead(400, { "Content-Type": "text/plain" }); + res.end("bad request"); + return; + } + if (u.pathname !== "/s") { + res.writeHead(404, { "Content-Type": "text/plain" }); + res.end("not found"); + return; + } + + const uParam = u.searchParams.get("u"); + const expires = Number(u.searchParams.get("e")); + const sig = u.searchParams.get("x"); + if (!uParam || !Number.isFinite(expires) || !sig || Date.now() >= expires || !verifySignature(uParam, expires, sig)) { + res.writeHead(403, { "Content-Type": "text/plain" }); + res.end("forbidden"); + return; + } + + let targetUrl; + try { targetUrl = new URL(Buffer.from(uParam, "base64url").toString("utf8")); } catch (_) { + res.writeHead(400, { "Content-Type": "text/plain" }); + res.end("bad target"); + return; + } + if (targetUrl.protocol !== "http:" && targetUrl.protocol !== "https:") { + res.writeHead(400, { "Content-Type": "text/plain" }); + res.end("bad target protocol"); + return; + } + + const forwardHeaders = await buildBilibiliCdnHeaders(); + if (req.headers.range) forwardHeaders.Range = req.headers.range; + + const abort = new AbortController(); + const connectTimer = setTimeout(() => abort.abort(), CDN_CONNECT_TIMEOUT_MS); + req.once("close", () => abort.abort()); + + let upstream; + try { + upstream = await fetch(targetUrl.href, { + method: req.method === "HEAD" ? "HEAD" : "GET", + headers: forwardHeaders, + redirect: "follow", + signal: abort.signal, + }); + } catch (e) { + clearTimeout(connectTimer); + throw new Error("CDN fetch failed: " + (e?.cause?.message || e?.message || String(e))); + } + clearTimeout(connectTimer); + + const headers = {}; + for (const name of ["content-type", "content-length", "content-range", "accept-ranges"]) { + const v = upstream.headers.get(name); + if (v != null) headers[name] = v; + } + res.writeHead(upstream.status, headers); + + if (req.method === "HEAD") { + try { upstream.body?.cancel?.(); } catch (_) {} + res.end(); + return; + } + + if (!upstream.body) { + res.end(); + return; + } + + await new Promise((resolve, reject) => { + const stream = Readable.fromWeb(upstream.body); + stream.once("error", reject); + res.once("error", reject); + res.once("close", () => { abort.abort(); resolve(); }); + stream.pipe(res); + res.once("finish", resolve); + }); +} diff --git a/src/music/bilibili/BilibiliResolver.mjs b/src/music/bilibili/BilibiliResolver.mjs new file mode 100644 index 0000000..a6b0222 --- /dev/null +++ b/src/music/bilibili/BilibiliResolver.mjs @@ -0,0 +1,421 @@ +/** + * @module src/music/bilibili/BilibiliResolver + * @description Bilibili video resolution: URL detection (BV/av ids, b23.tv / + * bili2233.cn short links, ?p= page selection), the public web API client + * (view + playurl with browser-style headers and an automatic buvid + * bootstrap), DASH audio-stream selection, and internal track building. + * + * The audio URLs Bilibili hands out only respond to requests carrying a + * bilibili Referer and a browser User-Agent, so the raw CDN URL is never + * handed to the audio pipeline directly — playback goes through the signed + * local proxy in {@link module:src/music/bilibili/BilibiliProxy}. + */ + +import { Utils } from "../../utils/Utils.mjs"; +import { logger } from "../../core/Logger.mjs"; + +/** @type {string} @description Browser User-Agent required by Bilibili API and CDN endpoints. */ +export const BILIBILI_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"; +/** @type {string} @description Referer required by Bilibili CDN endpoints. */ +export const BILIBILI_REFERER = "https://www.bilibili.com/"; + +/** @type {string} @description Video metadata endpoint (bvid= or aid=). */ +const API_VIEW = "https://api.bilibili.com/x/web-interface/view"; +/** @type {string} @description Playback URL endpoint (DASH manifest when fnval=16). */ +const API_PLAYURL = "https://api.bilibili.com/x/player/playurl"; +/** @type {string} @description Homepage used once per process to bootstrap buvid3/b_nut cookies. */ +const BOOTSTRAP_URL = "https://www.bilibili.com/"; + +/** @type {number} @description Timeout (ms) for Bilibili API requests. */ +const API_TIMEOUT_MS = 15_000; +/** @type {number} @description Timeout (ms) for short-link redirect resolution. */ +const SHORTLINK_TIMEOUT_MS = 10_000; +/** @type {number} @description Timeout (ms) for the one-shot cookie bootstrap. */ +const BOOTSTRAP_TIMEOUT_MS = 10_000; +/** @type {number} @description Maximum number of multi-page parts queued from one video. */ +const MAX_PAGES = 200; + +/** @type {Set} @description Bilibili hosts whose /video/ links the bot plays. */ +const BILIBILI_HOSTS = new Set([ + "bilibili.com", + "www.bilibili.com", + "m.bilibili.com", + "b23.tv", + "bili2233.cn", +]); + +/** @type {string} @description Error hint shown when Bilibili risk control blocks the server IP. */ +const BLOCKED_HINT = + "Bilibili blocked this server's requests (risk control, HTTP 412). " + + "Add a cookie string from a logged-in browser to config.json -> bilibili.cookie and restart the bot."; + +/** @type {string|null} @description Optional cookie string from config (SESSDATA etc.), overrides the bootstrap. */ +let _cookieOverride = null; +/** @type {string|null} @description buvid3/b_nut cookies picked up from the homepage bootstrap. */ +let _bootstrappedCookie = null; +/** @type {Promise|null} @description Memoized bootstrap run (best effort, never rejects). */ +let _bootstrapPromise = null; + +/** + * Set a user-provided cookie string (from config.json -> bilibili.cookie). + * Sent on every Bilibili API and CDN request; unlocks higher audio quality + * and works around IP-level risk-control blocks. + * @param {string|null} cookie + */ +export function setBilibiliCookie(cookie) { + _cookieOverride = cookie ? String(cookie).trim() : null; +} + +/** + * One best-effort homepage GET per process: Bilibili's risk control expects + * to see the buvid3/b_nut cookies the homepage sets, so picking them up + * raises the request trust level at zero cost. + * @returns {Promise} + */ +function bootstrapCookies() { + if (_bootstrapPromise) return _bootstrapPromise; + _bootstrapPromise = (async () => { + try { + const res = await fetch(BOOTSTRAP_URL, { + headers: { "User-Agent": BILIBILI_UA, "Accept": "text/html,application/xhtml+xml,*/*" }, + redirect: "follow", + signal: AbortSignal.timeout(BOOTSTRAP_TIMEOUT_MS), + }); + const parts = []; + for (const raw of res.headers.getSetCookie?.() ?? []) { + const pair = raw.split(";")[0].trim(); + if (/^(buvid3|b_nut|buvid4)=/.test(pair)) parts.push(pair); + } + try { res.body?.cancel?.(); } catch (_) {} + if (parts.length) { + _bootstrappedCookie = parts.join("; "); + logger.player("[Bilibili] bootstrapped cookies: " + parts.map(p => p.split("=")[0]).join(",")); + } + } catch (_) { + /* best effort only — plain headerless requests still work on most IPs */ + } + return null; + })(); + return _bootstrapPromise; +} + +/** + * Build the header set for Bilibili API requests (UA, Referer, Accept and + * the effective cookie: config override, else the bootstrapped buvid pair). + * @returns {Promise} + */ +async function biliRequestHeaders() { + if (!_cookieOverride) await bootstrapCookies(); + const headers = { + "User-Agent": BILIBILI_UA, + "Referer": BILIBILI_REFERER, + "Accept": "application/json, text/plain, */*", + "Accept-Language": "en-US,en;q=0.9", + }; + const cookie = _cookieOverride || _bootstrappedCookie; + if (cookie) headers.Cookie = cookie; + return headers; +} + +/** + * Build the header set the local proxy forwards to Bilibili CDN hosts. + * Same trust rules as the API headers: config cookie overrides bootstrap. + * @returns {Promise} + */ +export async function buildBilibiliCdnHeaders() { + if (!_cookieOverride) await bootstrapCookies(); + const headers = { + "User-Agent": BILIBILI_UA, + "Referer": BILIBILI_REFERER, + "Accept": "*/*", + }; + const cookie = _cookieOverride || _bootstrappedCookie; + if (cookie) headers.Cookie = cookie; + return headers; +} + +/** + * Turn a Bilibili API error code into a user-readable message. + * @param {number} code + * @param {string} message + * @returns {string} + */ +function describeApiError(code, message) { + if (code === -412) return BLOCKED_HINT; + if (code === -404 || code === 404 || code === -400) return "video not found (it may be private, deleted, or the link is wrong)"; + if (code === -403 || code === 403) return "this video is region-locked or private"; + if (code === 62002 || code === 62004) return "this video is not publicly visible"; + if (code === 62012) return "this video is only visible to its uploader"; + return "Bilibili API error " + code + (message ? ": " + message : ""); +} + +/** + * GET a Bilibili API endpoint and return its `data` payload, mapping HTTP + * status and body error codes to readable messages. + * @param {string} url + * @returns {Promise} + * @throws {Error} with a user-readable message on network/HTTP/API errors. + */ +async function biliJson(url) { + const headers = await biliRequestHeaders(); + let res; + try { + res = await fetch(url, { headers, redirect: "follow", signal: AbortSignal.timeout(API_TIMEOUT_MS) }); + } catch (e) { + throw new Error("Bilibili API unreachable: " + (e?.cause?.message || e?.message || String(e))); + } + if (res.status === 412) { + try { res.body?.cancel?.(); } catch (_) {} + throw new Error(BLOCKED_HINT); + } + if (res.status !== 200) { + try { res.body?.cancel?.(); } catch (_) {} + throw new Error("Bilibili API HTTP " + res.status); + } + let body; + try { + body = await res.json(); + } catch (_) { + throw new Error("Bilibili API returned invalid JSON"); + } + if (body.code !== 0) throw new Error(describeApiError(body.code, body.message)); + if (!body.data) throw new Error("Bilibili API returned no data"); + return body.data; +} + +/** + * Check whether a string is an HTTP(S) URL on a known Bilibili host + * (www./m. bilibili.com or the b23.tv / bili2233.cn shorteners). + * @param {string} str + * @returns {boolean} + */ +export function isBilibiliUrl(str) { + if (!str || typeof str !== "string") return false; + const trimmed = str.trim(); + if (!/^https?:\/\//i.test(trimmed)) return false; + try { + const u = new URL(trimmed); + return BILIBILI_HOSTS.has(u.hostname.toLowerCase()); + } catch (_) { + return false; + } +} + +/** + * Extract the video reference (BV/av id plus optional ?p= page) from a URL + * on a Bilibili host. BV ids are case-sensitive and preserved verbatim. + * @param {string} urlStr + * @returns {{kind: "bvid"|"aid", id: string, page: number|null}|null} + */ +export function parseBilibiliVideoRef(urlStr) { + let u; + try { u = new URL(String(urlStr)); } catch (_) { return null; } + if (!BILIBILI_HOSTS.has(u.hostname.toLowerCase())) return null; + const m = u.pathname.match(/\/video\/(BV[0-9A-Za-z]{8,12}|av(\d+))/i); + if (!m) return null; + const raw = m[1]; + const isAv = /^av/i.test(raw); + const pageRaw = u.searchParams.get("p"); + const page = pageRaw && /^\d+$/.test(pageRaw) ? Math.max(1, parseInt(pageRaw, 10)) : null; + return { kind: isAv ? "aid" : "bvid", id: isAv ? m[2] : raw, page }; +} + +/** + * Resolve b23.tv / bili2233.cn short links to their final URL by following + * redirects. Falls back to the short URL itself when resolution fails (the + * view API then produces the real error). Non-bilibili redirects (bangumi, + * space, etc.) yield null — only /video/ pages are playable. + * @param {URL} u + * @returns {Promise} + */ +async function resolveShortLink(u) { + try { + const res = await fetch(u.href, { + headers: { "User-Agent": BILIBILI_UA, "Accept": "text/html,*/*" }, + redirect: "follow", + signal: AbortSignal.timeout(SHORTLINK_TIMEOUT_MS), + }); + const finalUrl = res.url || u.href; + try { res.body?.cancel?.(); } catch (_) {} + let final; + try { final = new URL(finalUrl); } catch (_) { return null; } + if (!BILIBILI_HOSTS.has(final.hostname.toLowerCase())) return null; + return final.href; + } catch (_) { + return u.href; + } +} + +/** + * Normalize any accepted Bilibili link to its canonical URL form: short + * hosts are expanded, other hosts pass through. Returns null when the + * string is not a URL on a Bilibili host. + * @param {string} str + * @returns {Promise} + */ +async function normalizeBilibiliUrl(str) { + const trimmed = String(str ?? "").trim(); + if (!/^https?:\/\//i.test(trimmed)) return null; + let u; + try { u = new URL(trimmed); } catch (_) { return null; } + const host = u.hostname.toLowerCase(); + if (!BILIBILI_HOSTS.has(host)) return null; + if (host === "b23.tv" || host === "bili2233.cn") return resolveShortLink(u); + return u.href; +} + +/** + * Fetch video metadata for a parsed reference. + * @param {{kind: string, id: string}} ref + * @returns {Promise} The view API `data` payload. + */ +export async function fetchBilibiliView(ref) { + const params = ref.kind === "bvid" ? { bvid: ref.id } : { aid: String(ref.id) }; + return biliJson(API_VIEW + "?" + new URLSearchParams(params)); +} + +/** + * Fetch the playback manifest (DASH when fnval=16) for one video page. + * @param {{bvid?: string, aid?: number|string, cid: number|string}} meta + * @returns {Promise} The playurl API `data` payload. + */ +export async function fetchBilibiliPlayUrl(meta) { + const params = { cid: String(meta.cid), fnval: "16", fourk: "1" }; + if (meta.bvid) params.bvid = meta.bvid; + else if (meta.aid != null) params.aid = String(meta.aid); + return biliJson(API_PLAYURL + "?" + new URLSearchParams(params)); +} + +/** + * Pick the best DASH audio stream from a playurl payload: all audio + * variants (plain, flac, dolby when a login cookie unlocks them) are + * candidates and the highest-bandwidth entry wins. + * @param {object} data - playurl `data` payload. + * @returns {object|null} The chosen audio stream entry, or null. + */ +export function pickBestAudioStream(data) { + const dash = data?.dash; + const candidates = []; + if (Array.isArray(dash?.audio)) candidates.push(...dash.audio); + if (Array.isArray(dash?.flac?.audio)) candidates.push(...dash.flac.audio); + if (Array.isArray(dash?.dolby?.audio)) candidates.push(...dash.dolby.audio); + const usable = candidates.filter(a => typeof a?.baseUrl === "string" && a.baseUrl.startsWith("http")); + usable.sort((a, b) => (b.bandwidth || 0) - (a.bandwidth || 0)); + return usable[0] ?? null; +} + +/** + * Build the https page URL for a video (optionally a specific part). + * @param {string} bvid + * @param {number|null} page + * @returns {string} + */ +function pageUrl(bvid, page) { + return page && page > 1 + ? "https://www.bilibili.com/video/" + bvid + "?p=" + page + : "https://www.bilibili.com/video/" + bvid; +} + +/** + * Force https on Bilibili asset URLs (thumbnails come back as http://). + * @param {string|null} url + * @returns {string|null} + */ +function httpsify(url) { + if (typeof url !== "string" || !url) return null; + return url.replace(/^http:\/\//i, "https://"); +} + +/** + * Build one internal track object for a single video page. + * @param {object} opts - { bvid, aid, cid, page, partTitle, title, durationSec, thumbnail, owner } + * @returns {object} + */ +function buildTrack(opts) { + const { bvid, aid, cid, page, partTitle, title, durationSec, thumbnail, owner } = opts; + const displayTitle = partTitle && partTitle !== title ? title + " [P" + page + ": " + partTitle + "]" : title; + const ms = Math.max(0, Math.floor(Number(durationSec) || 0) * 1000); + const authorUrl = owner?.mid ? "https://space.bilibili.com/" + owner.mid : null; + return { + type: "bilibili", + videoId: bvid, + encoded: "", + sourceName: "bilibili", + title: displayTitle, + url: pageUrl(bvid, page), + thumbnail: httpsify(thumbnail), + spotifyUrl: null, + artist: owner?.name ?? null, + author: { name: owner?.name ?? "Unknown", url: authorUrl }, + artists: null, + _durationMs: ms, + duration: { timestamp: Utils.prettifyMS(ms), seconds: Math.floor(ms / 1000) }, + bilibili: { bvid, aid: aid ?? null, cid, page: page || 1 }, + }; +} + +/** + * Turn a view API payload into queueable tracks. + * Requested page: exactly that part. Multi-page video without a page: every + * part (capped at {@link MAX_PAGES}), matching the YouTube playlist UX. + * @param {object} data - view API `data` payload. + * @param {number|null} requestedPage + * @returns {{video: object, tracks: Array}} + */ +function buildBilibiliResult(data, requestedPage) { + const bvid = data.bvid; + const aid = data.aid ?? null; + const title = String(data.title ?? "Bilibili video"); + const pic = httpsify(data.pic); + const owner = data.owner ?? null; + const pages = Array.isArray(data.pages) ? data.pages : []; + + const base = { bvid, aid, title, thumbnail: pic, owner }; + const video = { ...base, url: pageUrl(bvid, null), durationSec: data.duration ?? 0 }; + + if (requestedPage != null) { + if (pages.length > 1) { + const page = pages.find(p => Number(p.page) === requestedPage) + ?? (requestedPage >= 1 && requestedPage <= pages.length ? pages[requestedPage - 1] : null); + if (!page) throw new Error("this video has " + pages.length + " part(s) — there is no part " + requestedPage); + return { video, tracks: [buildTrack({ + ...base, cid: page.cid, page: Number(page.page) || requestedPage, + partTitle: page.part, durationSec: page.duration ?? data.duration, + })] }; + } + if (requestedPage > 1) throw new Error("this video has a single part — there is no part " + requestedPage); + } + + if (pages.length > 1) { + const tracks = pages.slice(0, MAX_PAGES).map(p => buildTrack({ + ...base, cid: p.cid, page: Number(p.page) || 1, + partTitle: p.part, durationSec: p.duration ?? data.duration, + })); + return { video, tracks }; + } + + return { + video, + tracks: [buildTrack({ + ...base, cid: data.cid, page: 1, partTitle: null, durationSec: data.duration ?? 0, + })], + }; +} + +/** + * Full resolution pipeline for a pasted Bilibili link: normalize (expand + * short links), parse the video reference, fetch metadata, build tracks. + * @param {string} input - The raw query string (a Bilibili URL). + * @returns {Promise<{video: object, tracks: Array}>} + * @throws {Error} with a user-readable message when the link is not a + * playable video, the API fails, or the video is unavailable. + */ +export async function resolveBilibiliVideo(input) { + const normalized = await normalizeBilibiliUrl(input); + if (!normalized) throw new Error("not a Bilibili link"); + const ref = parseBilibiliVideoRef(normalized); + if (!ref) throw new Error("only Bilibili video links are supported (…/video/BV… or …/video/av…)"); + const data = await fetchBilibiliView(ref); + logger.player("[Bilibili] resolved " + (ref.kind === "bvid" ? ref.id : "av" + ref.id) + ": " + data.title); + return buildBilibiliResult(data, ref.page); +} diff --git a/src/music/bilibili/index.mjs b/src/music/bilibili/index.mjs new file mode 100644 index 0000000..c57a1b9 --- /dev/null +++ b/src/music/bilibili/index.mjs @@ -0,0 +1,80 @@ +/** + * @module src/music/bilibili + * @description Bilibili playback support barrel: URL detection, video/page + * resolution via the public web API, best-audio-stream selection, and the + * signed local proxy that lets the audio node fetch Bilibili CDN streams. + * + * Flow: `%play https://www.bilibili.com/video/BV…` → SearchMixin.play() + * detects the link → resolveBilibiliVideo() builds queueable track(s) → at + * playback time getBilibiliStreamUrl() re-resolves a fresh DASH audio URL + * (they expire) and wraps it in a signed proxy URL → the existing + * Lavalink/NodeLink resolve-through pipeline decodes it like any other + * direct audio stream. + */ + +import { + bilibiliEnabled, + buildSignedProxyUrl, + configureBilibiliProxy, + ensureBilibiliProxy, +} from "./BilibiliProxy.mjs"; +import { fetchBilibiliPlayUrl, pickBestAudioStream, setBilibiliCookie } from "./BilibiliResolver.mjs"; +import { logger } from "../../core/Logger.mjs"; + +/** + * Configure Bilibili support from the config.json `bilibili` section. + * Called once at bot startup; every field is optional. + * @param {object} [section] - config.json -> bilibili + * @param {boolean} [section.enabled=true] - false disables Bilibili playback. + * @param {string} [section.bind="127.0.0.1"] - Proxy listen address. + * @param {number} [section.port=0] - Proxy listen port (0 = ephemeral). + * @param {string} [section.advertiseHost] - Host the audio node uses to + * reach the proxy when it runs on another machine/container. + * @param {string} [section.cookie] - Browser cookie string (SESSDATA etc.); + * unlocks higher audio quality and works around IP blocks. + */ +export function configureBilibili(section = {}) { + setBilibiliCookie(section.cookie ?? null); + configureBilibiliProxy(section); +} + +/** + * Resolve a fresh, playable stream URL for a queued Bilibili track. + * DASH audio URLs expire after a few hours, so this runs at every play + * (and every seek/loop) rather than at queue time: the playurl API is + * re-queried, the best audio stream picked, and the CDN URL wrapped in a + * signed proxy URL the audio node can fetch with the right Referer/UA. + * @param {object} track - Internal track with a `bilibili` metadata field. + * @returns {Promise<{url: string, backupUrls: Array}>} + * @throws {Error} with a user-readable message when resolution fails. + */ +export async function getBilibiliStreamUrl(track) { + const meta = track?.bilibili; + if (!meta || (!meta.bvid && meta.aid == null) || meta.cid == null) { + throw new Error("track is missing Bilibili stream metadata"); + } + if (!bilibiliEnabled()) { + throw new Error("Bilibili playback is disabled in config.json -> bilibili.enabled"); + } + await ensureBilibiliProxy(); + + const data = await fetchBilibiliPlayUrl(meta); + const best = pickBestAudioStream(data); + if (!best?.baseUrl) { + throw new Error("Bilibili returned no playable audio stream for this video"); + } + + const url = await buildSignedProxyUrl(best.baseUrl); + logger.player("[Bilibili] audio stream ready (bandwidth " + (best.bandwidth || "?") + "): " + url.substring(0, 60) + "..."); + return { url, backupUrls: Array.isArray(best.backupUrl) ? best.backupUrl : [] }; +} + +export { isBilibiliUrl, parseBilibiliVideoRef, resolveBilibiliVideo } from "./BilibiliResolver.mjs"; +export { setBilibiliCookie, BILIBILI_UA, BILIBILI_REFERER } from "./BilibiliResolver.mjs"; +export { + bilibiliEnabled, + bilibiliProxyInfo, + ensureBilibiliProxy, + resetBilibiliProxy, + buildSignedProxyUrl, +} from "./BilibiliProxy.mjs"; diff --git a/src/music/player/PlaybackMixin.mjs b/src/music/player/PlaybackMixin.mjs index 6a04cf5..3803a34 100644 --- a/src/music/player/PlaybackMixin.mjs +++ b/src/music/player/PlaybackMixin.mjs @@ -13,6 +13,7 @@ import { getGlobalColor } from "../../ui/index.mjs"; import { Utils, cleanId } from "../../utils/Utils.mjs"; import { logger } from "../../core/Logger.mjs"; import meta from "../probe.mjs"; +import { getBilibiliStreamUrl } from "../bilibili/index.mjs"; /** * @type {object} @@ -245,6 +246,10 @@ const PlaybackMixin = { * @private @async Play a track through the FluxerAudioBridge. For * radio/external tracks without an encoded payload, attempts Lavalink URL * resolution first so MP3/AAC streams can use the loadstream pipeline. + * Bilibili tracks get a FRESH signed proxy URL here on every play (DASH + * audio URLs expire after a few hours, and each play/seek/loop needs its + * own), which also clears any stale encoded payload so the pre-resolve + * below re-resolves against the new URL. * @this {import('./Player.mjs').Player} * @param {object} songData * @param {object} [options={}] @@ -258,7 +263,15 @@ const PlaybackMixin = { throw new Error("No encoded track or URL for: " + (songData?.title ?? "unknown")); } - if (!songData.encoded && songData.url && songData.url.startsWith("http") && this._lavalink && songData.type !== "external") { + let bridgeUrl = songData.url; + if (songData.type === "bilibili") { + const stream = await getBilibiliStreamUrl(songData); + songData.streamUrl = stream.url; + songData.encoded = null; + bridgeUrl = stream.url; + } + + if (!songData.encoded && bridgeUrl && bridgeUrl.startsWith("http") && this._lavalink && songData.type !== "external") { try { const nlInfo = this._lavalink.getNodeLinkInfo?.(); if (nlInfo) { @@ -268,7 +281,7 @@ const PlaybackMixin = { if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId; if (this._guildId) headers["Guild-Id"] = this._guildId; - const loadtracksUrl = baseUrl + "/v4/loadtracks?identifier=" + encodeURIComponent(songData.url); + const loadtracksUrl = baseUrl + "/v4/loadtracks?identifier=" + encodeURIComponent(bridgeUrl); logger.player(`[Player] Pre-resolving ${songData.type || "external"} URL via Lavalink...`); const body = await this._request(loadtracksUrl, { headers }); @@ -296,7 +309,7 @@ const PlaybackMixin = { const result = await this._audioBridge.play(this._voiceConn, { encoded: songData.encoded, - url: songData.url, + url: bridgeUrl, title: songData.title, guildId: this._guildId, }, { diff --git a/src/music/player/SearchMixin.mjs b/src/music/player/SearchMixin.mjs index b8ac401..e7976e6 100644 --- a/src/music/player/SearchMixin.mjs +++ b/src/music/player/SearchMixin.mjs @@ -12,6 +12,7 @@ import { EventEmitter } from "node:events"; import { Utils } from "../../utils/Utils.mjs"; import { logger } from "../../core/Logger.mjs"; import { PROVIDERS, PROVIDER_NAMES } from "../providers.mjs"; +import { bilibiliEnabled, isBilibiliUrl, resolveBilibiliVideo } from "../bilibili/index.mjs"; /** * @type {object} @@ -188,7 +189,8 @@ const SearchMixin = { /** * Search for a track and add it to the queue. Handles URL loading with - * YouTube normalization + oEmbed title fallback and playlist expansion. + * YouTube normalization + oEmbed title fallback and playlist expansion; + * Bilibili links are routed to {@link _playBilibili} before Lavalink. * @this {import('./Player.mjs').Player} * @param {string} query * @param {boolean} [top=false] @@ -197,6 +199,8 @@ const SearchMixin = { * @returns {EventEmitter} Emits "message" events with status strings. */ play(query, top = false, provider, trackMeta = null) { + if (isBilibiliUrl(query)) return this._playBilibili(query, top); + const events = new EventEmitter(); const source = this._getSource(provider || "ytm"); const isUrl = Utils.isValidUrl(query); @@ -434,6 +438,65 @@ const SearchMixin = { return "External Stream"; }, + /** + * Resolve a Bilibili video link into queueable track(s) — reached from + * {@link play} for any bilibili.com / b23.tv URL. Multi-part videos queue + * every part (like a YouTube playlist); `?p=N` queues exactly that part. + * Metadata and duration come from the view API, so queue display works + * before any stream is fetched; the audio stream itself is resolved at + * playback time by {@link module:src/music/player/PlaybackMixin}. + * @this {import('./Player.mjs').Player} + * @param {string} query - The raw Bilibili URL. + * @param {boolean} [top=false] - Insert at the top of the queue. + * @returns {EventEmitter} Emits "message" events with status strings. + */ + _playBilibili(query, top = false) { + const events = new EventEmitter(); + + (async () => { + try { + /* let the caller attach its "message" listener before the first emit + (play() relies on the same await-before-emit property) */ + await Promise.resolve(); + + if (!bilibiliEnabled()) { + events.emit("message", this._t("responses.play.bilibiliDisabled")); + return; + } + + events.emit("message", this._t("responses.play.bilibiliResolving")); + + const { tracks } = await resolveBilibiliVideo(query); + if (!tracks.length) { + events.emit("message", this._t("responses.play.bilibiliNoAudio", { title: "?" })); + return; + } + + if (tracks.length === 1) { + this.addToQueue(tracks[0], top); + events.emit("message", this._t("responses.play.added", { + title: tracks[0].title, + url: tracks[0].url, + })); + } else { + this.addManyToQueue(tracks, top); + events.emit("message", this._t("responses.play.addedPlaylist", { count: tracks.length })); + } + + if (!this.queue.getCurrent()) { + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + } + } catch (err) { + logger.warn("[Player] Bilibili resolve failed:", err?.message); + events.emit("message", this._t("responses.play.bilibiliError", { + message: err?.message || String(err), + })); + } + })(); + + return events; + }, + /** * Play a direct audio URL (MP3, OGG, AAC, stream, etc.) without Lavalink * search. The bridge handles decoding via Lavalink if needed. diff --git a/src/services/TrackOptionsManager.mjs b/src/services/TrackOptionsManager.mjs index 5b6ebf2..50d08b6 100644 --- a/src/services/TrackOptionsManager.mjs +++ b/src/services/TrackOptionsManager.mjs @@ -40,19 +40,19 @@ export class TrackOptionsManager { async _ensureTable() { try { await this._query( - `CREATE TABLE IF NOT EXISTS track_options ( - id INT AUTO_INCREMENT PRIMARY KEY, - user_id VARCHAR(32) NOT NULL, - track_identifier VARCHAR(512) NOT NULL, - track_title VARCHAR(512) NOT NULL DEFAULT '', - alias VARCHAR(${MAX_ALIAS_LEN}) NOT NULL DEFAULT ${mysql.escape(DEFAULT_ALIAS)}, - start_ms INT UNSIGNED NOT NULL DEFAULT 0, - end_ms INT UNSIGNED NOT NULL DEFAULT 0, - bot_id VARCHAR(32) NOT NULL DEFAULT '', - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - UNIQUE KEY uq_user_track_alias_bot (user_id, track_identifier, alias, bot_id) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4` + `CREATE TABLE IF NOT EXISTS track_options ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_id VARCHAR(32) NOT NULL, + track_identifier VARCHAR(512) NOT NULL, + track_title VARCHAR(512) NOT NULL DEFAULT '', + alias VARCHAR(${MAX_ALIAS_LEN}) NOT NULL DEFAULT ${mysql.escape(DEFAULT_ALIAS)}, + start_ms INT UNSIGNED NOT NULL DEFAULT 0, + end_ms INT UNSIGNED NOT NULL DEFAULT 0, + bot_id VARCHAR(32) NOT NULL DEFAULT '', + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + UNIQUE KEY uq_user_track_alias_bot (user_id, track_identifier, alias, bot_id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4` ); await this._migrateOldTable(); this._hasTable = true; @@ -119,8 +119,8 @@ export class TrackOptionsManager { const u = new URL(track.url); return `${u.hostname}${u.pathname}`.replace(/\/+$/, "").toLowerCase().trim(); } catch (e) { - logger.warn("[TrackOptions] Error:", e?.message); - return track.url.toLowerCase().trim(); + logger.warn("[TrackOptions] Error:", e?.message); + return track.url.toLowerCase().trim(); } } const artist = track.artist || track.author?.name || ""; @@ -145,9 +145,9 @@ export class TrackOptionsManager { try { await this._query( - `INSERT INTO track_options (user_id, track_identifier, track_title, alias, start_ms, end_ms${bi.col}) - VALUES (${mysql.escape(userId)}, ${mysql.escape(identifier)}, ${mysql.escape(title)}, ${mysql.escape(safeAlias)}, ${safeStartMs}, ${safeEndMs}${bi.val}) - ON DUPLICATE KEY UPDATE start_ms = ${safeStartMs}, end_ms = ${safeEndMs}, track_title = ${mysql.escape(title)}` + `INSERT INTO track_options (user_id, track_identifier, track_title, alias, start_ms, end_ms${bi.col}) + VALUES (${mysql.escape(userId)}, ${mysql.escape(identifier)}, ${mysql.escape(title)}, ${mysql.escape(safeAlias)}, ${safeStartMs}, ${safeEndMs}${bi.val}) + ON DUPLICATE KEY UPDATE start_ms = ${safeStartMs}, end_ms = ${safeEndMs}, track_title = ${mysql.escape(title)}` ); this._cache.delete(`${userId}:${identifier}:${safeAlias}`); return { identifier, startMs: safeStartMs, endMs: safeEndMs, alias: safeAlias }; @@ -174,7 +174,7 @@ export class TrackOptionsManager { try { const rows = await this._query( - `SELECT start_ms, end_ms, track_title, alias FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)} AND alias = ${mysql.escape(safeAlias)}${this._botIdWhere()}` + `SELECT start_ms, end_ms, track_title, alias FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)} AND alias = ${mysql.escape(safeAlias)}${this._botIdWhere()}` ); if (!rows || rows.length === 0) return null; const result = { startMs: rows[0].start_ms, endMs: rows[0].end_ms, title: rows[0].track_title, alias: rows[0].alias }; @@ -198,7 +198,7 @@ export class TrackOptionsManager { try { const rows = await this._query( - `SELECT start_ms, end_ms, track_title, alias FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)}${this._botIdWhere()} ORDER BY alias` + `SELECT start_ms, end_ms, track_title, alias FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)}${this._botIdWhere()} ORDER BY alias` ); return rows || []; } catch (err) { @@ -240,7 +240,7 @@ export class TrackOptionsManager { await this.ready(); try { const rows = await this._query( - `SELECT track_identifier, track_title, alias, start_ms, end_ms FROM track_options WHERE user_id = ${mysql.escape(userId)}${this._botIdWhere()} ORDER BY track_title, alias LIMIT ${Math.min(limit, 100)}` + `SELECT track_identifier, track_title, alias, start_ms, end_ms FROM track_options WHERE user_id = ${mysql.escape(userId)}${this._botIdWhere()} ORDER BY track_title, alias LIMIT ${Math.min(limit, 100)}` ); return rows || []; } catch (err) { diff --git a/storage/locales/bot/ar-SA.json b/storage/locales/bot/ar-SA.json index 4de6c70..b00f797 100644 --- a/storage/locales/bot/ar-SA.json +++ b/storage/locales/bot/ar-SA.json @@ -58,7 +58,7 @@ "lyrics": "عرض كلمات الأغنية المتزامنة من NodeLink.", "np": "اطلب اسم ورابط الأغنية التي تعمل حالياً.", "pause": "إيقاف التشغيل مؤقتاً في قناتك الصوتية.", - "play": "شغّل أغنية أو قائمة تشغيل من رابط أو استعلام بحث.\nيدعم يوتيوب وسبوتيفاي وساوندكلاود ودييزر وآبل ميوزيك وتايدال والمزيد.\nالبحث الافتراضي: YouTube Music. استخدم `-p <المزود>` أو بادئة مضمنة مثل `sp: blinding lights`.", + "play": "شغّل أغنية أو قائمة تشغيل من رابط أو استعلام بحث.\nيدعم يوتيوب وسبوتيفاي وساوندكلاود ودييزر وآبل ميوزيك وتايدال وبيلي بيلي والمزيد.\nالبحث الافتراضي: YouTube Music. استخدم `-p <المزود>` أو بادئة مضمنة مثل `sp: blinding lights`.", "player": "أنشئ لوحة تحكم تشغيل تفاعلية مع تقدم مباشر.", "playnext": "مثل $prefixplay لكنه يضيف النتيجة إلى أعلى قائمة الانتظار.", "radio": "شغّل محطة إذاعية. استخدم `$prefixradio list` لتصفح جميع المحطات.", @@ -363,7 +363,11 @@ "loadFailed": "فشل تحميل المقطع.", "unexpectedResult": "نتيجة غير متوقعة من محمّل المقاطع.", "loadError": "حدث خطأ أثناء تحميل المقطع.", - "searchingProvider": "جارٍ البحث في {{provider}}..." + "searchingProvider": "جارٍ البحث في {{provider}}...", + "bilibiliResolving": "📺 جارٍ تحليل فيديو Bilibili...", + "bilibiliNoAudio": "❌ لا يوجد صوت قابل للتشغيل لـ **{{title}}** — قد يكون الفيديو مقفلًا جغرافيًا أو مدفوعًا أو يتطلب كوكيز تسجيل الدخول (config.json → bilibili.cookie).", + "bilibiliError": "❌ Bilibili: {{message}}", + "bilibiliDisabled": "❌ تشغيل Bilibili معطل (config.json → bilibili.enabled)." }, "playnext": { "searching": "🔍 جارٍ البحث..." diff --git a/storage/locales/bot/ckb.json b/storage/locales/bot/ckb.json index f4f9a68..10d9f41 100644 --- a/storage/locales/bot/ckb.json +++ b/storage/locales/bot/ckb.json @@ -58,7 +58,7 @@ "lyrics": "دەقی گۆرانیی هاوئاهەنگ لە NodeLink نیشان بدە.", "np": "ناو و بەستەری گۆرانیی ئێستا داوا بکە.", "pause": "پەخشکردنەکە لە کەناڵی دەنگیت وەستێنە.", - "play": "گۆرانییەک یان لیستی پەخش بەستەرێکەوە یان بە پرسیارێکی گەڕان پەخش بکە.\nپشتگیری YouTube، Spotify، SoundCloud، Deezer، Apple Music، Tidal و زیاتر دەکات.\nگەڕانی بنەڕەتی: YouTube Music. `-p ` یان پێشگر بەکاربهێنە وەک `sp: blinding lights`.", + "play": "گۆرانییەک یان لیستی پەخش بەستەرێکەوە یان بە پرسیارێکی گەڕان پەخش بکە.\nپشتگیری YouTube، Spotify، SoundCloud، Deezer، Apple Music، Tidal، Bilibili و زیاتر دەکات.\nگەڕانی بنەڕەتی: YouTube Music. `-p ` یان پێشگر بەکاربهێنە وەک `sp: blinding lights`.", "player": "پانێلی کۆنتڕۆڵی پەخشکەری تەواوکەری هاوئاهەنگ دروست بکە.", "playnext": "وەک $prefixplay بەڵام ئەنجامەکە لە سەرەوەی ڕیزبەندییەکە زیاد دەکرێت.", "radio": "ستەیشنی ڕادیۆ پەخش بکە. `$prefixradio list` بەکاربهێنە بۆ بینینی هەموو ستەیشنەکان.", @@ -363,7 +363,11 @@ "loadFailed": "بارکردنی تراک سەرکەوتوو نەبوو.", "unexpectedResult": "ئەنجامێکی چاوەڕواننەکراو لە بارکەری تراکەوە.", "loadError": "هەڵەیەک ڕوویدا لە کاتی بارکردنی تراک.", - "searchingProvider": "گەڕان لە {{provider}}..." + "searchingProvider": "گەڕان لە {{provider}}...", + "bilibiliResolving": "📺 ڤیدیۆی Bilibili چارەسەر دەکرێت...", + "bilibiliNoAudio": "❌ هیچ دەنگێکی لێدراو نییە بۆ **{{title}}** — لەوانەیە ڤیدیۆکە بە ناوچە دەبەسترێت، پارەدار بێت یان پێویستی بە کوکی چوونەژوورەوە هەبێت (config.json → bilibili.cookie).", + "bilibiliError": "❌ Bilibili: {{message}}", + "bilibiliDisabled": "❌ لێدانی Bilibili ناچالاک کراوە (config.json → bilibili.enabled)." }, "playnext": { "searching": "🔍 گەڕان..." diff --git a/storage/locales/bot/de-DE.json b/storage/locales/bot/de-DE.json index af86b1f..71990bd 100644 --- a/storage/locales/bot/de-DE.json +++ b/storage/locales/bot/de-DE.json @@ -58,7 +58,7 @@ "lyrics": "Zeige synchronisierte Songtexte von NodeLink an.", "np": "Frage den Namen und die URL des aktuell spielenden Songs ab.", "pause": "Pausiere die Wiedergabe in deinem Sprachkanal.", - "play": "Spiele einen Song oder eine Playlist von einer URL oder Suchanfrage.\nUnterstützt YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal und mehr.\nStandardsuche: YouTube Music. Nutze `-p ` oder Inline-Präfix wie `sp: blinding lights`.", + "play": "Spiele einen Song oder eine Playlist von einer URL oder Suchanfrage.\nUnterstützt YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bilibili und mehr.\nStandardsuche: YouTube Music. Nutze `-p ` oder Inline-Präfix wie `sp: blinding lights`.", "player": "Erstelle ein interaktives Wiedergabe-Kontrollfeld mit Live-Fortschritt.", "playnext": "Wie $prefixplay, fügt das Ergebnis aber an den Anfang der Warteschlange hinzu.", "radio": "Spiele einen Radiosender. Nutze `$prefixradio list`, um alle Sender zu durchsuchen.", @@ -363,7 +363,11 @@ "loadFailed": "Track konnte nicht geladen werden.", "unexpectedResult": "Unerwartetes Ergebnis vom Track-Lader.", "loadError": "Beim Laden des Tracks ist ein Fehler aufgetreten.", - "searchingProvider": "Suche auf {{provider}}..." + "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).", + "bilibiliError": "❌ Bilibili: {{message}}", + "bilibiliDisabled": "❌ Bilibili-Wiedergabe ist deaktiviert (config.json → bilibili.enabled)." }, "playnext": { "searching": "🔍 Suche..." diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index 67376ed..504d1ee 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -59,7 +59,7 @@ "lyrics": "Display synced lyrics from NodeLink.", "np": "Request the name and url of the currently playing song.", "pause": "Pause the playback in your voice channel.", - "play": "Play a song or playlist from a URL or search query.\nSupports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and more.\nDefault search: YouTube Music. Use `-p ` or inline prefix e.g. `sp: blinding lights`.", + "play": "Play a song or playlist from a URL or search query.\nSupports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bilibili, and more.\nDefault search: YouTube Music. Use `-p ` or inline prefix e.g. `sp: blinding lights`.", "player": "Create an interactive player control panel with live progress.", "playnext": "Same as $prefixplay but adds the result to the top of the queue.", "radio": "Play a radio station. Use `$prefixradio list` to browse all stations.", @@ -471,7 +471,11 @@ "loadFailed": "Failed to load track.", "unexpectedResult": "Unexpected result from track loader.", "loadError": "An error occurred while loading the track.", - "searchingProvider": "Searching {{provider}}..." + "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).", + "bilibiliError": "❌ Bilibili: {{message}}", + "bilibiliDisabled": "❌ Bilibili playback is disabled (config.json → bilibili.enabled)." }, "playnext": { "searching": "🔍 Searching..." diff --git a/storage/locales/bot/pt-BR.json b/storage/locales/bot/pt-BR.json index 0e321ec..2635798 100644 --- a/storage/locales/bot/pt-BR.json +++ b/storage/locales/bot/pt-BR.json @@ -58,7 +58,7 @@ "lyrics": "Exiba letras sincronizadas do NodeLink.", "np": "Solicite o nome e a URL da música que está tocando atualmente.", "pause": "Pause a reprodução no seu canal de voz.", - "play": "Toque uma música ou playlist a partir de uma URL ou consulta de busca.\nSuporta YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal e mais.\nBusca padrão: YouTube Music. Use `-p ` ou prefixo inline como `sp: blinding lights`.", + "play": "Toque uma música ou playlist a partir de uma URL ou consulta de busca.\nSuporta YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bilibili e mais.\nBusca padrão: YouTube Music. Use `-p ` ou prefixo inline como `sp: blinding lights`.", "player": "Crie um painel de controle interativo com progresso ao vivo.", "playnext": "Igual ao $prefixplay, mas adiciona o resultado ao topo da fila.", "radio": "Toque uma estação de rádio. Use `$prefixradio list` para ver todas as estações.", @@ -363,7 +363,11 @@ "loadFailed": "Falha ao carregar a faixa.", "unexpectedResult": "Resultado inesperado do carregador de faixas.", "loadError": "Ocorreu um erro ao carregar a faixa.", - "searchingProvider": "Buscando no {{provider}}..." + "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).", + "bilibiliError": "❌ Bilibili: {{message}}", + "bilibiliDisabled": "❌ A reprodução do Bilibili está desativada (config.json → bilibili.enabled)." }, "playnext": { "searching": "🔍 Buscando..." diff --git a/storage/locales/bot/tr.json b/storage/locales/bot/tr.json index 02b890f..11e5ff1 100644 --- a/storage/locales/bot/tr.json +++ b/storage/locales/bot/tr.json @@ -59,7 +59,7 @@ "lyrics": "NodeLink'ten senkronize şarkı sözlerini görüntüleyin.", "np": "Şu an çalan şarkının adını ve URL'sini isteyin.", "pause": "Ses kanalınızdaki çalmayı duraklatın.", - "play": "Bir URL veya arama sorgusundan şarkı veya çalma listesi çalın.\nYouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal ve daha fazlasını destekler.\nVarsayılan arama: YouTube Music. `-p ` veya `sp: blinding lights` gibi satır içi önek kullanın.", + "play": "Bir URL veya arama sorgusundan şarkı veya çalma listesi çalın.\nYouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bilibili ve daha fazlasını destekler.\nVarsayılan arama: YouTube Music. `-p ` veya `sp: blinding lights` gibi satır içi önek kullanın.", "player": "Canlı ilerleme çubuğlu etkileşimli bir oynatıcı kontrol paneli oluşturun.", "playnext": "$prefixplay ile aynıdır, ancak sonucu kuyruğun en üstüne ekler.", "radio": "Bir radyo istasyonu çalın. Tüm istasyonları görüntülemek için `$prefixradio list` kullanın.", @@ -460,7 +460,11 @@ "loadFailed": "Parça yüklenemedi.", "unexpectedResult": "Parça yükleyiciden beklenmeyen sonuç.", "loadError": "Parça yüklenirken bir hata oluştu.", - "searchingProvider": "{{provider}} aranıyor..." + "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).", + "bilibiliError": "❌ Bilibili: {{message}}", + "bilibiliDisabled": "❌ Bilibili oynatma devre dışı (config.json → bilibili.enabled)." }, "playnext": { "searching": "🔍 Aranıyor..."