mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-10-01 20:42:50 +08:00
fix(player): WinHTTP fallback for /jdymusic/ CDN that drops Node TCP
The old jdymusic CDN (e.g. m701/m801.music.126.net/.../jdymusic/obj/...) intermittently drops connections from Node's HTTP stack — even with a browser UA — while the same URL fetched via WinHTTP works. Newer paths (/jd-musicrep-ts/, /ymusic/) do not have this restriction. On Windows, dispatch /jdymusic/ URLs through `System.Net.WebClient` in PowerShell into a temp file, then run ffmpeg against the file. Other URLs and non-Windows platforms keep the direct ffmpeg + browser-UA path from the previous commit. Also fix buildFfmpegArgs to omit HTTP-only flags (-reconnect_*, -headers) when the input is a local file path — new ffmpeg builds reject these as "Option not found". stop() now also kills any in-flight PowerShell downloader and removes the temp dir, so cancellation is clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
9179780afb
commit
719ceae303
3 files changed
+344
-12
No files matched your search
+170
-11
@@ -1,7 +1,9 @@
|
||||
import { spawn, execSync, type ChildProcess } from "node:child_process";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { createRequire } from "node:module";
|
||||
import { accessSync, chmodSync, constants } from "node:fs";
|
||||
import { accessSync, chmodSync, constants, mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createOpusEncoder, PCM_FRAME_BYTES, type Encoder } from "./encoder.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
|
||||
@@ -52,28 +54,49 @@ function getFfmpegCommand(): string {
|
||||
const BROWSER_UA =
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
|
||||
|
||||
// Old jdymusic CDN paths (e.g. /jdymusic/obj/...) RST direct Node-stack
|
||||
// requests on Windows; same URL works when fetched via WinHTTP. Empirically,
|
||||
// /jd-musicrep-ts/ and /ymusic/ paths do not have this restriction.
|
||||
export function shouldUsePowerShellDownload(
|
||||
url: string,
|
||||
platform: string = process.platform,
|
||||
): boolean {
|
||||
return platform === "win32" && url.includes("/jdymusic/");
|
||||
}
|
||||
|
||||
export function cleanupTempDir(dir: string): void {
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// best-effort
|
||||
}
|
||||
}
|
||||
|
||||
export function buildFfmpegArgs(url: string, seekSeconds: number): string[] {
|
||||
const args: string[] = [];
|
||||
const isHttp = /^https?:\/\//i.test(url);
|
||||
|
||||
if (url.includes("bilivideo") || url.includes("bilibili")) {
|
||||
if (isHttp && (url.includes("bilivideo") || url.includes("bilibili"))) {
|
||||
args.push(
|
||||
"-headers",
|
||||
`Referer: https://www.bilibili.com\r\nUser-Agent: ${BROWSER_UA}\r\n`,
|
||||
);
|
||||
} else if (url.includes("music.126.net") || url.includes("music.163.com")) {
|
||||
} else if (isHttp && (url.includes("music.126.net") || url.includes("music.163.com"))) {
|
||||
args.push(
|
||||
"-headers",
|
||||
`Referer: https://music.163.com/\r\nUser-Agent: ${BROWSER_UA}\r\n`,
|
||||
);
|
||||
}
|
||||
|
||||
args.push(
|
||||
"-reconnect", "1",
|
||||
"-reconnect_streamed", "1",
|
||||
"-reconnect_delay_max", "30",
|
||||
"-reconnect_on_network_error", "1",
|
||||
"-reconnect_on_http_error", "4xx,5xx",
|
||||
);
|
||||
if (isHttp) {
|
||||
args.push(
|
||||
"-reconnect", "1",
|
||||
"-reconnect_streamed", "1",
|
||||
"-reconnect_delay_max", "30",
|
||||
"-reconnect_on_network_error", "1",
|
||||
"-reconnect_on_http_error", "4xx,5xx",
|
||||
);
|
||||
}
|
||||
if (seekSeconds > 0) args.push("-ss", String(seekSeconds));
|
||||
args.push("-i", url, "-f", "s16le", "-ar", "48000", "-ac", "2", "-acodec", "pcm_s16le", "-");
|
||||
|
||||
@@ -111,6 +134,8 @@ export class AudioPlayer extends EventEmitter {
|
||||
private static readonly MAX_CONSECUTIVE_FAILURES = 3;
|
||||
private healthyFrames = 0;
|
||||
private static readonly HEALTHY_FRAME_RESET = 50; // ~1 second of audio
|
||||
private downloader: ChildProcess | null = null;
|
||||
private currentTempDir: string | null = null;
|
||||
|
||||
constructor(logger: Logger) {
|
||||
super();
|
||||
@@ -137,6 +162,11 @@ export class AudioPlayer extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldUsePowerShellDownload(url)) {
|
||||
this.playViaPowerShellDownload(url, seekSeconds, currentSessionId);
|
||||
return;
|
||||
}
|
||||
|
||||
const args = buildFfmpegArgs(url, seekSeconds);
|
||||
|
||||
const ffmpegBin = getFfmpegCommand();
|
||||
@@ -183,6 +213,124 @@ export class AudioPlayer extends EventEmitter {
|
||||
this.startFrameLoop();
|
||||
}
|
||||
|
||||
private playViaPowerShellDownload(url: string, seekSeconds: number, sessionId: number): void {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "tsbot-jdymusic-"));
|
||||
const tempFile = join(tempDir, "song.audio");
|
||||
this.currentTempDir = tempDir;
|
||||
|
||||
const psScript = [
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
"$ProgressPreference = 'SilentlyContinue'",
|
||||
"$wc = New-Object System.Net.WebClient",
|
||||
"$wc.Headers.Add('User-Agent', $env:DL_UA)",
|
||||
"$wc.Headers.Add('Referer', $env:DL_REFERER)",
|
||||
"$wc.DownloadFile($env:DL_URL, $env:DL_OUT)",
|
||||
].join("; ");
|
||||
|
||||
this.logger.debug({ sessionId, tempFile }, "Downloading via PowerShell (jdymusic CDN)");
|
||||
|
||||
const ps = spawn(
|
||||
"powershell",
|
||||
["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", psScript],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
DL_URL: url,
|
||||
DL_OUT: tempFile,
|
||||
DL_UA: BROWSER_UA,
|
||||
DL_REFERER: "https://music.163.com/",
|
||||
},
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
this.downloader = ps;
|
||||
|
||||
let stderrTail = "";
|
||||
ps.stderr!.on("data", (chunk: Buffer) => {
|
||||
stderrTail = (stderrTail + chunk.toString()).slice(-500);
|
||||
});
|
||||
|
||||
ps.on("exit", (code, signal) => {
|
||||
if (this.sessionId !== sessionId) {
|
||||
cleanupTempDir(tempDir);
|
||||
return;
|
||||
}
|
||||
this.downloader = null;
|
||||
if (code !== 0) {
|
||||
this.logger.warn({ code, signal, stderr: stderrTail }, "PowerShell download failed");
|
||||
this.spawnFailed = true;
|
||||
this.consecutiveFailures++;
|
||||
this.state = "idle";
|
||||
cleanupTempDir(tempDir);
|
||||
this.currentTempDir = null;
|
||||
this.emit("error", new Error(`PowerShell download exited ${code}`));
|
||||
return;
|
||||
}
|
||||
this.spawnFfmpegFromFile(tempFile, seekSeconds, sessionId);
|
||||
});
|
||||
|
||||
ps.on("error", (err) => {
|
||||
if (this.sessionId !== sessionId) return;
|
||||
this.downloader = null;
|
||||
this.spawnFailed = true;
|
||||
this.consecutiveFailures++;
|
||||
cleanupTempDir(tempDir);
|
||||
this.currentTempDir = null;
|
||||
this.emit("error", err);
|
||||
});
|
||||
|
||||
this.state = "playing";
|
||||
this.startFrameLoop();
|
||||
}
|
||||
|
||||
private spawnFfmpegFromFile(tempFile: string, seekSeconds: number, sessionId: number): void {
|
||||
if (this.sessionId !== sessionId) {
|
||||
if (this.currentTempDir) {
|
||||
cleanupTempDir(this.currentTempDir);
|
||||
this.currentTempDir = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const args = buildFfmpegArgs(tempFile, seekSeconds);
|
||||
const ffmpegBin = getFfmpegCommand();
|
||||
this.ffmpeg = spawn(ffmpegBin, args, { stdio: ["ignore", "pipe", "pipe"] });
|
||||
|
||||
const currentPid = this.ffmpeg.pid;
|
||||
if (currentPid) {
|
||||
globalActivePids.add(currentPid);
|
||||
this.logger.debug({ pid: currentPid, sessionId }, "FFmpeg spawned (from temp file)");
|
||||
}
|
||||
const tempDirToCleanup = this.currentTempDir;
|
||||
|
||||
this.ffmpeg.stdout!.on("data", (chunk: Buffer) => {
|
||||
if (this.sessionId !== sessionId) return;
|
||||
this.pcmBuffer = Buffer.concat([this.pcmBuffer, chunk]);
|
||||
if (this.pcmBuffer.length > AudioPlayer.BUFFER_HIGH_WATER && !this.ffmpegPaused && this.ffmpeg?.stdout) {
|
||||
this.ffmpeg.stdout.pause();
|
||||
this.ffmpegPaused = true;
|
||||
}
|
||||
});
|
||||
|
||||
this.ffmpeg.on("exit", (code, signal) => {
|
||||
if (currentPid) globalActivePids.delete(currentPid);
|
||||
this.logger.info({ pid: currentPid, code, signal }, "FFmpeg exited");
|
||||
if (this.sessionId === sessionId) {
|
||||
this.ffmpeg = null;
|
||||
if (this.currentTempDir === tempDirToCleanup) this.currentTempDir = null;
|
||||
}
|
||||
if (tempDirToCleanup) cleanupTempDir(tempDirToCleanup);
|
||||
});
|
||||
|
||||
this.ffmpeg.on("error", (err) => {
|
||||
if (this.sessionId === sessionId) {
|
||||
this.spawnFailed = true;
|
||||
this.consecutiveFailures++;
|
||||
this.emit("error", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
// 3. 递增 ID 是最有效的逻辑“隔离墙”
|
||||
this.sessionId++;
|
||||
@@ -194,13 +342,24 @@ export class AudioPlayer extends EventEmitter {
|
||||
if (this.ffmpeg) {
|
||||
const procToKill = this.ffmpeg;
|
||||
const pidToKill = procToKill.pid;
|
||||
this.ffmpeg = null;
|
||||
this.ffmpeg = null;
|
||||
|
||||
if (pidToKill) {
|
||||
this.forceCleanup(procToKill, pidToKill);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.downloader) {
|
||||
const ps = this.downloader;
|
||||
this.downloader = null;
|
||||
try { ps.kill("SIGTERM"); } catch { /* already gone */ }
|
||||
}
|
||||
|
||||
if (this.currentTempDir) {
|
||||
cleanupTempDir(this.currentTempDir);
|
||||
this.currentTempDir = null;
|
||||
}
|
||||
|
||||
this.ffmpegPaused = false;
|
||||
this.spawnFailed = false;
|
||||
this.state = "idle";
|
||||
|
||||
Reference in new issue
Block a user