mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-10-02 21:12:49 +08:00
Major bug fixes and corner-case hardening across the backend, plus a
comprehensive feature test suite. All 94 unit tests + 51 integration
tests pass against a local TS3 server.
Lifecycle & state consistency
-----------------------------
- Bug A: startBot() now wraps connect() in a 15s deadline. A hung TS
handshake no longer blocks the /start HTTP call forever; the failing
instance is torn down and the caller gets a clean 500.
- Bug B: executeCommand rejects audio-dispatching commands (play, add,
next, skip, prev, playlist, album, fm) when the bot is disconnected.
Config-only commands (vol, mode, clear, stop, queue, now, lyrics)
still work so the UI stays usable while offline.
- Bug C: the tsClient 'disconnected' handler always clears player state
now, even when connect() never completed. A separate disconnectEmitted
flag guards duplicate external event emission. Previously an orphaned
connect attempt that idle-timed-out would leave playing=true forever.
- resolveAndPlay re-checks this.connected AFTER the URL-resolve await so
a stop() during the network call can't spawn ffmpeg on a disconnected
bot.
- connect() throws if disconnect() fired during the handshake await,
preventing a concurrent stop from being overwritten by a late connected
flag flip.
- startBot always disconnects the outgoing BotInstance before creating
a replacement, covering the mid-handshake case where isConnected()
still returned false but the library client was live.
- startBot now reuses the stored identity so server groups granted to
the bot survive restarts (was regenerating a fresh UID each time).
WebSocket reliability
---------------------
- BotManager extends EventEmitter and emits 'botInstance' whenever a
new instance is created. websocket.ts listens and re-attaches its
stateChange / connected / disconnected listeners immediately, fixing
the bug where player-bar UI never updated until manual refresh.
- attachedBots map now stores the BotInstance reference and detaches
stale listeners when the instance is replaced. Safety-net interval
(5s) also reconciles to catch anything missed.
- removeBot emits 'botInstanceRemoved' -> WS broadcasts a new
{type:"botRemoved", botId} message. Client drops the bot from its
local store instead of showing it as permanently offline.
HTTP input validation
---------------------
- /volume rejects non-number, NaN, Infinity, and out-of-range values
with a proper 400 instead of a 200 OK wrapping a usage-text string.
- /mode rejects anything not in {seq, loop, random, rloop} with 400.
- /seek rejects NaN / Infinity / negative (previously NaN slipped
through typeof==="number" and poisoned seekOffset).
- /play-at validates index < queue.size() BEFORE stopping current
playback (was silently killing the current song on invalid input).
- /play, /add, /playlist, /play-by-id, /add-by-id, /play-playlist
all honour platform=youtube now (previously fell through to netease
and silently played the wrong platform).
YouTube made truly optional
---------------------------
- Lazy checkYtDlpAvailable() runs `yt-dlp --version` once, caches only
positive results so users can install yt-dlp mid-run and have it
picked up without a restart.
- getAuthStatus() returns loggedIn=false with nickname
"YouTube (yt-dlp not installed)" when the binary is missing. UI can
grey out YouTube instead of silently returning empty searches.
- findYtDlp() picks .exe on win32 and bare binary elsewhere.
- /auth/status?platform=youtube now routes to the YouTube provider
instead of falling through to NetEase and leaking the NetEase
user's nickname + avatar.
- /auth/cookie rejects platform=youtube with 400 instead of clobbering
the NetEase cookie entry.
- README documents yt-dlp install paths (bin/ local vs PATH) and adds
a dedicated "Optional: YouTube source" section.
Bot Selector UI
---------------
- New power button in each row of the dropdown with play-state-aware
styling: disabled + wait-cursor during API call, green highlight when
connected, greys out when the bot is offline.
- Dropdown always visible when >=1 bot exists, bigger font + padding.
Queue correctness
-----------------
- PlayQueue.remove(current) now decrements currentIndex so next() in
sequential mode advances to the shifted song. Previously removing
the currently-playing track silently skipped the next track because
current() falsely reported it as active and next() then incremented
past it.
Vote-skip hardening
-------------------
- cmdVote: needed threshold is Math.max(1, ceil(users/2)) so a single
voter in an empty channel can't unanimously pass a vote with
needed=0.
- resolveAndPlay clears voteSkipUsers on every new track load so votes
can't leak across songs via cmdPlay/cmdPlaylist/cmdAlbum/cmdFm paths.
cmdAdd parity
-------------
- cmdAdd auto-plays the newly-added song if the player was idle,
matching /api/player/:id/add-by-id behaviour. Previously add'ing to
an empty queue on a connected+idle bot silently enqueued without
starting playback.
Test suite
----------
- scripts/test_full_feature.py — 51 tests across 10 groups exercising
every HTTP endpoint, WebSocket broadcasts, all music providers, bot
lifecycle, disconnected-state corners, seek validation, input
validation, and the main race conditions. Captures and restores the
target bot's initial state. Resilient to TS3 anti-flood via retry
with exponential backoff. Runs against a real local TS3 server.
- scripts/test_rapid_cycle.py — Bugs A/B/C regressions
- scripts/test_corner_cases.py — disconnect-during-connect race, config
commands while disconnected, etc.
- scripts/test_more_corners.py — resolveAndPlay race, seek NaN
- scripts/test_power_button.py — E2E for the new power button
- scripts/test_bot_remove.py — E2E for WS botRemoved broadcast
- scripts/test_playbar.py — player bar auto-show regression (updated
to restore bot state on exit)
- scripts/test_multibot.py — two-bot concurrent playback monitor
- src/audio/queue.test.ts — 4 new vitest cases for remove() edge cases
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
233 lines
6.2 KiB
TypeScript
233 lines
6.2 KiB
TypeScript
import { execFile } from "node:child_process";
|
|
import { promisify } from "node:util";
|
|
import { existsSync } from "node:fs";
|
|
import { fileURLToPath } from "node:url";
|
|
import { dirname, join } from "node:path";
|
|
import type {
|
|
MusicProvider,
|
|
Song,
|
|
SongWithUrl,
|
|
Playlist,
|
|
Album,
|
|
SearchResult,
|
|
LyricLine,
|
|
QrCodeResult,
|
|
AuthStatus,
|
|
} from "./provider.js";
|
|
|
|
const execFileAsync = promisify(execFile);
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
|
|
/** Resolve the yt-dlp binary path. Checks the project bin/ dir first, then PATH. */
|
|
function findYtDlp(): string {
|
|
const exe = process.platform === "win32" ? "yt-dlp.exe" : "yt-dlp";
|
|
const candidates = [
|
|
join(__dirname, "..", "..", "bin", exe),
|
|
join(__dirname, "..", "..", "bin", "yt-dlp"),
|
|
exe,
|
|
];
|
|
for (const c of candidates) {
|
|
// Absolute/relative paths: only return if the file exists.
|
|
// Bare names: return and let execFile resolve via PATH.
|
|
const isBinPath = c.includes(join("bin", "yt-dlp"));
|
|
if (!isBinPath || existsSync(c)) return c;
|
|
}
|
|
return exe;
|
|
}
|
|
|
|
/**
|
|
* Availability check for yt-dlp. Runs `yt-dlp --version` and caches only
|
|
* the positive result — if the binary is missing, subsequent calls retry
|
|
* so the user can install yt-dlp while the server is running and pick it
|
|
* up without a restart. Used by getAuthStatus() so the UI can reflect
|
|
* whether YouTube is actually usable.
|
|
*/
|
|
let cachedAvailable = false;
|
|
let pendingCheck: Promise<boolean> | null = null;
|
|
async function checkYtDlpAvailable(): Promise<boolean> {
|
|
if (cachedAvailable) return true;
|
|
if (pendingCheck) return pendingCheck;
|
|
pendingCheck = (async () => {
|
|
try {
|
|
await execFileAsync(findYtDlp(), ["--version"], {
|
|
timeout: 5_000,
|
|
maxBuffer: 1024,
|
|
});
|
|
cachedAvailable = true;
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
} finally {
|
|
pendingCheck = null;
|
|
}
|
|
})();
|
|
return pendingCheck;
|
|
}
|
|
|
|
/** Force re-detection on the next call (for tests). */
|
|
export function resetYtDlpAvailabilityCache(): void {
|
|
cachedAvailable = false;
|
|
pendingCheck = null;
|
|
}
|
|
|
|
async function runYtDlp(args: string[], timeoutMs = 30_000): Promise<string> {
|
|
const binary = findYtDlp();
|
|
const env = { ...process.env };
|
|
if (process.env.HTTPS_PROXY || process.env.HTTP_PROXY) {
|
|
// yt-dlp respects these env vars natively
|
|
}
|
|
const { stdout } = await execFileAsync(binary, args, {
|
|
timeout: timeoutMs,
|
|
env,
|
|
maxBuffer: 10 * 1024 * 1024,
|
|
});
|
|
return stdout;
|
|
}
|
|
|
|
interface YtDlpEntry {
|
|
id: string;
|
|
title: string;
|
|
uploader?: string;
|
|
channel?: string;
|
|
duration?: number;
|
|
thumbnail?: string;
|
|
webpage_url?: string;
|
|
url?: string;
|
|
entries?: YtDlpEntry[];
|
|
_type?: string;
|
|
}
|
|
|
|
function entryToSong(entry: YtDlpEntry): Song {
|
|
return {
|
|
id: entry.id ?? "",
|
|
name: entry.title ?? "Unknown",
|
|
artist: entry.uploader ?? entry.channel ?? "YouTube",
|
|
album: "YouTube",
|
|
duration: Math.round(entry.duration ?? 0),
|
|
coverUrl: entry.thumbnail ?? "",
|
|
platform: "youtube",
|
|
};
|
|
}
|
|
|
|
export class YouTubeProvider implements MusicProvider {
|
|
readonly platform = "youtube" as const;
|
|
private quality = "bestaudio";
|
|
|
|
async search(query: string, limit = 5): Promise<SearchResult> {
|
|
try {
|
|
const raw = await runYtDlp([
|
|
`ytsearch${limit}:${query}`,
|
|
"--dump-json",
|
|
"--flat-playlist",
|
|
"--no-warnings",
|
|
"--quiet",
|
|
]);
|
|
const lines = raw.trim().split("\n").filter(Boolean);
|
|
const songs: Song[] = lines.map((line) => {
|
|
const entry = JSON.parse(line) as YtDlpEntry;
|
|
return entryToSong(entry);
|
|
});
|
|
return { songs, playlists: [], albums: [] };
|
|
} catch {
|
|
return { songs: [], playlists: [], albums: [] };
|
|
}
|
|
}
|
|
|
|
async getSongUrl(songId: string): Promise<string | null> {
|
|
try {
|
|
const url = `https://www.youtube.com/watch?v=${songId}`;
|
|
const raw = await runYtDlp([
|
|
url,
|
|
"--get-url",
|
|
"-f",
|
|
"bestaudio[ext=webm]/bestaudio[ext=m4a]/bestaudio",
|
|
"--no-warnings",
|
|
"--quiet",
|
|
], 45_000);
|
|
const audioUrl = raw.trim().split("\n")[0];
|
|
return audioUrl || null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
setQuality(quality: string): void {
|
|
this.quality = quality;
|
|
}
|
|
|
|
getQuality(): string {
|
|
return this.quality;
|
|
}
|
|
|
|
async getSongDetail(songId: string): Promise<Song | null> {
|
|
try {
|
|
const url = `https://www.youtube.com/watch?v=${songId}`;
|
|
const raw = await runYtDlp([url, "--dump-json", "--no-warnings", "--quiet"]);
|
|
const entry = JSON.parse(raw.trim()) as YtDlpEntry;
|
|
return entryToSong(entry);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async getPlaylistSongs(playlistId: string): Promise<Song[]> {
|
|
try {
|
|
const url = playlistId.startsWith("http")
|
|
? playlistId
|
|
: `https://www.youtube.com/playlist?list=${playlistId}`;
|
|
const raw = await runYtDlp([
|
|
url,
|
|
"--dump-json",
|
|
"--flat-playlist",
|
|
"--no-warnings",
|
|
"--quiet",
|
|
], 60_000);
|
|
const lines = raw.trim().split("\n").filter(Boolean);
|
|
return lines.map((line) => entryToSong(JSON.parse(line) as YtDlpEntry));
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
async getRecommendPlaylists(): Promise<Playlist[]> {
|
|
return [];
|
|
}
|
|
|
|
async getAlbumSongs(_albumId: string): Promise<Song[]> {
|
|
return [];
|
|
}
|
|
|
|
async getLyrics(_songId: string): Promise<LyricLine[]> {
|
|
return [];
|
|
}
|
|
|
|
async getQrCode(): Promise<QrCodeResult> {
|
|
return { qrUrl: "", key: "" };
|
|
}
|
|
|
|
async checkQrCodeStatus(
|
|
_key: string
|
|
): Promise<"waiting" | "scanned" | "confirmed" | "expired"> {
|
|
return "expired";
|
|
}
|
|
|
|
setCookie(_cookie: string): void {}
|
|
getCookie(): string { return ""; }
|
|
|
|
async getAuthStatus(): Promise<AuthStatus> {
|
|
// YouTube has no login concept via yt-dlp, so "loggedIn" here means
|
|
// "yt-dlp binary is reachable and responds to --version". The UI can
|
|
// use this flag to grey out YouTube when the optional dependency is
|
|
// missing, instead of silently returning empty search results.
|
|
const available = await checkYtDlpAvailable();
|
|
if (available) {
|
|
return { loggedIn: true, nickname: "YouTube (yt-dlp)" };
|
|
}
|
|
return {
|
|
loggedIn: false,
|
|
nickname: "YouTube (yt-dlp not installed)",
|
|
};
|
|
}
|
|
}
|