Compare commits

...
23 Commits
Author SHA1 Message Date
TIANYAO ZHANG 20283aa6a7 fix(netease): bound playlist count lookups and prepare v1.16.2 2026-11-28 22:04:15 +08:00
TIANYAO ZHANG dfa15fd5a5 Merge pull request #203: count visible cloud playlist tracks
Closes #201

# Conflicts:
#	src/music/netease.test.ts
2026-11-28 21:58:56 +08:00
TIANYAO ZHANG 19c9a32850 Merge pull request #202: load complete NetEase playlists
Closes #200
2026-11-28 21:58:41 +08:00
yhxglsa2016 39b94ffdf2 fix(netease): count visible cloud tracks in playlist cards
Use playlist track IDs for account-specific counts when cloud tracks are reported. Keep other cards available if an individual detail lookup fails.
2026-11-28 12:18:09 +08:00
yhxglsa2016 a44324b748 fix(netease): warn about missing playlist track details
After all batches succeed, log one warning with the playlist ID and expected, matched, and missing track counts. Return the matched tracks in playlist order.
2026-11-28 12:08:19 +08:00
yhxglsa2016 11081ec4f8 fix(netease): use eapi for playlist track details 2026-11-28 11:51:20 +08:00
yhxglsa2016 0b3bb0c3dd fix(netease): load playlists beyond 1000 tracks 2026-11-28 09:49:35 +08:00
TIANYAO ZHANG fc4d472685 Merge pull request #199 from ZHANGTIANYAO1/fix/open-issues-v1161
fix(playback): 修复断流续播、队列推进和平台取流错误,准备 v1.16.1
2026-11-18 18:40:20 +08:00
TIANYAO ZHANG b0393b42b2 fix(playback): preserve the current queue until direct play starts 2026-11-18 18:37:50 +08:00
TIANYAO ZHANG de6b050646 fix(playback): retain the successful quality when renewing a stream 2026-11-18 18:37:10 +08:00
TIANYAO ZHANG 20ad2d44a7 fix(qq): check collection playback with the room account 2026-11-18 18:37:10 +08:00
TIANYAO ZHANG 2db8c4cc05 fix(web): keep FM request timing scoped to its bot and result 2026-11-18 18:36:05 +08:00
TIANYAO ZHANG f965b70c22 chore(release): prepare v1.16.1 playback fixes 2026-11-18 18:33:16 +08:00
TIANYAO ZHANG 135ff0ae0e fix(playback): resume interrupted finite music streams 2026-11-18 18:31:46 +08:00
TIANYAO ZHANG d130652279 fix(teamspeak): resume only on arrivals in the bot channel 2026-11-18 18:31:19 +08:00
TIANYAO ZHANG e5470b6b78 fix(qq): verify sidecar ports and validate batch playback results 2026-11-18 18:31:19 +08:00
TIANYAO ZHANG 5c2a9468bd fix(web): preserve playback on invalid queue selections 2026-11-18 18:22:50 +08:00
TIANYAO ZHANG afb1cd7c14 fix(playback): skip blocked providers while advancing mixed queues 2026-11-18 18:22:50 +08:00
TIANYAO ZHANG 0adf21c566 fix(playback): preserve active playback and report actual start failures 2026-11-18 18:21:08 +08:00
TIANYAO ZHANG 23b36e2019 test(bilibili): check recovery request context 2026-11-18 18:21:08 +08:00
TIANYAO ZHANG d0e1422af7 fix(chat): report failed starts for queue and collection commands 2026-11-18 18:21:08 +08:00
TIANYAO ZHANG 1b57af6722 fix(bilibili): rotate CDN hosts during stream recovery 2026-11-18 18:16:47 +08:00
TIANYAO ZHANG fbc12aa11b fix(music): align QQ stream requests and surface provider failures 2026-11-18 18:16:47 +08:00
30 changed files with 1890 additions and 540 deletions

No files matched your search

+23 -3
View File
@@ -399,6 +399,8 @@ QQ 音源启用时,`QQ_MUSIC_MANAGED_SESSION` 默认为 `1`。在 **设置 →
| **已存队列** | 保存当前队列为清单、加载(替换)/ 追加 / 删除已保存清单(仅在管理员开启「保存/加载播放清单」后出现) |
| **设置** | 账户(修改自己密码) / 主题切换 / 机器人管理 / 行为设置(空闲超时、频道无人自动暂停、保存/加载播放清单、单曲直接播放不清空队列) / 多平台账号登录(网易云 / QQ / 酷狗 / B站) / 音质选择 / 命令前缀 / 用户管理(仅管理员,含成员能力与机器人白名单)/ 操作审计(仅管理员) |
网易云歌单卡片的曲目数包含当前网易云账号可见的云盘歌曲。含云盘曲目的歌单若暂时无法取得详情,卡片会显示网易云列表返回的数量。
### TeamSpeak 文字命令
在 TeamSpeak 频道中发送文字消息控制机器人:
@@ -423,7 +425,7 @@ QQ 音源启用时,`QQ_MUSIC_MANAGED_SESSION` 默认为 `1`。在 **设置 →
| `!queue` | 查看播放队列 |
| `!remove <位置>` | 从队列中删除指定位置的歌曲(位置从 1 开始,见 `!queue`) |
| `!mode <seq\|loop\|random\|rloop>` | 切换播放模式 |
| `!playlist <歌单名或ID>` | 加载歌单(支持名称模糊搜索和 ID;Jellyfin 歌单 GUID 也可直接粘贴) |
| `!playlist <歌单名或ID>` | 加载歌单(支持名称模糊搜索和 ID;Jellyfin 歌单 GUID 也可直接粘贴)。超过 1000 首的网易云歌单会按原顺序分批加载,网页歌单详情和「播放全部」同样支持 |
| `!playlist -q <歌单名>` | 从 QQ 音乐搜索并加载歌单 |
| `!playlist <歌单链接>` | 直接粘贴网易云 / QQ 音乐 / YouTube 歌单链接加载,平台由链接自动识别,无需加 `-q` 等标志;也可直接粘贴 App 的分享文案或短链(`163cn.tv`、`c6.y.qq.com`) |
| `!album <专辑名或ID>` | 加载专辑(支持名称搜索 / 数字 ID / Jellyfin GUID) |
@@ -905,6 +907,10 @@ OAuth 相关端点:`/api/spotify/login`、`/api/spotify/callback`、`/api/spot
## 常见问题
**点歌时提示网易云 `-460` 或酷狗 `20028` 怎么办?**
网易云 `-460` 表示上游拒绝本次取流,可稍后用同一首歌重试。酷狗 `20028` 表示平台要求验证,请在酷狗检查账号状态。自动切歌时,机器人会在本次切歌中跳过要求验证或已限制请求的音源,并尝试队列里的其他音源。反馈时提供机器人版本、音源、歌曲 ID、时间点和错误码即可。
**Q:支持 TeamSpeak 6 Server 吗?**
A:支持。本项目内置 TS3/TS6 双协议支持,连接时会自动检测服务器类型。如果自动检测失败(例如 Query 端口被防火墙屏蔽),可以在创建机器人时手动指定 `serverProtocol: "ts6"`。TS6 Server 的 HTTP Query API(端口 10080)也已适配,需要时可配置 `ts6ApiKey`。
@@ -927,7 +933,7 @@ A:使用 `!move <频道名>` 命令,或在设置页面创建机器人时指
A:可以。在设置页面创建多个实例,分别连接不同的 TS 服务器或频道。
**Q:端口 3200 被占用?**
A:QQ 音乐 API 启动时会监听 `config.json` 里的 `qqMusicApiPort`(默认 **3200**),客户端也用同一个端口发请求,二者始终一致。如果之前的进程还在运行,程序会自动复用。如需改端口,改 `qqMusicApiPort` 后重启即可;如需重启可手动结束 `node` 进程。
A:QQ 音乐 API 使用 `config.json` 的 `qqMusicApiPort`(默认 **3200**)。程序会验证已在该端口监听的 QQ 音乐 API,再复用它。如果端口被 WebUI、端口转发或其他服务占用,请将 `qqMusicApiPort` 改为另一个空闲端口并重启。
**Q:日志里 `baseURL` 是 3200,但 QQ API 实际监听在 3300?(二维码不弹)**
A:这是**旧版本**(或过期的 `latest` Docker 镜像)才有的问题:早期实现用的上游包默认端口是 3300,而客户端 `baseURL` 已经是 3200,两边对不上,取二维码时就 `ECONNREFUSED 127.0.0.1:3200`。当前版本已把内嵌 QQ 音乐 API **强制绑定到 `qqMusicApiPort`(默认 3200)**,并在启动前把上游包读取的 `PORT` 环境变量对齐到该端口,二者不可能再错位。修复方法:**拉取最新镜像并重启**(`docker compose pull && docker compose up -d`),或用 `npm ci && npm run build` 更新到最新代码。启动后可在日志里确认那行 `QQ Music API started`,其 `port` 字段就是实际监听端口。
@@ -993,7 +999,21 @@ A:本项目内置 `/login` 限流(每 IP 每分钟 5 次),但生产部
> 完整历史请查看 [git log](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/commits/main) 或 [Releases](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/releases)。这里只列出重要变更和面向用户的破坏性改动。
### 最新版本 — v1.16.0:播放可靠性、音乐账号与 OpenProtocol
### 最新版本 — v1.16.2 网易云歌单加载与计数修复
- 超过 1000 首的网易云歌单按原顺序分批加载,网页详情、「播放全部」与 `!playlist` 均可读取完整歌单。缺失的歌曲详情会记录数量告警,某一批请求失败时会报错,避免把失败当作完整歌单。 [#202](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/202)
- 网易云音乐库、推荐和搜索中的歌单卡片按当前音乐账号可见的曲目计数,含云盘曲目时补查详情,避免漏算或重复相加。补查采用有限并发和 5 秒总时限;查询失败或超时时保留列表原有数量。 [#203](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/203)
无配置或数据库迁移。实时播放队列可超过 1000 首;保存队列的 1000 首上限保持不变。
### v1.16.1:播放、续播与队列修复
- B 站长视频中断后优先尝试其他 CDN。网易云、QQ 音乐和酷狗的完整曲目提前断流时,机器人会在有限次数内刷新地址,从已播位置续播。停止、切歌和断开连接会取消旧曲目的恢复。
- 网页加载空歌单、预检失败或选择无效队列位置时会保留原播放。进度条会跟随实际音频进度,切歌失败会显示原因。更新机器人头像时结束的短曲也能正常推进队列。
- QQ 音乐使用内嵌 API 支持的歌曲 MID 和音质参数。批量预检会区分上游错误与确实不可播的曲目,启动时也会识别 QQ 端口被其他服务占用。酷狗要求验证时会显示平台错误码。
- 机器人只会因听众进入自己所在的频道而恢复自动暂停的播放。混合队列遇到音源限制时,会继续尝试其他音源。
### v1.16.0:播放可靠性、音乐账号与 OpenProtocol
- **播放恢复**:临时取流失败会按上限重试,支持的音源可尝试更低音质。`playUrlRetries` 默认为 2,可设为 0–5,设为 0 时关闭重试。切歌、停止或断线会取消旧请求。网易云返回上游限制时会提示具体类型,并停止同一来源的连续重试。网易云播放请求的 User-Agent 与登录客户端配置一致。 [#185](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/185) · [#190](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/190)
- **B 站**:点播链接保留分 P 参数,修复部分 CDN 的 403。 [#191](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/191)
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "tsmusicbot",
"version": "1.16.0",
"version": "1.16.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "tsmusicbot",
"version": "1.16.0",
"version": "1.16.2",
"license": "MIT",
"dependencies": {
"@discordjs/opus": "^0.10.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "tsmusicbot",
"version": "1.16.0",
"version": "1.16.2",
"description": "TeamSpeak music bot with NetEase Cloud Music and QQ Music support",
"type": "module",
"engines": {
+2 -16
View File
@@ -42,22 +42,8 @@ export function decideOccupancyAction(
}
/**
* Whether a client-presence push event (a `clientEnter`) should trigger an
* auto-resume, WITHOUT consulting a clientlist query.
*
* Why event-driven: the full-client `clientlist`/`channellist` commands time
* out whenever ≥2 clients are connected to the server (a library limitation) —
* which is exactly the moment a listener returns. So occupancy cannot be
* re-queried to confirm the return; we must act on the push event itself.
* This is sound because the bot only ever auto-pauses while it is alone on the
* server (the sole state in which the occupancy query succeeds and pause
* fires). Therefore, while `autoPaused` is true, the only way occupancy can
* return is a fresh connection — delivered reliably as `clientEnter`.
*
* Gating on `autoPaused` (not merely "paused") guarantees we never revive a
* track the user paused by hand, and makes the bot's own `clientEnter` at
* connect a no-op (autoPaused is cleared to false on connect). This predicate
* NEVER pauses — pause stays on the authoritative clientlist path.
* Whether a confirmed arrival in the bot's channel should resume playback.
* An arrival does not resume a pause requested manually.
*/
export function shouldResumeOnReturn(
autoPaused: boolean,
+182 -2
View File
@@ -3,6 +3,8 @@ import { EventEmitter } from "node:events";
import { BotInstance } from "./instance.js";
import { AudioPlayer } from "../audio/player.js";
import { PlayQueue } from "../audio/queue.js";
import type { Platform, SongUrlRequestOptions } from "../music/provider.js";
import { BiliBiliProvider } from "../music/bilibili.js";
import { ManagedVoiceClientRegistry } from "./managed-voice-clients.js";
function deferred<T>() {
@@ -39,6 +41,7 @@ function makeBot() {
const tsClient = new EventEmitter() as any;
tsClient.getClientsInChannel = vi.fn(async () => [{ id: 1 }, { id: 2 }]);
tsClient.getClientId = () => 1;
tsClient.getChannelId = () => 3n;
tsClient.sendVoiceData = vi.fn();
tsClient.connect = vi.fn(async () => { tsClient.emit("connected"); });
tsClient.disconnect = vi.fn(() => { tsClient.emit("disconnected"); });
@@ -78,10 +81,165 @@ function cancel(bot: any, action: string) {
} else { bot.player.sessionId++; bot.player.state = "idle"; }
}
function makeMusicBot(platform: Platform = "netease") {
const bot = makeBot();
bot.queue.clear();
bot.queue.add({
id: "music", name: "Music", artist: "A", album: "", coverUrl: "",
platform, duration: 240, url: "https://cdn.test/old.wav",
});
bot.queue.playAt(0);
bot.player.elapsed = 60.28;
bot.effectiveDuration = 240;
bot.provider.getSongUrl.mockResolvedValue({ url: "https://cdn.test/new.wav" });
return bot;
}
beforeEach(() => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }));
afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
describe("finite music CDN recovery", () => {
it.each(["netease", "qq", "kugou"] as const)("resumes %s at the real playback position", async platform => {
const bot = makeMusicBot(platform);
bot.player.emit("trackEnd");
await flush();
expect(bot.player.play).toHaveBeenCalledWith("https://cdn.test/new.wav", 60.28, 240);
expect(bot.playNext).not.toHaveBeenCalled();
});
it.each([
["netease", "higher"],
["qq", "320"],
] as const)("renews %s with its successful %s quality only for that song", async (platform, fallback) => {
const bot = makeMusicBot(platform);
const song = bot.queue.current();
bot.voteSkipUsers = new Set();
bot.database = { addPlayHistory: vi.fn() };
bot.provider.getFallbackQualities = () => [fallback];
bot.provider.getSongUrl.mockImplementation(async (id: string, quality?: string, options?: SongUrlRequestOptions) => {
if (id === song.id && quality !== fallback) return null;
return { url: options?.refresh ? "https://cdn.test/renewed.wav" : "https://cdn.test/initial.wav" };
});
const initial = bot.resolveAndPlay(song);
await vi.advanceTimersByTimeAsync(120);
await expect(initial).resolves.toBe(true);
bot.player.state = "idle";
bot.player.elapsed = 60.28;
bot.player.emit("trackEnd");
await flush();
expect(bot.provider.getSongUrl).toHaveBeenLastCalledWith(song.id, fallback, { refresh: true });
expect(bot.player.play).toHaveBeenLastCalledWith("https://cdn.test/renewed.wav", 60.28, 240);
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(3);
bot.player.state = "idle";
bot.player.emit("trackEnd");
await flush();
expect(bot.provider.getSongUrl).toHaveBeenLastCalledWith(song.id, fallback, { refresh: true });
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(4);
// A different queue entry may carry a cached URL, but it has no prior
// quality evidence even when the URL happens to match.
const next = { ...song, id: "another" };
bot.queue.add(next);
bot.queue.playAt(1);
bot.player.state = "idle";
bot.player.emit("trackEnd");
await flush();
expect(bot.provider.getSongUrl).toHaveBeenLastCalledWith(next.id, undefined, { refresh: true });
});
it.each(["preview", "zero progress", "infinite duration", "local URL"])("does not recover %s streams", async condition => {
const bot = makeMusicBot();
if (condition === "preview") {
const song = bot.queue.current();
bot.currentStream = { song, url: song.url, isTrial: true };
}
if (condition === "zero progress") bot.player.elapsed = 0;
if (condition === "infinite duration") bot.effectiveDuration = Infinity;
if (condition === "local URL") bot.queue.current().url = "file:///example.wav";
bot.player.emit("trackEnd");
await flush();
expect(bot.provider.getSongUrl).not.toHaveBeenCalled();
expect(bot.playNext).toHaveBeenCalledTimes(1);
});
it("does not resume a full track into a preview URL", async () => {
const bot = makeMusicBot("qq");
bot.provider.getSongUrl.mockResolvedValue({ url: "https://cdn.test/preview.wav", trialDuration: 30 });
bot.player.emit("trackEnd");
await flush();
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(1);
expect(bot.player.play).not.toHaveBeenCalled();
expect(bot.playNext).toHaveBeenCalledTimes(1);
});
it("advances after exhausting the resume budget at the same position", async () => {
const bot = makeMusicBot("qq");
for (let i = 0; i < 4; i++) {
bot.player.state = "idle";
bot.player.emit("trackEnd");
await flush();
}
expect(bot.player.play).toHaveBeenCalledTimes(3);
expect(bot.playNext).toHaveBeenCalledTimes(1);
});
it.each(["stop", "disconnect"])("does not use a fresh URL after %s", async action => {
const bot = makeMusicBot("kugou");
const lookup = deferred<{ url: string }>();
bot.provider.getSongUrl.mockReturnValueOnce(lookup.promise);
bot.player.emit("trackEnd");
await flush();
expect(bot.provider.getSongUrl).toHaveBeenCalledTimes(1);
cancel(bot, action);
lookup.resolve({ url: "https://cdn.test/stale.wav" });
await flush();
expect(bot.player.play).not.toHaveBeenCalled();
expect(bot.playNext).not.toHaveBeenCalled();
});
});
describe("Bilibili recovery retries transient URL failures", () => {
it("rotates to untried CDN hosts after a long stream ends repeatedly at the same point", async () => {
const bot = makeBot();
const song = bot.queue.current();
song.url = "https://upos-primary.bilivideo.com/audio.m4s?deadline=1";
bot.player.elapsed = 2220;
bot.effectiveDuration = 4020;
song.duration = 4020;
const primary = "https://upos-primary.bilivideo.com/audio.m4s?deadline=2";
const backup = "https://upos-backup.bilivideo.com/audio.m4s?deadline=2";
const edge = "https://fixture.szbdyd.com/audio.m4s?deadline=2";
const provider = new BiliBiliProvider() as any;
provider.cidCache.set(song.id, 42);
provider.api = {
get: vi.fn(async () => ({
data: { data: { dash: { audio: [{ bandwidth: 192000, baseUrl: primary, backupUrl: [edge, backup] }] } } },
})),
};
bot.getProviderFor = () => provider;
bot.player.emit("trackEnd");
await flush();
expect(bot.player.play).toHaveBeenLastCalledWith(backup, 2220, 4020);
bot.player.state = "idle";
bot.player.emit("trackEnd");
await flush();
expect(bot.player.play).toHaveBeenLastCalledWith(edge, 2220, 4020);
// Once playback advances, a previously failed host can be used again.
bot.player.elapsed += 31;
bot.player.state = "idle";
bot.player.emit("trackEnd");
await flush();
expect(bot.player.play).toHaveBeenLastCalledWith(primary, 2251, 4020);
expect(bot.queue.current()).toBe(song);
expect(bot.playNext).not.toHaveBeenCalled();
});
it("keeps the same queue and seek through a null lookup, then resumes after one second", async () => {
const bot = makeBot();
const song = bot.queue.current();
@@ -291,7 +449,7 @@ describe("occupancy responses belong to the current request and connection", ()
const older = deferred<any[]>();
bot.tsClient.getClientsInChannel.mockReturnValueOnce(older.promise).mockResolvedValueOnce([]);
const first = bot.refreshOccupancy();
bot.tsClient.emit(event, { id: 2, targetChannelID: 3n });
bot.tsClient.emit(event, { id: 2, channelID: 3n, targetChannelID: 3n });
await flush();
older.resolve([{ id: 1 }]);
await first;
@@ -300,6 +458,28 @@ describe("occupancy responses belong to the current request and connection", ()
expect(bot.idleTimer).toBeNull();
});
it("does not resume for a client entering another channel", async () => {
const bot = makeBot();
bot.player.state = "paused";
bot.autoPaused = true;
bot.tsClient.getClientsInChannel.mockResolvedValue([]);
bot.tsClient.emit("clientEnter", { id: 2, channelID: 4n });
await flush();
expect(bot.player.getState()).toBe("paused");
expect(bot.autoPaused).toBe(true);
});
it("resumes when a listener moves into the channel and the occupancy query fails", async () => {
const bot = makeBot();
bot.player.state = "paused";
bot.autoPaused = true;
bot.tsClient.getClientsInChannel.mockResolvedValue([]);
bot.tsClient.emit("clientMoved", { id: 2, targetChannelID: 3n });
await flush();
expect(bot.player.getState()).toBe("playing");
expect(bot.autoPaused).toBe(false);
});
it("a listener's return cannot be undone by an earlier alone response", async () => {
const bot = makeBot();
bot.player.state = "paused";
@@ -307,7 +487,7 @@ describe("occupancy responses belong to the current request and connection", ()
const older = deferred<any[]>(), newer = deferred<any[]>();
bot.tsClient.getClientsInChannel.mockReturnValueOnce(older.promise).mockReturnValueOnce(newer.promise);
const first = bot.refreshOccupancy();
bot.tsClient.emit("clientEnter");
bot.tsClient.emit("clientEnter", { id: 2, channelID: 3n });
expect(bot.player.getState()).toBe("playing");
older.resolve([{ id: 1 }]);
await first;
+197 -4
View File
@@ -2,14 +2,14 @@ import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
import { EventEmitter } from "node:events";
import { BotInstance, COMMAND_DENIED_MESSAGE, spotifyPortsForBotId } from "./instance.js";
import type { BotInstanceOptions } from "./instance.js";
import { PlayQueue, PlayMode } from "../audio/queue.js";
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
import { AudioPlayer } from "../audio/player.js";
import { createDatabase, SHARED_QUEUE_OWNER } from "../data/database.js";
import { parseCommand } from "./commands.js";
import type { TS3TextMessage } from "../ts-protocol/client.js";
import type { SpotifyController } from "../music/spotify/controller.js";
import type { SpotifyOAuth } from "../music/spotify/spotify-oauth.js";
import type { MusicProvider } from "../music/provider.js";
import type { MusicProvider, PlayFailure } from "../music/provider.js";
import type { BotDatabase } from "../data/database.js";
import type { AvatarStore } from "../data/avatars.js";
import type { BotConfig } from "../data/config.js";
@@ -518,6 +518,101 @@ it("does not start a track whose URL resolved after the queue was cleared", asyn
expect(player.play).not.toHaveBeenCalled();
});
it.each(["netease", "spotify"])("keeps %s playback successful when saving history fails", async platform => {
const player = makePlayer();
const url = platform === "spotify" ? "spotify:track:abc" : "https://example.com/track";
const ctx = makeResolveCtx({ controller: makeController(), player, url });
ctx.database.addPlayHistory.mockImplementation(() => { throw new Error("Database temporarily unavailable"); });
expect(await resolveAndPlay.call(ctx, { ...spotifySong(), platform })).toBe(true);
expect(player.getState()).toBe("playing");
expect(ctx.emit).toHaveBeenCalledWith("stateChange");
expect(ctx.syncProfileToSong).toHaveBeenCalledTimes(1);
});
it("advances again when a track ends during a slow profile upload", async () => {
const player = Object.assign(new EventEmitter(), makePlayer(), {
getPlaybackSessionId: vi.fn(() => 1),
});
const ctx = makeResolveCtx({ controller: makeController(), player, url: "https://example.com/track" });
const queue = new PlayQueue();
for (const id of ["previous", "short", "following"]) {
queue.add({ ...spotifySong(), id, platform: "netease" });
}
queue.play();
ctx.queue = queue;
ctx.resumeInterruptedStream = vi.fn(async () => false);
ctx.resolveAndPlay = resolveAndPlay.bind(ctx);
ctx.playNext = playNext.bind(ctx);
ctx.sweepLocalAudio = vi.fn();
ctx.spotifyController = Object.assign(new EventEmitter(), { on: EventEmitter.prototype.on });
const profileStarted = deferred();
const finishProfile = deferred();
ctx.syncProfileToSong.mockImplementationOnce(() => {
profileStarted.resolve();
return finishProfile.promise;
});
setupPlayerEvents.call(ctx);
const advancing = ctx.playNext();
await profileStarted.promise;
try {
player.stop();
player.emit("trackEnd");
await new Promise<void>(resolve => setImmediate(resolve));
expect(queue.current()?.id).toBe("following");
} finally {
finishProfile.resolve();
await advancing;
}
});
it("reports the reason when the next track cannot be started", async () => {
const current = { ...spotifySong(), id: "next", platform: "netease" };
const ctx = {
connected: true,
queue: { current: () => current },
playNext: async (_maxRetries: number, report?: (failure: { message: string }) => void) => {
report?.({ message: "网易云暂时拒绝播放请求(-460),请稍后重试" });
return false;
},
};
expect(await BotInstance.prototype.skipToNext.call(ctx as unknown as BotInstance)).toEqual({
ok: false,
message: expect.stringContaining("-460"),
});
});
describe("queue advancement after a provider-wide failure", () => {
it.each([
["netease", "risk_control"],
["kugou", "provider_verification_required"],
] as const)("skips queued %s tracks without spending retries for other sources", async (platform, code) => {
const queue = new PlayQueue();
for (let i = 0; i < 8; i++) queue.add({ ...spotifySong(), id: String(i), platform });
const available = { ...spotifySong(), id: "available", platform: "qq" as const };
queue.add(available);
const ctx = {
connected: true,
queue,
player: makePlayer(),
voteSkipUsers: new Set<string>(),
resolveAndPlay: vi.fn(async (track: QueuedSong, onFailure: (failure: PlayFailure) => void) => {
if (track.platform === "qq") return true;
onFailure({ platform, songId: track.id, code, message: "Provider unavailable" });
return false;
}),
profileManager: { onSongChange: vi.fn(async () => {}) },
sweepLocalAudio: vi.fn(),
emit: vi.fn(),
};
expect(await playNext.call(ctx)).toBe(true);
expect(ctx.resolveAndPlay.mock.calls.map(([track]) => track.id)).toEqual(["0", "available"]);
expect(queue.current()?.id).toBe("available");
});
});
describe("BotInstance.resolveAndPlay — Spotify routing (C4)", () => {
it("routes a spotify song to controller.playTrack + player.playPcmStream, not player.play", async () => {
const controller = makeController();
@@ -1302,6 +1397,7 @@ const playSingleSong = BotInstance.prototype.playSingleSong as (
this: unknown,
song: unknown,
requesterName?: string,
onFailure?: (failure: PlayFailure, currentTrackContinues?: boolean) => void,
) => Promise<boolean>;
const loadSavedQueue = BotInstance.prototype.loadSavedQueue as (
this: unknown,
@@ -1344,7 +1440,10 @@ describe("BotInstance.playSingleSong / playKeepsQueue (#119)", () => {
isSameSong,
disableFmMode: vi.fn(),
sweepLocalAudio: vi.fn(),
resolveAndPlay: vi.fn(async () => true),
resolveAndPlay: vi.fn(async (_song, _onFailure, commitQueue?: () => void) => {
commitQueue?.();
return true;
}),
} as any;
}
@@ -1378,6 +1477,93 @@ describe("BotInstance.playSingleSong / playKeepsQueue (#119)", () => {
expect(ctx.queue.list().map((s: any) => s.id)).toEqual(["b"]);
expect(ctx.queue.current()?.id).toBe("b");
});
it.each([
[false, "new"], [false, "old"], [true, "new"], [true, "old"],
] as const)("retains the current queue and stream after a failed direct start (keep=%s, requested=%s)", async (keep, id) => {
const ctx = makeCtx(keep);
const current = song119("old");
ctx.queue.add(current);
ctx.queue.add(song119("following"));
ctx.queue.play();
ctx.player._play();
ctx.player.getPlaybackSessionId = () => 3;
ctx.resolveAndPlay.mockImplementation(async (_track: QueuedSong, onFailure?: (failure: PlayFailure) => void) => {
onFailure?.({ platform: "netease", songId: id, code: "unknown", message: "No URL" });
return false;
});
const failure = vi.fn();
expect(await playSingleSong.call(ctx, song119(id), "alice", failure)).toBe(false);
expect(ctx.queue.current()).toBe(current);
expect(ctx.queue.list().map((song: QueuedSong) => song.id)).toEqual(["old", "following"]);
expect(ctx.player.stop).not.toHaveBeenCalled();
expect(ctx.disableFmMode).not.toHaveBeenCalled();
expect(ctx.sweepLocalAudio).not.toHaveBeenCalled();
expect(failure).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message: "No URL" }), id === "old");
});
function makeRealStartCtx() {
const queue = new PlayQueue();
queue.add(song119("old"));
queue.add(song119("following"));
queue.play();
const player = Object.assign(new EventEmitter(), makePlayer(), {
resetFailures: vi.fn(), getPlaybackSessionId: () => 1,
});
const ctx = Object.assign(makeResolveCtx({ controller: makeController(), player, url: "" }), {
queue, player, withRequester, isSameSong, disableFmMode: vi.fn(),
sweepLocalAudio: vi.fn(), spotifyController: new EventEmitter(),
resumeInterruptedStream: async () => false,
});
ctx.playNext = BotInstance.prototype.playNext.bind(ctx);
ctx.resolveAndPlay = BotInstance.prototype.resolveAndPlay.bind(ctx);
setupPlayerEvents.call(ctx);
return ctx;
}
it("looks up a successful direct play once and commits the queue before status publication", async () => {
const ctx = makeRealStartCtx();
const getSongUrl = vi.fn(async () => ({ url: "https://example.test/new.mp3" }));
ctx.getProviderFor.mockReturnValue({ platform: "netease", getSongUrl });
ctx.emit.mockImplementation((event: string) => {
if (event === "stateChange") expect(ctx.queue.current()?.id).toBe("new");
});
expect(await playSingleSong.call(ctx, song119("new"), "alice")).toBe(true);
expect(getSongUrl).toHaveBeenCalledTimes(1);
expect(ctx.queue.current()).toMatchObject({ id: "new", requestedBy: "alice", url: "https://example.test/new.mp3" });
expect(ctx.emit).toHaveBeenCalledExactlyOnceWith("stateChange");
});
it("lets the current track end normally during an unresolved direct request", async () => {
const ctx = makeRealStartCtx();
ctx.player.play("https://example.test/old.mp3");
ctx.player.play.mockClear();
const lookupStarted = deferred();
const directLookup = deferred<{ url: string }>();
const getSongUrl = vi.fn(async (id: string) => {
if (id === "new") {
lookupStarted.resolve();
return directLookup.promise;
}
return { url: "https://example.test/following.mp3" };
});
ctx.getProviderFor.mockReturnValue({ platform: "netease", getSongUrl });
const request = playSingleSong.call(ctx, song119("new"));
await lookupStarted.promise;
expect(ctx.queue.current()?.id).toBe("old");
expect(ctx.player.getState()).toBe("playing");
ctx.player.stop();
ctx.player.emit("trackEnd");
await new Promise<void>(resolve => setImmediate(resolve));
directLookup.resolve({ url: "https://example.test/stale.mp3" });
expect(await request).toBe(false);
expect(ctx.queue.current()?.id).toBe("following");
expect(getSongUrl.mock.calls.map(([id]) => id)).toEqual(["new", "following"]);
expect(ctx.player.play).toHaveBeenCalledExactlyOnceWith("https://example.test/following.mp3", 0, 1);
});
});
describe("BotInstance.loadSavedQueue (#119)", () => {
@@ -1710,6 +1896,12 @@ describe("cmdPlaylist with a playlist link (#160)", () => {
expect(ctx.providers.netease.search).not.toHaveBeenCalled();
});
it("reports a refused first track instead of announcing playback", async () => {
const ctx = makeCtx();
ctx.resolveAndPlay.mockResolvedValue(false);
expect(await cmdPlaylist.call(ctx, cmd("2829883282"))).toBe("Cannot play: Song");
});
it("checks the link's platform is enabled", async () => {
const ctx = makeCtx();
ctx.assertProviderEnabled.mockImplementation(() => { throw new Error("音源未启用:qq"); });
@@ -1765,7 +1957,7 @@ describe("resumeInterruptedStream — long B站 streams dying mid-play (#161)",
it("re-resolves the URL and resumes at the current position when a B站 stream ends early", async () => {
const ctx = makeCtx({ elapsed: 1000, duration: 10_000 });
expect(await resumeInterruptedStream.call(ctx)).toBe(true);
expect(ctx.provider.getSongUrl).toHaveBeenCalledWith("BV1abc");
expect(ctx.provider.getSongUrl).toHaveBeenCalledExactlyOnceWith("BV1abc", undefined, { avoidHosts: new Set() });
expect(ctx.player.play).toHaveBeenCalledWith("https://fresh.test/a.m4s", 1000, 10_000);
expect(ctx.song.url).toBe("https://fresh.test/a.m4s");
});
@@ -2131,6 +2323,7 @@ describe("BotInstance — OpenProtocol & command routing", () => {
sweepLocalAudio: vi.fn(),
emit: vi.fn(),
refreshOccupancy: vi.fn(async () => {}),
_resumeIfReturning: vi.fn(),
profileManager: { onChannelMoved: vi.fn(async () => {}) },
logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
} as Record<string, any>;
+197 -154
View File
@@ -9,7 +9,7 @@ import {
} from "../ts-protocol/client.js";
import { OpenProtocolManager } from "../ts-protocol/open-protocol.js";
import { AudioPlayer } from "../audio/player.js";
import { resolveUrlWithRetry } from "./url-retry.js";
import { blocksProviderForAdvance, resolveUrlWithRetry } from "./url-retry.js";
import { RISK_CONTROL_CODE, RiskControlError, toPlayFailure } from "../music/provider.js";
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
import type { MusicProvider, Platform, PlayFailure, Song, SongUrlResult } from "../music/provider.js";
@@ -59,6 +59,13 @@ import {
/** Reply sent when a non-admin invokes an admin-only chat command. */
export const COMMAND_DENIED_MESSAGE = "⛔ 需要管理员权限(该命令仅限管理员服务器组)";
async function startTrackForCommand(bot: BotInstance, song: QueuedSong | null): Promise<string | undefined> {
if (!song) return "No track to play";
let reason: string | undefined;
const started = await bot.resolveAndPlay(song, failure => { reason = failure.message; });
if (!started) return reason ? `Cannot play: ${song.name} — ${reason}` : `Cannot play: ${song.name}`;
}
/** Maps the persisted / command-line play-mode string to the PlayMode enum.
* Shared by the !mode command and the restart-restore path (#125). */
const PLAY_MODE_BY_VALUE: Record<string, PlayMode> = {
@@ -226,8 +233,19 @@ export class BotInstance extends EventEmitter {
private playbackRequest?: symbol;
/** 当前曲实际播放时长(试听片段秒数或完整 duration);resolveAndPlay 赋值。 */
private effectiveDuration: number | undefined;
/** Format metadata belongs to the selected queue entry and its current URL. */
private currentStream?: { song: QueuedSong; url: string; quality?: string; isTrial: boolean };
/** Resume attempts for the current song's stream (#161); see resumeInterruptedStream. */
private streamRecovery: { song: QueuedSong; attempts: number; position: number; session: number; generation: number; pauseRequested: boolean; inFlight: boolean } | null = null;
private streamRecovery: {
song: QueuedSong;
attempts: number;
position: number;
session: number;
generation: number;
pauseRequested: boolean;
inFlight: boolean;
failedHosts: Set<string>;
} | null = null;
private playGate: Promise<unknown> = Promise.resolve();
/** Per-bot Jellyfin playback-report session (start / ~10s progress / stop).
* null when the wired provider has no reporting capability. */
@@ -542,12 +560,10 @@ export class BotInstance extends EventEmitter {
// React near-instantly to channel membership changes. The 30s idle
// poller remains the fallback if any of these events are missed.
//
// clientEnter additionally arms auto-RESUME directly from the event,
// because the occupancy query (clientlist) times out whenever another
// client is present — i.e. exactly when a listener returns — so it cannot
// be used to confirm the return. See _resumeIfReturning().
this.tsClient.on("clientEnter", () => {
this._resumeIfReturning();
// Enter and move events can confirm a listener's arrival even if the
// occupancy query fails. Only arrivals in this channel can resume playback.
this.tsClient.on("clientEnter", (event: { id: number; channelID: bigint }) => {
this._resumeIfReturning(event.id, event.channelID);
void this.refreshOccupancy();
});
this.tsClient.on("clientLeave", (event: { id: number }) => {
@@ -567,6 +583,7 @@ export class BotInstance extends EventEmitter {
this.openProtocol?.scheduleAnnounce();
} else {
this.voiceDucking.removeSpeaker(event.id);
this._resumeIfReturning(event.id, event.targetChannelID);
}
void this.refreshOccupancy();
});
@@ -612,20 +629,10 @@ export class BotInstance extends EventEmitter {
}
}
/**
* Resume playback when a listener returns after an auto-pause, driven by the
* clientEnter push event rather than a (timing-out) occupancy query.
*
* We only auto-pause while alone on the server, so `autoPaused` is a reliable
* "paused because empty" flag; any client appearing while it's set means a
* listener returned. Delegating to handleOccupancy(1) routes through
* decideOccupancyAction (resume iff autoPaused && paused) and also cancels the
* idle-disconnect timer. This path NEVER pauses — userCount is always > 0 —
* so a spurious or unrelated enter can only (harmlessly) resume, never stop
* playback. Pause remains exclusively on the authoritative clientlist path.
*/
private _resumeIfReturning(): void {
if (!this.connected) return;
/** Resume an automatic pause after a listener arrives in the bot's channel. */
private _resumeIfReturning(listenerId: number, channelId: bigint): void {
if (!this.connected || listenerId <= 0 || listenerId === this.tsClient.getClientId() ||
channelId === 0n || channelId !== this.tsClient.getChannelId()) return;
if (shouldResumeOnReturn(this.autoPaused, this.player.getState())) {
this.handleOccupancy(1);
}
@@ -960,7 +967,7 @@ export class BotInstance extends EventEmitter {
return this.cmdStop();
case "next":
case "skip":
return this.cmdNext();
return (await this.skipToNext()).message;
case "prev":
return this.cmdPrev();
case "vol":
@@ -1070,7 +1077,11 @@ export class BotInstance extends EventEmitter {
}
/** Resolve the URL and start playback if this request still owns the queue. */
async resolveAndPlay(song: QueuedSong, onFailure?: (failure: PlayFailure) => void): Promise<boolean> {
async resolveAndPlay(
song: QueuedSong,
onFailure?: (failure: PlayFailure) => void,
commitQueue?: () => void,
): Promise<boolean> {
const request = Symbol();
this.playbackRequest = request;
const generation = this.lifecycleGeneration;
@@ -1091,10 +1102,6 @@ export class BotInstance extends EventEmitter {
fail("该机器人已关闭本地音频播放");
return false;
}
// Clear any accumulated skip votes — every fresh track starts with a
// clean slate, regardless of which code path loaded it (cmdPlay,
// cmdPlaylist, cmdAlbum, cmdFm, trackEnd auto-advance, etc.).
this.voteSkipUsers.clear();
try {
const provider = this.getProviderFor(song.platform);
if (song.platform === "bilibili" && (!song.id.includes("?p=") || song.duration === 0)) {
@@ -1117,9 +1124,13 @@ export class BotInstance extends EventEmitter {
// click, chat !play, auto-advance, FM — shares the same budget. The
// policy lives in url-retry.ts so it is unit tested without a bot; a
// config without the field means 0 retries, i.e. the previous behaviour.
let selectedQuality: string | undefined;
const result = await resolveUrlWithRetry({
retries: this.config?.playUrlRetries,
resolve: (quality) => provider.getSongUrl(song.id, quality),
resolve: (quality) => {
selectedQuality = quality;
return provider.getSongUrl(song.id, quality);
},
// NetEase's quality ladder is not continuous: a track can play at 192k
// while both 320k and 128k return null, so every lower level is tried.
// Providers without a quality knob return [] and keep one attempt.
@@ -1138,7 +1149,7 @@ export class BotInstance extends EventEmitter {
"URL resolve hit NetEase risk control (-460) — backing off",
);
} else if (error) {
this.logger.warn({ ...fields, err: error }, "URL resolve threw — retrying");
this.logger.warn({ ...fields, err: error }, "URL resolve attempt failed");
} else if (attempt < total) {
this.logger.debug(fields, "URL resolve returned no URL — retrying");
}
@@ -1210,7 +1221,8 @@ export class BotInstance extends EventEmitter {
// frame counter is not reset, so player.getElapsed() over-reads for the
// 2nd+ consecutive Spotify track. Cosmetic only — the authoritative
// elapsed shown to users is status.track.position from the backend poll.
if (!this.player.isExternalActive()) {
if (commitQueue) this.player.resetFailures();
if (commitQueue || !this.player.isExternalActive()) {
this.player.playPcmStream(this.spotifyController.getPcmStream(), {
// The sidecar PCM pipe is long-lived; per-track end arrives via the
// controller "trackEnded" WS event, not stream EOF. A real EOF here
@@ -1239,45 +1251,41 @@ export class BotInstance extends EventEmitter {
this.player.resume();
}
this.currentSourceIsSpotify = true;
this.jellyfinReporter?.onStop();
song.url = result.url;
// No trial clip for Spotify — full-track duration only (the near-end
// stall watchdog is disabled for the external stream anyway).
// Spotify has no preview clip or URL stall watchdog.
this.effectiveDuration = song.duration;
this.autoPaused = false;
this.database.addPlayHistory({
botId: this.id,
songId: song.id,
songName: song.name,
artist: song.artist,
album: song.album,
platform: song.platform,
coverUrl: song.coverUrl,
requestedBy: song.requestedBy,
});
await this.syncProfileToSong(song);
this.emit("stateChange");
return true;
}
// Non-Spotify track: if we were on Spotify, pause the sidecar so it stops
// decoding ahead before the URL ffmpeg reclaims the PCM buffer.
if (this.currentSourceIsSpotify) {
this.spotifyController.pause().catch((err) =>
this.logger.warn({ err }, "Failed to pause Spotify sidecar on source switch"));
this.currentSourceIsSpotify = false;
} else {
// Pause the sidecar before URL playback reclaims the PCM buffer.
if (this.currentSourceIsSpotify) {
this.spotifyController.pause().catch((err) =>
this.logger.warn({ err }, "Failed to pause Spotify sidecar on source switch"));
this.currentSourceIsSpotify = false;
}
if (commitQueue) this.player.resetFailures();
this.effectiveDuration = result.trialDuration ?? song.duration;
this.player.play(result.url, 0, this.effectiveDuration);
}
song.url = result.url;
// 试听片段用试听时长(让 player nearEnd 正确触发自动切歌);完整曲回退 song.duration
this.effectiveDuration = result.trialDuration ?? song.duration;
this.player.play(result.url, 0, this.effectiveDuration);
// Jellyfin playback reporting: open a session for jellyfin tracks (the
// reporter closes the previous one itself); close any open session when
// playback moves to another source. Fire-and-forget — never blocks play.
this.currentStream = { song, url: result.url, quality: selectedQuality, isTrial: result.trialDuration !== undefined };
} catch (err) {
if (isCancelled()) return false;
this.logger.error({ err, songId: song.id }, "Failed to resolve URL");
onFailure?.(toPlayFailure(song.platform, song.id, err));
return false;
}
// A direct play request commits its queue only after playback starts.
commitQueue?.();
this.voteSkipUsers.clear();
// Playback has started. Failures in bookkeeping must not skip a track
// or turn an otherwise successful playback request into an error.
this.autoPaused = false;
try {
if (song.platform === "jellyfin") this.jellyfinReporter?.onTrackStart(song.id);
else this.jellyfinReporter?.onStop();
// Fresh playback (re)start — clear auto-pause so a later occupancy
// change won't try to "resume" a track the user already restarted.
this.autoPaused = false;
} catch (err) {
this.logger.warn({ err, songId: song.id }, "Failed to report playback session");
}
try {
this.database.addPlayHistory({
botId: this.id,
songId: song.id,
@@ -1288,31 +1296,25 @@ export class BotInstance extends EventEmitter {
coverUrl: song.coverUrl,
requestedBy: song.requestedBy,
});
// Keep TeamSpeak-side profile updates on the same path for play/next/FM.
await this.syncProfileToSong(song);
this.emit("stateChange");
return true;
} catch (err) {
if (isCancelled()) return false;
this.logger.error({ err, songId: song.id }, "Failed to resolve URL");
onFailure?.(toPlayFailure(song.platform, song.id, err));
return false;
this.logger.warn({ err, songId: song.id }, "Failed to save play history");
}
this.emit("stateChange");
// Profile uploads can outlive a short track. Let the queue advance while
// the profile manager's generation checks discard superseded updates.
void this.syncProfileToSong(song);
return true;
}
/** Platforms whose CDN stream can die mid-file on long content (#89, #161). */
private static readonly RESUMABLE_PLATFORMS: ReadonlySet<Platform> = new Set(["bilibili"]);
private static readonly RESUMABLE_PLATFORMS: ReadonlySet<Platform> = new Set(["bilibili", "netease", "qq", "kugou"]);
/** A track that ends within this many seconds of its duration ended normally. */
private static readonly STREAM_END_TOLERANCE_S = 30;
private static readonly MAX_STREAM_RESUMES = 3;
private static readonly MAX_STREAM_URL_LOOKUPS = 3;
/**
* Called when the player reports a track end. If a B站 stream ended long
* before its known duration, the CDN dropped it (#161): fetch a fresh URL
* and continue from where it stopped instead of skipping the rest of a
* 2-3 hour video. Gives up after MAX_STREAM_RESUMES attempts that make no
* real progress, so a truly broken stream still advances the queue.
* Renew an interrupted finite CDN stream and seek to the audio clock at EOF.
* The existing recovery budget bounds restarts that make no progress.
*
* Returns true when it handled the end (resumed, or a newer track has
* already taken over), false when the caller should advance the queue.
@@ -1322,12 +1324,21 @@ export class BotInstance extends EventEmitter {
if (!song || !this.connected || !BotInstance.RESUMABLE_PLATFORMS.has(song.platform)) {
return false;
}
const bilibili = song.platform === "bilibili";
const source = song.url ? URL.parse(song.url) : null;
const playback = this.currentStream?.song === song && this.currentStream.url === song.url
? this.currentStream : undefined;
const duration = this.effectiveDuration ?? song.duration;
const position = Math.floor(this.player.getElapsed());
const elapsed = this.player.getElapsed();
const position = bilibili ? Math.floor(elapsed) : elapsed;
const endedSession = this.player.getPlaybackSessionId();
if (!(duration > 0) || duration - position <= BotInstance.STREAM_END_TOLERANCE_S) {
if (!Number.isFinite(duration) || duration <= 0 || !Number.isFinite(position) || position < 0 ||
duration - position <= BotInstance.STREAM_END_TOLERANCE_S) {
return false;
}
// Music previews can start at a different offset than the full song.
if (!bilibili && (playback?.isTrial || position <= 0 ||
(source?.protocol !== "http:" && source?.protocol !== "https:"))) return false;
if (this.player.getState() !== "idle") return true;
const generation = this.lifecycleGeneration;
@@ -1339,7 +1350,10 @@ export class BotInstance extends EventEmitter {
recovery.generation !== generation ||
position - recovery.position > BotInstance.STREAM_END_TOLERANCE_S
) {
this.streamRecovery = { song, attempts: 0, position, session: endedSession, generation, pauseRequested: false, inFlight: false };
this.streamRecovery = {
song, attempts: 0, position, session: endedSession, generation,
pauseRequested: false, inFlight: false, failedHosts: new Set(),
};
}
const state = this.streamRecovery!;
if (state.inFlight) return true;
@@ -1352,9 +1366,11 @@ export class BotInstance extends EventEmitter {
return false;
}
state.position = position;
const failedHost = source?.hostname.replace(/\.$/, "");
if (bilibili && failedHost) state.failedHosts.add(failedHost);
this.logger.warn(
{ songId: song.id, position, duration, attempt: state.attempts + 1 },
{ platform: song.platform, songId: song.id, position, duration, attempt: state.attempts + 1 },
"Stream ended before the track did — resuming with a fresh URL",
);
state.inFlight = true;
@@ -1375,16 +1391,28 @@ export class BotInstance extends EventEmitter {
let result: Awaited<ReturnType<MusicProvider["getSongUrl"]>> = null;
let reason = "no-url";
try {
result = await this.getProviderFor(song.platform).getSongUrl(song.id);
} catch {
result = await this.getProviderFor(song.platform).getSongUrl(
song.id, playback?.quality, bilibili ? { avoidHosts: state.failedHosts } : { refresh: true },
);
} catch (err) {
if (!isCurrent()) return cancelled();
if (blocksProviderForAdvance(toPlayFailure(song.platform, song.id, err).code)) return false;
reason = "lookup-error";
}
// Skip, stop, reconnect, or a new playback session supersedes the lookup.
if (!isCurrent()) return cancelled();
if (result?.url) {
if (!bilibili) {
const stream = URL.parse(result.url);
if (result.trialDuration !== undefined || (stream?.protocol !== "http:" && stream?.protocol !== "https:")) {
this.logger.warn({ platform: song.platform, songId: song.id }, "Fresh URL cannot resume the full track");
return false;
}
}
// Lookup retries do not consume the actual decoder resume budget.
state.attempts++;
song.url = result.url;
if (playback) playback.url = result.url;
this.player.play(result.url, position, duration);
state.session = this.player.getPlaybackSessionId();
if (state.pauseRequested) this.player.pause();
@@ -1392,7 +1420,7 @@ export class BotInstance extends EventEmitter {
return true;
}
this.logger.warn(
{ platform: "bilibili", sessionId: endedSession, position, duration, lookupAttempt: lookup + 1, reason },
{ platform: song.platform, sessionId: endedSession, position, duration, lookupAttempt: lookup + 1, reason },
"Fresh stream URL lookup failed",
);
}
@@ -1480,56 +1508,53 @@ export class BotInstance extends EventEmitter {
if (error) return error;
const song0 = song!;
let why: string | undefined;
const ok = await this.playSingleSong(song0, requesterName, failure => { why = failure.message; });
if (!ok) return why ? `Cannot play: ${song0.name} — ${why}` : `Cannot play: ${song0.name}`;
const ok = await this.playSingleSong(song0, requesterName, (failure, currentTrackContinues) => {
why = currentTrackContinues
? `Could not restart ${song0.name}. The current track is still playing: ${failure.message}`
: `Cannot play: ${song0.name} — ${failure.message}`;
});
if (!ok) return why ?? `Cannot play: ${song0.name}`;
return `Now playing: ${song0.name} - ${song0.artist}`;
}
/**
* Play a single resolved song immediately, honoring config.playKeepsQueue:
* - false (default): clear the queue and play only this song — today's
* behavior. The prior track is stopped and released local uploads swept.
* - true (and the queue is non-empty): insert the song after the current
* track and jump to it (reusing addNext + playAt — no new queue logic), so
* the rest of the queue survives and continues after it. FM auto-refill is
* stopped (manual takeover), but existing queued songs are preserved.
*
* Shared by chat !play and the web /play-song route so the toggle decision
* lives in exactly one place (#119). Returns true if a track started playing.
*/
async playSingleSong(song: QueuedSong, requesterName?: string, onFailure?: (failure: PlayFailure) => void): Promise<boolean> {
const s = this.withRequester(song, requesterName);
if (this.config.playKeepsQueue && !this.queue.isEmpty()) {
const insertedAt =
this.queue.getCurrentIndex() < 0
? this.queue.size()
: this.queue.getCurrentIndex() + 1;
this.player.stop();
this.disableFmMode();
this.queue.addNext(s);
this.queue.playAt(insertedAt);
this.player.resetFailures();
// No sweep here: the queue is kept, so no local uploads were released.
return this.resolveAndPlay(this.queue.current()!, onFailure);
}
// Legacy replace behavior (default).
/** Start the requested song before changing the queue or stopping FM. */
async playSingleSong(
song: QueuedSong,
requesterName?: string,
onFailure?: (failure: PlayFailure, currentTrackContinues?: boolean) => void,
): Promise<boolean> {
const requested = this.withRequester(song, requesterName);
const previous = this.queue.current();
if (previous && !this.isSameSong(previous, s)) {
this.player.stop();
const previousSession = this.isSameSong(previous, requested) ? this.player.getPlaybackSessionId() : undefined;
const keepQueue = this.config.playKeepsQueue && !this.queue.isEmpty();
let failure: PlayFailure | undefined;
const started = await this.resolveAndPlay(requested, reason => { failure = reason; }, () => {
this.disableFmMode();
if (keepQueue) {
const currentIndex = this.queue.getCurrentIndex();
const index = currentIndex < 0 ? this.queue.size() : currentIndex + 1;
this.queue.addNext(requested);
this.queue.playAt(index);
} else {
this.queue.clear();
this.queue.add(requested);
this.queue.play();
}
});
if (!started) {
const currentTrackContinues = previousSession !== undefined &&
this.queue.current() === previous && this.player.getPlaybackSessionId() === previousSession &&
this.player.getState() === "playing";
onFailure?.(failure ?? {
platform: song.platform,
songId: song.id,
code: "unknown",
message: "播放请求已取消",
}, currentTrackContinues);
return false;
}
this.queue.clear();
this.disableFmMode();
this.queue.add(s);
this.queue.play();
// Reset failure counter on user-initiated play
this.player.resetFailures();
const ok = await this.resolveAndPlay(this.queue.current()!, onFailure);
// Sweep AFTER the new song is queued+resolved: the replaced songs are no
// longer referenced (and get deleted), but the song — if it is the same
// local upload that was already playing — stays referenced and is preserved.
this.sweepLocalAudio("replaced");
return ok;
if (!keepQueue) this.sweepLocalAudio("replaced");
return true;
}
/**
@@ -1584,9 +1609,9 @@ export class BotInstance extends EventEmitter {
if (wasIdle) {
this.queue.playAt(this.queue.size() - 1);
this.player.resetFailures();
await this.resolveAndPlay(this.queue.current()!);
const failure = await startTrackForCommand(this, this.queue.current());
this.emit("stateChange");
return `Now playing: ${s.name} - ${s.artist}`;
return failure ?? `Now playing: ${s.name} - ${s.artist}`;
}
this.emit("stateChange");
@@ -1614,10 +1639,9 @@ export class BotInstance extends EventEmitter {
if (wasIdle) {
this.queue.playAt(insertedAt);
this.player.resetFailures();
const ok = await this.resolveAndPlay(this.queue.current()!);
const failure = await startTrackForCommand(this, this.queue.current());
this.emit("stateChange");
if (!ok) return `Cannot play: ${s.name}`;
return `Now playing: ${s.name} - ${s.artist}`;
return failure ?? `Now playing: ${s.name} - ${s.artist}`;
}
this.emit("stateChange");
@@ -1682,12 +1706,16 @@ export class BotInstance extends EventEmitter {
return "Stopped and queue cleared";
}
private async cmdNext(): Promise<string> {
await this.playNext();
async skipToNext(): Promise<{ ok: boolean; message: string }> {
if (!this.connected) throw new Error("Bot is not connected to TeamSpeak");
if (this.isAdvancing) return { ok: false, message: "正在切歌,请稍后" };
let reason: string | undefined;
const started = await this.playNext(3, failure => { reason = failure.message; });
const current = this.queue.current();
if (current)
return `Now playing: ${current.name} - ${current.artist}`;
return "Queue is empty";
if (started && current) {
return { ok: true, message: `Now playing: ${current.name} - ${current.artist}` };
}
return { ok: false, message: reason ?? (current ? "没有可播放的下一首" : "队列为空") };
}
private async cmdPrev(): Promise<string> {
@@ -1876,10 +1904,10 @@ export class BotInstance extends EventEmitter {
this.queue.add(this.withRequester({ ...song, platform: provider.platform }, requesterName));
}
const first = this.queue.play();
if (first) await this.resolveAndPlay(first);
const failure = await startTrackForCommand(this, first);
this.sweepLocalAudio("queue_replaced");
this.emit("stateChange");
return `Loaded ${songs.length} songs. Now playing: ${first?.name ?? "unknown"}`;
return failure ?? `Loaded ${songs.length} songs. Now playing: ${first?.name ?? "unknown"}`;
}
private async cmdAlbum(cmd: ParsedCommand, requesterName?: string): Promise<string> {
@@ -1913,10 +1941,10 @@ export class BotInstance extends EventEmitter {
this.queue.add(this.withRequester({ ...song, platform: provider.platform }, requesterName));
}
const first = this.queue.play();
if (first) await this.resolveAndPlay(first);
const failure = await startTrackForCommand(this, first);
this.sweepLocalAudio("queue_replaced");
this.emit("stateChange");
return `Loaded ${songs.length} songs. Now playing: ${first?.name ?? "unknown"}`;
return failure ?? `Loaded ${songs.length} songs. Now playing: ${first?.name ?? "unknown"}`;
}
private async cmdFm(cmd: ParsedCommand, requesterName?: string): Promise<string> {
@@ -1954,11 +1982,11 @@ export class BotInstance extends EventEmitter {
this.player.resetFailures();
const first = this.queue.play();
if (first) await this.resolveAndPlay(first);
const failure = await startTrackForCommand(this, first);
this.sweepLocalAudio("queue_replaced");
this.emit("stateChange");
const label = provider.platform === "qq" ? "QQ Radar FM" : "Personal FM";
return `${label} started: ${first?.name ?? "unknown"} - ${first?.artist ?? ""}`;
return failure ?? `${label} started: ${first?.name ?? "unknown"} - ${first?.artist ?? ""}`;
}
private async cmdArtist(cmd: ParsedCommand, requesterName?: string): Promise<string> {
@@ -1988,10 +2016,10 @@ export class BotInstance extends EventEmitter {
this.player.resetFailures();
const first = this.queue.play();
if (first) await this.resolveAndPlay(first);
const failure = await startTrackForCommand(this, first);
this.sweepLocalAudio("queue_replaced");
this.emit("stateChange");
return `Artist mode: ${cmd.args} — ${filtered.length} songs loaded. Now playing: ${first?.name ?? "unknown"}`;
return failure ?? `Artist mode: ${cmd.args} — ${filtered.length} songs loaded. Now playing: ${first?.name ?? "unknown"}`;
}
private async refillFm(): Promise<void> {
@@ -2232,11 +2260,26 @@ export class BotInstance extends EventEmitter {
if (this.isAdvancing || !this.connected) return false;
this.isAdvancing = true;
let started = false;
let riskControlled = false;
const blockedProviders = new Set<string>();
const captureFailure = (failure: PlayFailure) => {
riskControlled = failure.code === "risk_control";
if (blocksProviderForAdvance(failure.code)) blockedProviders.add(failure.platform);
onFailure?.(failure);
};
const nextCandidate = (): QueuedSong | null => {
if (blockedProviders.size === 0) return this.queue.next();
const sequential = this.queue.getMode() === PlayMode.Sequential;
const currentIndex = this.queue.getCurrentIndex();
if (!this.queue.list().some((track, index) =>
(!sequential || index > currentIndex) && !blockedProviders.has(track.platform),
)) return null;
// Do not spend URL attempts on a blocked source. Allow for crossing a
// shuffle boundary, but always terminate in looping modes.
for (let i = 0; i < this.queue.size() * 2; i++) {
const candidate = this.queue.next();
if (!candidate || !blockedProviders.has(candidate.platform)) return candidate;
}
return null;
};
const generation = this.lifecycleGeneration;
const unchanged = (song: QueuedSong, request: symbol | undefined) =>
this.connected && this.lifecycleGeneration === generation &&
@@ -2251,8 +2294,8 @@ export class BotInstance extends EventEmitter {
started = await playback;
if (!started && !unchanged(next, request)) return false;
if (!started) {
for (let i = 0; i < maxRetries && this.connected && !riskControlled; i++) {
const retry = this.queue.next();
for (let i = 0; i < maxRetries && this.connected; i++) {
const retry = nextCandidate();
if (!retry) break;
const retryPlayback = this.resolveAndPlay(retry, captureFailure);
const retryRequest = this.playbackRequest;
+14
View File
@@ -41,6 +41,20 @@ describe("normalizeRetryCount", () => {
});
describe("resolveUrlWithRetry", () => {
it("stops immediately when the provider asks the user to verify", async () => {
const error = new SongUrlUnavailable({
platform: "kugou", songId: "song", code: "provider_verification_required", message: "Verification required",
});
const resolve = vi.fn(async () => { throw error; });
const onExhausted = vi.fn();
const { sleep, delays } = recordingSleep();
expect(await resolveUrlWithRetry({ retries: 5, fallbacks: ["standard"], resolve, onExhausted, sleep })).toBeNull();
expect(resolve).toHaveBeenCalledTimes(1);
expect(delays).toEqual([]);
expect(onExhausted).toHaveBeenCalledExactlyOnceWith({ error, quality: undefined });
});
it("makes exactly one attempt when retries is 0", async () => {
const resolve = vi.fn(async () => null);
const { sleep } = recordingSleep();
+8 -2
View File
@@ -1,5 +1,10 @@
import { RiskControlError } from "../music/provider.js";
import type { SongUrlResult } from "../music/provider.js";
import { RiskControlError, SongUrlUnavailable } from "../music/provider.js";
import type { PlayFailureCode, SongUrlResult } from "../music/provider.js";
/** These failures apply to the provider for the current queue transition. */
export function blocksProviderForAdvance(code: PlayFailureCode | undefined): boolean {
return code === "risk_control" || code === "provider_verification_required";
}
/**
* Silent re-resolve of a playable URL.
@@ -179,6 +184,7 @@ export async function resolveUrlWithRetry(
lastError = error;
lastQuality = step.quality;
opts.onAttemptFailed?.({ attempt: i + 1, total: plan.length, quality: step.quality, error });
if (error instanceof SongUrlUnavailable && error.failure.code === "provider_verification_required") break;
// Only same-quality attempts grow the backoff; a level switch resets it.
sameQualityAttempt = step.fallback ? 0 : sameQualityAttempt + 1;
}
+7
View File
@@ -274,6 +274,13 @@ describe("config", () => {
});
});
it("retains a numeric QQ bitrate saved by an older settings API", () => {
const dir = makeTmpDir();
const path = join(dir, "config.json");
writeFileSync(path, JSON.stringify({ audioQuality: { qq: 128 } }));
expect(loadConfig(path).audioQuality.qq).toBe("128");
});
it("creates config file on save", () => {
const dir = makeTmpDir();
const path = join(dir, "sub", "config.json");
+4 -4
View File
@@ -469,15 +469,15 @@ export function loadConfig(path: string): BotConfig {
? (rawDefault as GateableProvider)
: null;
// audioQuality → per-provider strings; each field falls back to its default
// when missing/blank/non-string (a hand-edited/legacy config must never smuggle
// a non-string past the gate — the value is fed straight to provider.setQuality).
// Normalize the two numeric QQ bitrates accepted by older settings APIs.
// Other missing, blank or non-string qualities use provider defaults.
const partialAq = (partial.audioQuality ?? {}) as Partial<AudioQualityConfig>;
const coerceQuality = (v: unknown, fallback: string): string =>
typeof v === "string" && v.trim() ? v : fallback;
const qqQuality: unknown = partialAq.qq;
const audioQuality: AudioQualityConfig = {
netease: coerceQuality(partialAq.netease, defaults.audioQuality.netease),
qq: coerceQuality(partialAq.qq, defaults.audioQuality.qq),
qq: qqQuality === 128 || qqQuality === 320 ? String(qqQuality) : coerceQuality(qqQuality, defaults.audioQuality.qq),
bilibili: coerceQuality(partialAq.bilibili, defaults.audioQuality.bilibili),
kugou: coerceQuality(partialAq.kugou, defaults.audioQuality.kugou),
jellyfin: coerceQuality(partialAq.jellyfin, defaults.audioQuality.jellyfin),
+2 -2
View File
@@ -67,7 +67,7 @@ async function main() {
);
await apiServer.start();
const neteaseProvider = new NeteaseProvider(apiServer.getNeteaseBaseUrl());
const neteaseProvider = new NeteaseProvider(apiServer.getNeteaseBaseUrl(), logger);
const bilibiliProvider = new BiliBiliProvider();
const localProvider = new LocalMusicProvider(LOCAL_AUDIO_DIR);
const kugouProvider = new KugouProvider();
@@ -88,7 +88,7 @@ async function main() {
const qqSession = (process.env.QQ_MUSIC_MANAGED_SESSION ?? "1") === "1" && isProviderEnabled(config, "qq")
? new QQManagedSession(createQqLoginClient(), qqStore, logger)
: undefined;
const qqProvider = new QQMusicProvider(apiServer.getQQMusicBaseUrl(), qqSession);
const qqProvider = new QQMusicProvider(apiServer.getQQMusicBaseUrl(), qqSession, apiServer.assertQqMusicApiPort);
if (!qqSession) {
try {
const cookie = cookieStore.load("qq");
+10 -1
View File
@@ -34,7 +34,7 @@ describe("embedded API runtime", () => {
listen = vi.fn(() => { queueMicrotask(() => { server.listening = true; server.emit("listening"); }); return server; });
state.qqExport = { listen };
});
afterEach(() => { if (previousPort === undefined) delete process.env.PORT; else process.env.PORT = previousPort; });
afterEach(() => { if (previousPort === undefined) delete process.env.PORT; else process.env.PORT = previousPort; vi.restoreAllMocks(); });
it("binds NetEase to loopback/configured port without version checks and waits for listening", async () => {
let ready = false;
@@ -74,9 +74,18 @@ describe("embedded API runtime", () => {
});
it("reuses a legacy module that auto-started on import without a duplicate listen", async () => {
state.portFree = false;
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({ data: { message: "no songmid" } }), {
status: 400, headers: { "Content-Type": "application/json" },
}));
expect(await startEmbeddedApi("qq", 39217)).toEqual({ server: null });
expect(listen).not.toHaveBeenCalled();
});
it("reports an occupied port if another service bound it during import", async () => {
state.portFree = false;
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("not QQ", { status: 200 }));
await expect(startEmbeddedApi("qq", 39217)).rejects.toMatchObject({ code: "EADDRINUSE" });
expect(listen).not.toHaveBeenCalled();
});
it("never reflects arbitrary startup message, stack or code values", () => {
expect(getSafeApiStartupError({ message: "synthetic-credential", stack: "synthetic-credential", code: "synthetic-credential" })).toEqual({ category: "startup" });
expect(getSafeApiStartupError({ code: "ERR_REQUIRE_ESM", message: "synthetic-credential" })).toEqual({ category: "esm", code: "ERR_REQUIRE_ESM" });
+36 -1
View File
@@ -34,6 +34,38 @@ export function isApiPortFree(port: number): Promise<boolean> {
});
}
/** Identify the QQ wrapper without credentials or a request to QQ upstream. */
export async function isQqMusicApi(port: number): Promise<boolean> {
try {
const response = await fetch(`http://127.0.0.1:${port}/getMusicPlay`, {
redirect: "manual",
signal: AbortSignal.timeout(2_000),
});
if (response.status !== 400 || !response.headers.get("content-type")?.includes("application/json")) {
await response.body?.cancel();
return false;
}
const reader = response.body?.getReader();
if (!reader) return false;
const buffer = Buffer.alloc(1024);
let length = 0;
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
if (length + value.length > buffer.length) return false;
buffer.set(value, length);
length += value.length;
}
} finally {
await reader.cancel();
}
return JSON.parse(buffer.toString("utf8", 0, length))?.data?.message === "no songmid";
} catch {
return false;
}
}
function waitForListening(server: Server): Promise<void> {
if (server.listening) return Promise.resolve();
return new Promise((resolve, reject) => {
@@ -80,7 +112,10 @@ export async function startEmbeddedApi(provider: ApiProvider, port: number): Pro
if (!app || typeof app.listen !== "function") throw new Error("QQ API did not expose a Koa app");
// Historical packages listened during import. Their listener remains
// owned by this child and closes when the child exits.
if (!(await isApiPortFree(port))) return { server: null };
if (!(await isApiPortFree(port))) {
if (await isQqMusicApi(port)) return { server: null };
throw Object.assign(new Error("QQ Music API port is occupied"), { code: "EADDRINUSE" });
}
server = app.listen(port, "127.0.0.1");
}
await waitForListening(server!);
+13 -1
View File
@@ -67,7 +67,7 @@ describe("embedded API child lifecycle", () => {
logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() } as unknown as Logger;
manager = createApiServerManager(options, logger);
});
afterEach(async () => { manager.stop(); await flush(); vi.useRealTimers(); });
afterEach(async () => { manager.stop(); await flush(); vi.useRealTimers(); vi.restoreAllMocks(); });
it("isolates both APIs with ignored stdio, configured ports and IPC", async () => {
await manager.start();
@@ -87,10 +87,22 @@ describe("embedded API child lifecycle", () => {
manager = createApiServerManager({ ...options, neteaseEnabled: false, qqEnabled: false }, logger);
await manager.start(); expect(state.probes).toHaveLength(0); expect(state.fork).not.toHaveBeenCalled();
state.portFree = false;
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(JSON.stringify({ data: { message: "no songmid" } }), {
status: 400, headers: { "Content-Type": "application/json" },
}));
manager = createApiServerManager({ ...options, neteaseEnabled: false }, logger);
await manager.start(); expect(state.fork).not.toHaveBeenCalled();
expect(logger.info).toHaveBeenCalledWith({ port: 39217 }, expect.stringContaining("reusing"));
});
it("detects the wrong service on the QQ music port without assuming every occupied port is reusable", async () => {
state.portFree = false;
vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("<html>WebUI</html>", { status: 200 }));
manager = createApiServerManager({ ...options, neteaseEnabled: false }, logger);
await manager.start();
expect(state.fork).not.toHaveBeenCalled();
expect(logger.error).toHaveBeenCalledWith({ provider: "qq", port: 39217, category: "port-in-use" }, expect.stringContaining("qqMusicApiPort"));
expect(() => manager.assertQqMusicApiPort()).toThrow(expect.objectContaining({ code: "QQ_API_PORT_CONFLICT" }));
});
it("inherits tsx loader arguments without unrelated parent runner flags", async () => {
const previous = process.execArgv;
process.execArgv = ["--require", "C:\\app\\node_modules\\tsx\\dist\\preflight.cjs", "--import", "file:///app/node_modules/tsx/dist/loader.mjs", "--eval", "synthetic-evaluation", "--conditions", "vitest", "--input-type=module", "--inspect"];
+22 -1
View File
@@ -1,6 +1,6 @@
import { fork, type ChildProcess } from "node:child_process";
import type { Logger } from "../logger.js";
import { getSafeApiStartupError, isApiPortFree, safeApiErrorCode, type ApiProvider, type SafeApiStartupError } from "./api-server-runtime.js";
import { getSafeApiStartupError, isApiPortFree, isQqMusicApi, safeApiErrorCode, type ApiProvider, type SafeApiStartupError } from "./api-server-runtime.js";
export interface ApiServerOptions {
neteasePort: number;
@@ -13,6 +13,7 @@ export interface ApiServerManager {
stop(): void;
getNeteaseBaseUrl(): string;
getQQMusicBaseUrl(): string;
assertQqMusicApiPort(): void;
}
export function describeQqApiStartupError(err: unknown): string | null {
@@ -52,6 +53,13 @@ export function createApiServerManager(options: ApiServerOptions, logger: Logger
let generation = 0;
let starting: Promise<void> | null = null;
let stopping: Promise<void> = Promise.resolve();
let qqPortConflict = false;
function reportQqPortConflict(port: number): void {
qqPortConflict = true;
logger.error({ provider: "qq", port, category: "port-in-use" },
"QQ Music API port is occupied by another service. Free the port or set qqMusicApiPort to an unused port and restart.");
}
function launch(provider: ApiProvider, port: number, launchGeneration: number): Promise<void> {
const source = import.meta.url.endsWith(".ts");
@@ -158,16 +166,24 @@ export function createApiServerManager(options: ApiServerOptions, logger: Logger
const free = await isApiPortFree(port);
if (startGeneration !== generation) return;
if (!free) {
if (provider === "qq") {
const compatible = await isQqMusicApi(port);
if (startGeneration !== generation) return;
if (!compatible) { reportQqPortConflict(port); continue; }
qqPortConflict = false;
}
logger.info({ port }, `${provider === "netease" ? "NetEase" : "QQ Music"} API port already in use — reusing existing instance`);
continue;
}
await launch(provider, port, startGeneration);
if (startGeneration !== generation) return;
if (provider === "qq") qqPortConflict = false;
logger.info({ port }, `${name} API started`);
} catch (error) {
if (startGeneration !== generation) return;
const details = error instanceof StartupFailure ? error.details : getSafeApiStartupError(error);
if (details.category === "cancelled") return;
if (provider === "qq" && details.category === "port-in-use") { reportQqPortConflict(port); continue; }
const hint = provider === "qq" ? describeQqApiStartupError(details.category === "esm" ? { code: "ERR_REQUIRE_ESM" } : details.category === "node-engine" ? { code: "EBADENGINE" } : {}) : null;
logger.error({ provider, port, ...details }, hint ? `QQ Music API failed to start — ${hint}. QQ features (search/play/login) will be unavailable until fixed; port ${port} is down.` : `Failed to start ${name} API`);
}
@@ -191,5 +207,10 @@ export function createApiServerManager(options: ApiServerOptions, logger: Logger
},
getNeteaseBaseUrl: () => `http://127.0.0.1:${options.neteasePort}`,
getQQMusicBaseUrl: () => `http://127.0.0.1:${options.qqMusicPort}`,
assertQqMusicApiPort(): void {
if (qqPortConflict) {
throw Object.assign(new Error("QQ Music API port conflict; check qqMusicApiPort"), { code: "QQ_API_PORT_CONFLICT" });
}
},
};
}
+5
View File
@@ -185,6 +185,11 @@ describe("pickStableAudioUrl (#161 long streams dying mid-play)", () => {
expect(pickStableAudioUrl({ baseUrl: pcdn, backupUrl: [szbdyd] })).toBe(pcdn);
});
it("allows a refreshed URL from the same host if no alternative is available", () => {
const host = new URL(upos).hostname;
expect(pickStableAudioUrl({ baseUrl: upos }, new Set([host]))).toBe(upos);
});
it("returns undefined when there is no url at all", () => {
expect(pickStableAudioUrl({})).toBeUndefined();
});
+17 -15
View File
@@ -4,6 +4,7 @@ import axios, { type AxiosInstance } from "axios";
import type {
MusicProvider,
Song,
SongUrlRequestOptions,
SongUrlResult,
Playlist,
LyricLine,
@@ -52,26 +53,23 @@ const BILI_PCDN_HOST = /\.mcdn\.bilivideo\.cn$|\.szbdyd\.com$/i;
/**
* Pick the audio URL least likely to die mid-stream: the first upos/cos
* mirror among baseUrl + backupUrl, else the baseUrl as before.
* mirror among baseUrl + backupUrl. When recovering, exhaust untried hosts
* before reusing a failed host whose newly signed URL may still work.
*/
export function pickStableAudioUrl(stream: {
baseUrl?: string;
base_url?: string;
backupUrl?: string[];
backup_url?: string[];
}): string | undefined {
}, avoidHosts?: ReadonlySet<string>): string | undefined {
const primary = stream.baseUrl ?? stream.base_url;
const candidates = [primary, ...(stream.backupUrl ?? stream.backup_url ?? [])].filter(
(u): u is string => typeof u === "string" && u.length > 0,
);
const stable = candidates.find((u) => {
try {
return !BILI_PCDN_HOST.test(new URL(u).hostname);
} catch {
return false;
}
});
return stable ?? primary;
const candidates = [primary, ...(stream.backupUrl ?? stream.backup_url ?? [])]
.filter((url): url is string => typeof url === "string" && url.length > 0)
.map((url) => ({ url, host: URL.parse(url)?.hostname.replace(/\.$/, "") }));
const stable = candidates.filter(({ host }) => host && !BILI_PCDN_HOST.test(host));
const isUntried = ({ host }: (typeof candidates)[number]) => host && !avoidHosts?.has(host);
return stable.find(isUntried)?.url ?? candidates.find(isUntried)?.url ?? stable[0]?.url ?? primary;
}
/**
@@ -362,7 +360,11 @@ export class BiliBiliProvider implements MusicProvider {
return this.cidCache.get(key) ?? this.cidCache.get(`${bvid}?p=${page}`) ?? this.cidCache.get(bvid) ?? null;
}
async getSongUrl(songId: string, _quality?: string): Promise<SongUrlResult | null> {
async getSongUrl(
songId: string,
_quality?: string,
options?: SongUrlRequestOptions,
): Promise<SongUrlResult | null> {
const { bvid, page } = parseBilibiliId(songId);
const cid = await this.getCid(bvid, page);
if (!cid) return null;
@@ -385,7 +387,7 @@ export class BiliBiliProvider implements MusicProvider {
(b.bandwidth ?? 0) > (a.bandwidth ?? 0) ? b : a
);
const biliUrl = pickStableAudioUrl(best);
const biliUrl = pickStableAudioUrl(best, options?.avoidHosts);
return biliUrl ? { url: biliUrl } : null;
} catch {
return null;
+25
View File
@@ -2,6 +2,31 @@ import { describe, it, expect, vi } from "vitest";
import { mapKugouSong, mapKugouSongs, mapKugouAlbums, mapKugouPlaylist, mapKugouPlaylists, krcToLrc, KugouProvider } from "./kugou.js";
import { parseLyrics } from "./netease.js";
describe("KugouProvider.getSongUrl failure diagnostics", () => {
const id = "b3a52a7a958bf0aed0efbba2e9a818b7|32100650|966846";
const provider = () => {
const p = new KugouProvider();
p.setCookie("dfid=test-device");
return { bot: p, http: p as unknown as { request: (...args: unknown[]) => Promise<unknown> } };
};
it("distinguishes a provider verification response from a missing stream", async () => {
const { bot, http } = provider();
vi.spyOn(http, "request").mockResolvedValue({ status: 0, errcode: 20028 });
await expect(bot.getSongUrl(id)).rejects.toMatchObject({
failure: { code: "provider_verification_required", upstream: { code: 20028 } },
});
});
it("carries only safe status fields on a failed HTTP request", async () => {
const { bot, http } = provider();
vi.spyOn(http, "request").mockRejectedValue({ response: { status: 503, data: { hidden: "test-cookie" } } });
await expect(bot.getSongUrl(id)).rejects.toMatchObject({
failure: { code: "upstream_request_failed", upstream: { httpStatus: 503 } },
});
});
});
describe("mapKugouSongs", () => {
it("maps the mobile-search song shape to a Song with platform 'kugou'", () => {
// Shape captured live from mobilecdn.kugou.com/api/v3/search/song.
+31 -11
View File
@@ -11,15 +11,14 @@
* VERIFICATION NOTE: search and lyrics were verified live during development.
* The play-URL endpoint (`/v5/url`) is gated by Kugou's risk-control and may
* return `errcode 20028 "本次请求需要验证"` from flagged (datacenter) IPs even
* for free songs; on such hosts a logged-in session (QR login below) and/or a
* residential IP is required. QR login and VIP audio could not be verified in
* the build environment.
* for free songs. Surface explicit verification requests to the operator.
*/
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios";
import crypto from "node:crypto";
import zlib from "node:zlib";
import { parseLyrics } from "./netease.js";
import { playbackRequestFailure, SongUrlUnavailable } from "./provider.js";
import type {
Album,
AuthStatus,
@@ -663,8 +662,9 @@ export class KugouProvider implements MusicProvider {
if (!hash) return null;
await this.ensureDfid();
const q = quality ? (QUALITY_MAP[quality] ?? this.quality) : this.quality;
let data;
try {
const data = await this.request({
data = await this.request({
method: "GET",
url: "/v5/url",
xRouter: "trackercdn.kugou.com",
@@ -692,14 +692,34 @@ export class KugouProvider implements MusicProvider {
clientver: 11430,
},
});
const urls: string[] = Array.isArray(data?.url) ? data.url : [];
const backup: string[] = Array.isArray(data?.backupUrl) ? data.backupUrl : [];
const url = urls.find(Boolean) || backup.find(Boolean);
if (!url) return null;
return { url };
} catch {
return null;
} catch (error) {
const responseData = (error as { response?: { data?: unknown } } | null)?.response?.data;
throw this.kugouVerificationFailure(songId, responseData) ?? playbackRequestFailure(this.platform, songId, error);
}
const verification = this.kugouVerificationFailure(songId, data);
if (verification) throw verification;
const urls: unknown[] = Array.isArray(data?.url) ? data.url : [];
const backup: unknown[] = Array.isArray(data?.backupUrl) ? data.backupUrl : [];
const url = [...urls, ...backup].find((value): value is string => typeof value === "string" && value.length > 0);
if (url) return { url };
throw new SongUrlUnavailable({
platform: this.platform,
songId,
code: "unknown",
message: "酷狗未返回播放地址",
});
}
private kugouVerificationFailure(songId: string, data: unknown): SongUrlUnavailable | undefined {
const code = (data as { errcode?: unknown } | null)?.errcode;
if (code !== 20028 && code !== "20028") return;
return new SongUrlUnavailable({
platform: this.platform,
songId,
code: "provider_verification_required",
message: "酷狗要求完成验证(20028),请在酷狗检查账号状态",
upstream: { code: 20028 },
});
}
async getSongDetail(songId: string): Promise<Song | null> {
+168
View File
@@ -0,0 +1,168 @@
import { CanceledError, type AxiosInstance, type AxiosResponse, type InternalAxiosRequestConfig } from "axios";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { NeteaseProvider } from "./netease.js";
interface Summary {
id: number;
name: string;
trackCount: number;
cloudTrackCount?: number;
trackIds?: { id: number }[];
}
interface DetailRequest {
id: string;
config: InternalAxiosRequestConfig;
signal?: AbortSignal;
complete(count: number): void;
fail(): void;
}
const fixtures: { close(): void }[] = [];
// Replace only the external HTTP boundary; keep Axios cancellation and the
// provider's account selection, detail mapping and card mapping real.
function boundary(rows: Summary[]) {
const provider = new NeteaseProvider("http://netease.invalid");
provider.setCookie("MUSIC_U=owner");
const requests: DetailRequest[] = [];
const active = new Set<DetailRequest>();
let peak = 0;
let closed = false;
const api = (provider as unknown as { api: AxiosInstance }).api;
api.defaults.adapter = (config) => {
const response = (data: unknown): AxiosResponse => ({
data, config, status: 200, statusText: "OK", headers: {},
});
switch (config.url) {
case "/login/status": return Promise.resolve(response({ data: { profile: { userId: 1 } } }));
case "/user/playlist": return Promise.resolve(response({ playlist: rows }));
case "/personalized": return Promise.resolve(response({ result: rows }));
case "/cloudsearch": return Promise.resolve(response({ result: { playlists: rows } }));
case "/playlist/detail": return new Promise((resolve, reject) => {
if (closed) return reject(new Error("Fixture closed"));
const signal = config.signal as AbortSignal | undefined;
const finish = (error?: Error, count = 0) => {
if (!active.delete(request)) return;
signal?.removeEventListener("abort", abort);
if (error) reject(error);
else resolve(response({ playlist: {
id: config.params.id,
trackCount: 999,
trackIds: Array.from({ length: count }, (_, id) => ({ id })),
} }));
};
const abort = () => finish(new CanceledError("Request aborted"));
const request: DetailRequest = {
id: String(config.params.id), config, signal,
complete: (count) => finish(undefined, count),
fail: () => finish(new Error("Upstream unavailable")),
};
requests.push(request);
active.add(request);
peak = Math.max(peak, active.size);
signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted) abort();
});
default: return Promise.reject(new Error(`Unexpected endpoint ${config.url}`));
}
};
const fixture = {
provider, requests, active,
get peak() { return peak; },
request(id: string) {
const request = requests.find((request) => request.id === id);
if (!request) throw new Error(`Detail ${id} has not started`);
return request;
},
close() {
closed = true;
for (const request of active) request.fail();
},
};
fixtures.push(fixture);
return fixture;
}
function cloud(id: number): Summary {
return { id, name: `Playlist ${id}`, trackCount: id, cloudTrackCount: 1 };
}
describe("NetEase playlist card enrichment budget", () => {
beforeEach(() => vi.useFakeTimers());
afterEach(async () => {
for (const fixture of fixtures.splice(0)) fixture.close();
await vi.runAllTimersAsync();
vi.useRealTimers();
});
it("runs independent lookups concurrently within a four-request bound and keeps card order", async () => {
const fixture = boundary([
cloud(1), cloud(2), cloud(3), cloud(4), cloud(5), cloud(6), cloud(7),
{ id: 8, name: "Ordinary", trackCount: 8 },
{ ...cloud(9), trackIds: [{ id: 90 }, { id: 91 }] },
]);
const cards = fixture.provider.getUserPlaylists();
await vi.advanceTimersByTimeAsync(0);
expect(fixture.requests.map((request) => request.id)).toEqual(["1", "2", "3", "4"]);
// The remaining workers must continue with the account that supplied the list.
fixture.provider.setCookie("MUSIC_U=other");
fixture.request("4").complete(40);
await vi.advanceTimersByTimeAsync(0);
fixture.request("2").complete(0);
await vi.advanceTimersByTimeAsync(0);
fixture.request("5").fail();
await vi.advanceTimersByTimeAsync(0);
expect(fixture.requests.map((request) => request.id)).toEqual(["1", "2", "3", "4", "5", "6", "7"]);
expect(fixture.peak).toBe(4);
expect(fixture.requests.every((request) => request.config.params.cookie === "MUSIC_U=owner")).toBe(true);
fixture.request("7").complete(70);
fixture.request("1").complete(10);
fixture.request("6").complete(60);
fixture.request("3").complete(30);
expect((await cards).map((card) => [card.id, card.songCount])).toEqual([
["1", 10], ["2", 0], ["3", 30], ["4", 40], ["5", 5],
["6", 60], ["7", 70], ["8", 8], ["9", 2],
]);
expect(fixture.active.size).toBe(0);
expect(vi.getTimerCount()).toBe(0);
});
it.each(["library", "recommendations", "search"])("returns %s cards at the overall deadline, aborting active requests and skipping queued cards", async (entry) => {
const fixture = boundary([cloud(1), cloud(2), cloud(3), cloud(4), cloud(5), cloud(6), cloud(7)]);
const provider = fixture.provider;
const result = entry === "library" ? provider.getUserPlaylists()
: entry === "recommendations" ? provider.getRecommendPlaylists()
: provider.search("music").then((result) => result.playlists);
let settled = false;
void result.then(() => { settled = true; });
await vi.advanceTimersByTimeAsync(1000);
fixture.request("1").complete(0);
await vi.advanceTimersByTimeAsync(3999);
expect(settled).toBe(false);
await vi.advanceTimersByTimeAsync(1);
expect(settled).toBe(true);
expect((await result).map((card) => card.songCount)).toEqual([0, 2, 3, 4, 5, 6, 7]);
expect(fixture.active.size).toBe(0);
expect(fixture.requests.filter((request) => request.signal?.aborted).map((request) => request.id)).toEqual(["1", "2", "3", "4", "5"]);
expect(fixture.requests).toHaveLength(5);
expect(vi.getTimerCount()).toBe(0);
});
it("leaves standalone detail requests on the normal timeout without an enrichment signal", async () => {
const fixture = boundary([cloud(1)]);
const result = fixture.provider.getPlaylistDetail("1");
let settled = false;
void result.then(() => { settled = true; });
await vi.advanceTimersByTimeAsync(5000);
expect(settled).toBe(false);
expect(fixture.request("1").signal).toBeUndefined();
expect(fixture.request("1").config.timeout).toBe(10000);
fixture.request("1").complete(2);
expect((await result)?.songCount).toBe(2);
expect(vi.getTimerCount()).toBe(0);
});
});
+120
View File
@@ -237,6 +237,115 @@ describe("NeteaseProvider.search pagination", () => {
});
});
describe("NeteaseProvider.getPlaylistSongs (#200)", () => {
function playlistFixture(size: number) {
const warn = vi.fn();
const ids = Array.from({ length: size }, (_, i) => i + 1);
const get = vi.fn().mockResolvedValue({
data: { playlist: { trackIds: ids.map(id => ({ id })) } },
});
const post = vi.fn(async (_path: string, body: { ids: string }) => ({
data: { songs: body.ids.split(",").reverse().map(id => ({ id: Number(id) })) },
}));
const provider = new NeteaseProvider("http://x", { warn }).withCookie("MUSIC_U=test");
(provider as any).api = { get, post };
return { provider, ids, get, post, warn };
}
it.each([0, 12, 1000, 1360, 2000])("loads %i tracks in playlist order", async size => {
const { provider, ids, get, post, warn } = playlistFixture(size);
const songs = await provider.getPlaylistSongs("920292129");
expect(songs.map(song => song.id)).toEqual(ids.map(String));
expect(warn).not.toHaveBeenCalled();
expect(get.mock.calls).toEqual([["/playlist/detail", {
params: { id: "920292129", cookie: "MUSIC_U=test" },
}]]);
expect(post).toHaveBeenCalledTimes(Math.ceil(size / 1000));
for (let offset = 0; offset < size; offset += 1000) {
expect(post).toHaveBeenNthCalledWith(offset / 1000 + 1, "/song/detail", {
ids: ids.slice(offset, offset + 1000).join(","), cookie: "MUSIC_U=test", crypto: "eapi",
}, { headers: { "x-apicache-bypass": "1" } });
}
});
it("continues past unavailable tracks in an earlier batch", async () => {
const { provider, post, warn } = playlistFixture(1002);
post.mockResolvedValueOnce({ data: { songs: [{ id: 1 }] } });
const songs = await provider.getPlaylistSongs("920292129");
expect(songs.map(song => song.id)).toEqual(["1", "1001", "1002"]);
expect(warn.mock.calls).toEqual([[{
playlistId: "920292129", expectedCount: 1002, matchedCount: 3, missingCount: 999,
}, "NetEase playlist track IDs missing song details"]]);
});
it("propagates a failed batch instead of returning a partial playlist", async () => {
const { provider, post, warn } = playlistFixture(1360);
post.mockResolvedValueOnce({ data: { songs: [{ id: 1 }] } })
.mockRejectedValueOnce(new Error("sidecar unavailable"));
await expect(provider.getPlaylistSongs("920292129")).rejects.toThrow("sidecar unavailable");
expect(warn).not.toHaveBeenCalled();
});
});
describe("NetEase playlist counts (#201)", () => {
const summaries = [
{ id: 1, trackCount: 2, cloudTrackCount: 233 },
{ id: 2, trackCount: 337, cloudTrackCount: 7 },
{ id: 3, trackCount: 1360, cloudTrackCount: 3 },
{ id: 4, trackCount: 162, trackIds: [] },
{ id: 5, trackCount: 2, cloudTrackCount: 2, trackIds: [] },
{ id: 6, trackCount: 1, cloudTrackCount: 1, trackIds: [{ id: 10 }, { id: 20 }] },
];
const visibleCounts = [235, 344, 1360, 162, 0];
function fixture(cookie: string) {
const provider = new NeteaseProvider("http://x").withCookie(cookie);
const get = vi.fn(async (path: string, { params }: { params: Record<string, unknown> }) => {
expect(params.cookie).toBe(cookie);
switch (path) {
case "/login/status": return { data: { data: { profile: { userId: 1 } } } };
case "/user/playlist": return { data: { playlist: summaries } };
case "/personalized": return { data: { result: summaries } };
case "/cloudsearch": return { data: { result: { playlists: summaries } } };
case "/playlist/detail": {
const index = Number(params.id) - 1;
const count = cookie === "account=owner" ? visibleCounts[index] : summaries[index].trackCount;
return { data: { playlist: { ...summaries[index], trackIds: Array(count).fill({}) } } };
}
default: throw new Error("Unexpected endpoint: " + path);
}
});
(provider as any).api = { get };
return { provider, get };
}
it.each(["library", "recommendations", "search"])("counts visible cloud tracks in %s cards", async entry => {
const { provider, get } = fixture("account=owner");
let playlists;
if (entry === "library") playlists = await provider.getUserPlaylists();
else if (entry === "recommendations") playlists = await provider.getRecommendPlaylists();
else playlists = (await provider.search("music")).playlists;
expect(playlists.map(p => p.songCount)).toEqual([235, 344, 1360, 162, 0, 2]);
const lookups = get.mock.calls.filter(([path]) => path === "/playlist/detail");
expect(lookups.map(([, { params }]) => params.id)).toEqual(["1", "2", "3", "5"]);
});
it("respects the viewing account in playlist details and library cards", async () => {
const owner = fixture("account=owner").provider;
const guest = fixture("account=other").provider;
expect((await owner.getPlaylistDetail("1"))?.songCount).toBe(235);
expect((await guest.getPlaylistDetail("1"))?.songCount).toBe(2);
expect((await guest.getUserPlaylists())[0].songCount).toBe(2);
});
it("keeps the card's original count if its detail request fails", async () => {
const { provider } = fixture("account=owner");
vi.spyOn(provider, "getPlaylistDetail").mockRejectedValueOnce(new Error("Unavailable"));
const playlists = await provider.getUserPlaylists();
expect(playlists.map(p => p.songCount)).toEqual([2, 344, 1360, 162, 0, 2]);
});
});
describe("mapNeteaseArtists (artist search + detail)", () => {
it("maps cloudsearch type=100 artist entries", () => {
const out = mapNeteaseArtists([
@@ -480,6 +589,17 @@ describe("NetEase risk control (-460)", () => {
expect(r?.url).toBe("http://cdn.example/x.mp3");
expect(r?.trialDuration).toBe(60);
});
it("requests a new sidecar cache key for interruption recovery", async () => {
const get = vi.fn(async (_url: string, _config: unknown) => ({
data: { data: [{ url: "http://cdn.example/track.mp3" }] },
}));
const provider = providerWithApi(get);
await provider.getSongUrl("1");
await provider.getSongUrl("1", undefined, { refresh: true });
expect(get.mock.calls[0][1]).not.toHaveProperty("params.timestamp");
expect(get.mock.calls[1][1]).toMatchObject({ params: { id: "1", timestamp: expect.any(Number) } });
});
});
// ---------------------------------------------------------------------------
+115 -40
View File
@@ -1,11 +1,13 @@
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios";
import type { Logger } from "../logger.js";
import { RISK_CONTROL_CODE, RiskControlError, SongUrlUnavailable } from "./provider.js";
import type { PlayFailure } from "./provider.js";
import type {
MusicProvider,
Song,
SongUrlResult,
SongUrlRequestOptions,
Playlist,
PlaylistDetail,
LyricLine,
@@ -228,6 +230,16 @@ function getPlaybackUserAgent(cookie: string): string {
}
}
interface NeteasePlaylistSummary {
id: string | number;
name: string;
coverImgUrl?: string;
picUrl?: string;
trackCount?: number;
cloudTrackCount?: number;
trackIds?: { id: string | number }[] | null;
}
export class NeteaseProvider implements MusicProvider {
readonly platform = "netease" as const;
private api: AxiosInstance;
@@ -235,7 +247,7 @@ export class NeteaseProvider implements MusicProvider {
private quality = "exhigh";
private readonly baseUrl: string;
constructor(baseUrl: string) {
constructor(baseUrl: string, private readonly logger: Pick<Logger, "warn"> = console) {
this.baseUrl = baseUrl;
this.api = axios.create({
baseURL: baseUrl,
@@ -255,13 +267,56 @@ export class NeteaseProvider implements MusicProvider {
return this.cookie ? { cookie: this.cookie } : {};
}
private async mapPlaylistCards(rows: NeteasePlaylistSummary[], cookie: Record<string, string>): Promise<Playlist[]> {
const lookups: number[] = [];
const cards = rows.map((row, index): Playlist => {
const id = String(row.id);
let songCount = row.trackCount ?? 0;
if (Array.isArray(row.trackIds) && row.trackIds.length > 0) {
songCount = row.trackIds.length;
} else if ((row.cloudTrackCount ?? 0) > 0) {
lookups.push(index);
}
return { id, name: row.name, coverUrl: row.coverImgUrl ?? row.picUrl ?? "", songCount, platform: "netease" };
});
if (lookups.length === 0) return cards;
// Count enrichment is optional: a slow detail service must not delay the
// whole library or search by a separate request timeout for every card.
const controller = new AbortController();
const deadline = Date.now() + 5000;
const timer = setTimeout(() => controller.abort(), 5000);
let next = 0;
const enrich = async () => {
while (!controller.signal.aborted && Date.now() < deadline && next < lookups.length) {
const index = lookups[next++];
try {
// Cloud counts may overlap the list count or be hidden from this account.
const detail = await this.getPlaylistDetail(cards[index].id, cookie, controller.signal);
if (!controller.signal.aborted && Date.now() < deadline) {
cards[index].songCount = detail?.songCount ?? cards[index].songCount;
}
} catch {
// Keep the list count on failure or cancellation at the shared deadline.
}
}
};
try {
await Promise.all(Array.from({ length: Math.min(4, lookups.length) }, enrich));
} finally {
clearTimeout(timer);
}
return cards;
}
async search(query: string, limit = 20, offset = 0): Promise<SearchResult> {
const cookie = this.cookieParams;
// /cloudsearch supports offset for every type. Songs, playlists (type 1000)
// and albums (type 10) are all limit/offset-driven so the web can page past
// the first page (playlists/albums were previously hardcoded to limit: 10).
const [songRes, playlistRes, albumRes, artistRes] = await Promise.all([
this.api.get("/cloudsearch", {
params: { keywords: query, type: 1, limit, offset, ...this.cookieParams },
params: { keywords: query, type: 1, limit, offset, ...cookie },
}),
this.api.get("/cloudsearch", {
params: {
@@ -269,28 +324,20 @@ export class NeteaseProvider implements MusicProvider {
type: 1000,
limit,
offset,
...this.cookieParams,
...cookie,
},
}),
this.api.get("/cloudsearch", {
params: { keywords: query, type: 10, limit, offset, ...this.cookieParams },
params: { keywords: query, type: 10, limit, offset, ...cookie },
}),
this.api.get("/cloudsearch", {
params: { keywords: query, type: 100, limit, offset, ...this.cookieParams },
params: { keywords: query, type: 100, limit, offset, ...cookie },
}),
]);
const songs: Song[] = mapNeteaseSongs(songRes.data?.result?.songs);
const playlists: Playlist[] = (
playlistRes.data?.result?.playlists ?? []
).map((p: any) => ({
id: String(p.id),
name: p.name,
coverUrl: p.coverImgUrl ?? "",
songCount: p.trackCount ?? 0,
platform: "netease",
}));
const playlists = await this.mapPlaylistCards(playlistRes.data?.result?.playlists ?? [], cookie);
const albums = mapNeteaseAlbums(albumRes.data?.result?.albums);
@@ -299,12 +346,16 @@ export class NeteaseProvider implements MusicProvider {
return { songs, playlists, albums, artists };
}
async getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null> {
async getSongUrl(songId: string, quality?: string, options?: SongUrlRequestOptions): Promise<SongUrlResult | null> {
const level = quality ?? this.quality;
let res;
try {
res = await this.api.get("/song/url/v1", {
params: { id: songId, level, ua: getPlaybackUserAgent(this.cookie), ...this.cookieParams },
params: {
id: songId, level, ua: getPlaybackUserAgent(this.cookie), ...this.cookieParams,
// The embedded sidecar caches successful responses for two minutes.
...(options?.refresh && { timestamp: Date.now() }),
},
});
} catch (err) {
// -460 arrives as HTTP 400, and left as-is it looks like "this track is
@@ -351,23 +402,51 @@ export class NeteaseProvider implements MusicProvider {
}
async getPlaylistSongs(playlistId: string): Promise<Song[]> {
const res = await this.api.get("/playlist/track/all", {
params: { id: playlistId, ...this.cookieParams },
const cookie = this.cookieParams;
const res = await this.api.get("/playlist/detail", {
params: { id: playlistId, ...cookie },
});
return mapNeteaseSongs(res.data?.songs);
const trackIds: { id: number | string }[] = res.data?.playlist?.trackIds;
if (!Array.isArray(trackIds)) throw new Error("网易云返回的歌单曲目列表无效");
// Song detail accepts at most 1000 IDs. Page over the playlist snapshot
// so missing details for unavailable tracks cannot hide a later batch.
const batchSize = 1000;
const songs: Song[] = [];
for (let offset = 0; offset < trackIds.length; offset += batchSize) {
const ids = trackIds.slice(offset, offset + batchSize).map(track => String(track.id));
const details = await this.api.post("/song/detail", {
ids: ids.join(","),
// Match /playlist/track/all's detail lookup; /song/detail defaults to weapi.
crypto: "eapi",
...cookie,
}, {
// The sidecar's URL-based cache cannot distinguish POST bodies.
headers: { "x-apicache-bypass": "1" },
});
if (!Array.isArray(details.data?.songs)) throw new Error("网易云返回的歌曲详情无效");
const byId = new Map(mapNeteaseSongs(details.data.songs).map(song => [song.id, song]));
for (const id of ids) {
const song = byId.get(id);
if (song) songs.push(song);
}
}
if (songs.length < trackIds.length) {
this.logger.warn({
playlistId,
expectedCount: trackIds.length,
matchedCount: songs.length,
missingCount: trackIds.length - songs.length,
}, "NetEase playlist track IDs missing song details");
}
return songs;
}
async getRecommendPlaylists(): Promise<Playlist[]> {
const cookie = this.cookieParams;
const res = await this.api.get("/personalized", {
params: { limit: 10, ...this.cookieParams },
params: { limit: 10, ...cookie },
});
return (res.data?.result ?? []).map((p: any) => ({
id: String(p.id),
name: p.name,
coverUrl: p.picUrl ?? "",
songCount: p.trackCount ?? 0,
platform: "netease",
}));
return this.mapPlaylistCards(res.data?.result ?? [], cookie);
}
async getAlbumSongs(albumId: string): Promise<Song[]> {
@@ -503,7 +582,7 @@ export class NeteaseProvider implements MusicProvider {
* a web user's personal FM uses their own taste instead of the shared login.
*/
withCookie(cookie: string): NeteaseProvider {
const view = new NeteaseProvider(this.baseUrl);
const view = new NeteaseProvider(this.baseUrl, this.logger);
view.setQuality(this.quality);
view.setCookie(cookie);
return view;
@@ -570,9 +649,10 @@ export class NeteaseProvider implements MusicProvider {
return mapNeteaseSongs(res.data?.data?.dailySongs);
}
async getPlaylistDetail(playlistId: string): Promise<PlaylistDetail | null> {
async getPlaylistDetail(playlistId: string, cookie = this.cookieParams, signal?: AbortSignal): Promise<PlaylistDetail | null> {
const res = await this.api.get("/playlist/detail", {
params: { id: playlistId, ...this.cookieParams },
params: { id: playlistId, ...cookie },
...(signal && { signal }),
});
const p = res.data?.playlist;
if (!p) return null;
@@ -581,27 +661,22 @@ export class NeteaseProvider implements MusicProvider {
name: p.name ?? "",
description: p.description ?? "",
coverUrl: p.coverImgUrl ?? "",
songCount: p.trackCount ?? 0,
songCount: Array.isArray(p.trackIds) ? p.trackIds.length : p.trackCount ?? 0,
};
}
async getUserPlaylists(): Promise<Playlist[]> {
const cookie = this.cookieParams;
// First get user ID from login status
const statusRes = await this.api.get("/login/status", {
params: { ...this.cookieParams },
params: { ...cookie },
});
const uid = statusRes.data?.data?.profile?.userId;
if (!uid) return [];
const res = await this.api.get("/user/playlist", {
params: { uid, ...this.cookieParams },
params: { uid, ...cookie },
});
return (res.data?.playlist ?? []).map((p: any) => ({
id: String(p.id),
name: p.name,
coverUrl: p.coverImgUrl ?? "",
songCount: p.trackCount ?? 0,
platform: "netease",
}));
return this.mapPlaylistCards(res.data?.playlist ?? [], cookie);
}
}
+38 -2
View File
@@ -62,6 +62,10 @@ export type PlayFailureCode =
| "no_copyright"
/** The track exists, but this quality level is not ours to serve. */
| "quality_denied"
/** The upstream HTTP request failed or the expected API was unreachable. */
| "upstream_request_failed"
/** The music service explicitly asked the user to complete verification. */
| "provider_verification_required"
/** 200 with no URL and nothing that explains why. */
| "unknown";
@@ -71,7 +75,7 @@ export interface PlayFailure {
code: PlayFailureCode;
/** One short line in the UI's language — safe to render as-is. */
message: string;
/** Raw upstream fields (fee / payed / code / level). Logs only, never shown. */
/** Selected non-secret diagnostic fields. Logs only, never shown directly. */
upstream?: Record<string, unknown>;
}
@@ -92,6 +96,31 @@ export class SongUrlUnavailable extends Error {
}
}
/** Preserve typed status for troubleshooting without forwarding request or response data. */
export function playbackRequestFailure(
platform: "qq" | "kugou",
songId: string,
error: unknown,
): SongUrlUnavailable {
const raw = error as { code?: unknown; response?: { status?: unknown } } | null;
const status = raw?.response?.status;
const httpStatus = typeof status === "number" && Number.isInteger(status) && status >= 100 && status < 600
? status : undefined;
const name = platform === "qq" ? "QQ 音乐 API" : "酷狗";
const message = httpStatus ? `${name}播放请求失败(HTTP ${httpStatus})`
: raw?.code === "QQ_API_PORT_CONFLICT" && platform === "qq" ? "QQ 音乐 API 端口被其他服务占用,请检查 qqMusicApiPort"
: raw?.code === "ECONNREFUSED" && platform === "qq" ? "无法连接 QQ 音乐 API,请检查服务启动与端口"
: raw?.code === "ECONNABORTED" || raw?.code === "ETIMEDOUT" ? `${name}播放请求超时`
: `${name}播放请求失败,请检查服务与网络连接`;
return new SongUrlUnavailable({
platform,
songId,
code: "upstream_request_failed",
message,
upstream: httpStatus ? { httpStatus } : undefined,
});
}
export function toPlayFailure(platform: string, songId: string, error: unknown): PlayFailure {
if (error instanceof SongUrlUnavailable) return error.failure;
if (error instanceof RiskControlError) {
@@ -185,11 +214,18 @@ export interface AuthStatus {
avatarUrl?: string;
}
export interface SongUrlRequestOptions {
/** CDN hosts that already failed around this playback position (where supported). */
avoidHosts?: ReadonlySet<string>;
/** Resolve after an interruption without reusing a cached playback URL. */
refresh?: boolean;
}
export interface MusicProvider {
readonly platform: Platform;
search(query: string, limit?: number, offset?: number): Promise<SearchResult>;
getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null>;
getSongUrl(songId: string, quality?: string, options?: SongUrlRequestOptions): Promise<SongUrlResult | null>;
setQuality(quality: string): void;
getQuality(): string;
getSongDetail(songId: string): Promise<Song | null>;
+88
View File
@@ -10,6 +10,94 @@ vi.mock("axios", () => ({
import { mapQqAlbums, mapQqArtists, mapQqSongs, parseQqTrial, QQMusicProvider } from "./qq.js";
describe("QQ playback sidecar contract", () => {
beforeEach(() => {
mockGet.mockReset();
});
it("maps app playback quality to the installed sidecar format", async () => {
const provider = new QQMusicProvider("http://127.0.0.1:3200");
provider.setQuality("lossless");
mockGet.mockResolvedValue({ data: { data: { playUrl: { abc: { url: "https://example.com/audio" } } } } });
await expect(provider.getSongUrl("abc")).resolves.toMatchObject({ url: "https://example.com/audio" });
expect(mockGet).toHaveBeenLastCalledWith("/getMusicPlay", { params: expect.objectContaining({ songmid: "abc", quality: "flac" }) });
});
it.each([320, "320"])("accepts QQ quality %j from the settings API", async (quality) => {
const provider = new QQMusicProvider("http://127.0.0.1:3200");
provider.setQuality(quality);
expect(provider.getQuality()).toBe("320");
mockGet.mockResolvedValue({ data: { data: { playUrl: { abc: { url: "https://example.com/audio" } } } } });
await provider.getSongUrl("abc");
expect(mockGet).toHaveBeenLastCalledWith("/getMusicPlay", { params: expect.objectContaining({ quality: "320" }) });
});
it("resolves a numeric ID to a MID before asking the sidecar for playback", async () => {
const provider = new QQMusicProvider("http://127.0.0.1:3200");
mockGet.mockResolvedValueOnce({ data: { response: { songinfo: { data: { track_info: { mid: "abc" } } } } } });
mockGet.mockResolvedValueOnce({ data: { data: { playUrl: { abc: { url: "https://example.com/audio" } } } } });
await expect(provider.getSongUrl("12345")).resolves.toMatchObject({ url: "https://example.com/audio" });
expect(mockGet).toHaveBeenNthCalledWith(1, "/getSongInfo", { params: expect.objectContaining({ songid: "12345" }) });
expect(mockGet).toHaveBeenNthCalledWith(2, "/getMusicPlay", { params: expect.objectContaining({ songmid: "abc" }) });
});
it("separates a broken sidecar from a track without a URL", async () => {
const provider = new QQMusicProvider("http://127.0.0.1:3200");
mockGet.mockRejectedValue({ response: { status: 502, data: { hidden: "test-cookie" } } });
await expect(provider.getSongUrl("abc")).rejects.toMatchObject({
failure: { code: "upstream_request_failed", upstream: { httpStatus: 502 } },
});
expect(mockGet).toHaveBeenCalledOnce();
});
it("keeps tracks playable at a supported fallback quality during batch preflight", async () => {
const provider = new QQMusicProvider("http://127.0.0.1:3200");
provider.setQuality("exhigh");
mockGet.mockResolvedValueOnce({ data: { data: { playUrl: { abc: { url: "https://example.com/audio1" }, def: { url: "" } } } } });
mockGet.mockResolvedValueOnce({ data: { data: { playUrl: { def: { url: "https://example.com/audio2" } } } } });
await expect(provider.getPlayableSongIds(["abc", "def"])).resolves.toEqual(new Set(["abc", "def"]));
expect(mockGet).toHaveBeenNthCalledWith(2, "/getMusicPlay", { params: expect.objectContaining({ songmid: "def", quality: "128" }) });
});
it.each([{}, { abc: { url: "" } }, { abc: { url: "" }, def: { url: 17 } }])(
"does not interpret incomplete or unconfirmed HTTP 200 play maps as unavailable",
async (playUrl) => {
const provider = new QQMusicProvider("http://127.0.0.1:3200");
provider.setQuality("128");
mockGet.mockResolvedValue({ status: 200, data: { data: { playUrl } } });
await expect(provider.getPlayableSongIds(["abc", "def"])).resolves.toBeNull();
},
);
it("does not treat an upstream error inside HTTP 200 as a final no-URL result", async () => {
const provider = new QQMusicProvider("http://127.0.0.1:3200");
provider.setQuality("128");
mockGet.mockResolvedValue({ status: 200, data: { data: { code: 0, req_0: { code: 502 }, playUrl: { abc: { url: "" } } } } });
await expect(provider.getPlayableSongIds(["abc"])).resolves.toBeNull();
await expect(provider.getSongUrl("abc")).rejects.toMatchObject({
failure: { code: "upstream_request_failed", upstream: { code: 502 } },
});
});
it("accepts a fully confirmed no-play result and a numeric HTTP envelope success code", async () => {
const provider = new QQMusicProvider("http://127.0.0.1:3200");
provider.setQuality("128");
mockGet.mockResolvedValue({ status: 200, data: { code: 200, data: {
code: "0", req_0: { code: 0, data: { midurlinfo: [{ songmid: "abc", purl: "" }] } }, playUrl: { abc: { url: "" } },
} } });
await expect(provider.getPlayableSongIds(["abc"])).resolves.toEqual(new Set());
});
it("stops playback before sending a request when the sidecar port is occupied by another service", async () => {
const guard = () => { throw Object.assign(new Error("QQ sidecar port conflict"), { code: "QQ_API_PORT_CONFLICT" }); };
const provider = new QQMusicProvider("http://127.0.0.1:3200", undefined, guard);
await expect(provider.getSongUrl("abc")).rejects.toMatchObject({
failure: { code: "upstream_request_failed", message: expect.stringContaining("端口") },
});
expect(mockGet).not.toHaveBeenCalled();
});
});
describe("QQ adapter", () => {
it("mapQqSongs maps QQMusicApi-style song entries", () => {
const out = mapQqSongs([
+139 -47
View File
@@ -1,5 +1,6 @@
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios";
import { playbackRequestFailure, SongUrlUnavailable } from "./provider.js";
import type {
MusicProvider,
Song,
@@ -45,6 +46,53 @@ const qqFavApi = axios.create({
headers: { referer: "https://y.qq.com/" },
});
/** Formats supported by @sansenjian/qq-music-api 2.4's /getMusicPlay route. */
function qqPlaybackQuality(quality: string): string {
switch (quality) {
case "exhigh": return "320";
case "lossless":
case "hires":
case "jymaster": return "flac";
case "320":
case "flac":
case "ape":
case "m4a": return quality;
default: return "128";
}
}
function isQqNumericId(value: string): boolean {
return /^\d+$/.test(value);
}
interface QqPlaybackReply {
code?: unknown;
data?: {
code?: unknown;
req_0?: { code?: unknown; data?: { midurlinfo?: unknown } };
playUrl?: Record<string, { url?: unknown }>;
};
}
function readQqCode(raw: unknown): number | undefined {
const code = typeof raw === "string" && /^-?\d+$/.test(raw) ? Number(raw) : raw;
return typeof code === "number" && Number.isSafeInteger(code) ? code : undefined;
}
function qqPlaybackErrorCode(reply?: QqPlaybackReply): number | undefined {
const wrapper = readQqCode(reply?.code);
if (wrapper !== undefined && wrapper !== 0 && wrapper !== 200) return wrapper;
return [readQqCode(reply?.data?.code), readQqCode(reply?.data?.req_0?.code)]
.find(code => code !== undefined && code !== 0);
}
function confirmedQqMisses(reply: QqPlaybackReply): Set<string> {
const request = reply.data?.req_0;
const rows = request?.data?.midurlinfo;
if (readQqCode(request?.code) !== 0 || !Array.isArray(rows)) return new Set();
return new Set(rows.flatMap(row => typeof row?.songmid === "string" && row.purl === "" && !row.vkey ? [row.songmid] : []));
}
/** True when a search_type=2 album search entry really belongs to this singer.
* QQ fills singerMID for most albums; older entries only carry singer_list. */
function isArtistAlbum(a: any, artistId: string): boolean {
@@ -172,30 +220,47 @@ function computeGtk(pSkey: string): number {
export class QQMusicProvider implements MusicProvider {
readonly platform = "qq" as const;
private api: AxiosInstance;
private readonly sidecar: AxiosInstance;
private legacyCookie = "";
private quality = "exhigh";
private radarPage = 1;
constructor(baseUrl: string, readonly managedSession?: QQManagedSession) {
this.api = axios.create({
constructor(
baseUrl: string,
readonly managedSession?: QQManagedSession,
private readonly assertSidecarPort?: () => void,
) {
this.sidecar = axios.create({
baseURL: baseUrl,
timeout: 10000,
});
}
private get api(): AxiosInstance {
this.assertSidecarPort?.();
return this.sidecar;
}
private get cookie(): string {
return this.managedSession?.getCookie() ?? this.legacyCookie;
}
setQuality(quality: string): void {
this.quality = quality;
setQuality(quality: string | number): void {
if (quality === 128 || quality === 320) this.quality = String(quality);
else if (typeof quality === "string" && quality.trim()) this.quality = quality.trim();
}
getQuality(): string {
return this.quality;
}
getFallbackQualities(): string[] {
const primary = qqPlaybackQuality(this.quality);
if (primary === "flac" || primary === "ape") return ["320", "128"];
if (primary === "320") return ["128"];
return [];
}
private get cookieParams(): Record<string, string> {
return this.cookie ? { cookie: this.cookie } : {};
}
@@ -358,25 +423,37 @@ export class QQMusicProvider implements MusicProvider {
}
async getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null> {
const format = qqPlaybackQuality(quality ?? this.quality);
try {
const res = await this.api.get("/getMusicPlay", {
params: { songmid: songId, quality: quality ?? this.quality, ...this.cookieParams },
});
const playUrl = res.data?.data?.playUrl?.[songId];
if (playUrl?.url) return { url: playUrl.url, trialDuration: parseQqTrial(playUrl) };
} catch {
// try with songid
try {
const res = await this.api.get("/getMusicPlay", {
params: { songid: songId, quality: quality ?? this.quality, ...this.cookieParams },
});
const playUrl = res.data?.data?.playUrl?.[songId];
if (playUrl?.url) return { url: playUrl.url, trialDuration: parseQqTrial(playUrl) };
} catch {
// ignore
const api = this.api;
// The play endpoint only accepts MIDs. Old queues and explicit ID
// requests can carry a numeric ID, which the metadata endpoint resolves.
const songmid = isQqNumericId(songId) ? (await this.getSongDetail(songId))?.id : songId;
if (!songmid || isQqNumericId(songmid)) {
throw new SongUrlUnavailable({ platform: this.platform, songId, code: "unknown", message: "QQ 音乐未返回该曲目的 MID" });
}
const response = await api.get<QqPlaybackReply>("/getMusicPlay", {
params: { songmid, quality: format, resType: "full", ...this.cookieParams },
});
const code = qqPlaybackErrorCode(response.data);
if (code !== undefined) {
throw new SongUrlUnavailable({
platform: this.platform, songId, code: "upstream_request_failed", message: `QQ 音乐播放请求返回错误(${code})`,
upstream: { code },
});
}
const playUrl = response.data?.data?.playUrl?.[songmid];
if (typeof playUrl?.url === "string" && playUrl.url) {
return { url: playUrl.url, trialDuration: parseQqTrial(playUrl) };
}
} catch (error) {
if (error instanceof SongUrlUnavailable) throw error;
throw playbackRequestFailure(this.platform, songId, error);
}
return null;
throw new SongUrlUnavailable({
platform: this.platform, songId, code: "unknown",
message: `QQ 音乐未返回播放地址(${format})`,
});
}
/**
@@ -390,37 +467,49 @@ export class QQMusicProvider implements MusicProvider {
* the URL well under typical 8KB query-string limits and to keep per-
* request latency bounded (~2-3s per 100 mids).
*
* Returns:
* - non-null Set: authoritative result. Empty Set means all songs are
* unplayable; non-empty means filter to those mids.
* - null: every chunk failed. Caller should fall back to sequential
* retry rather than treating as "all unplayable".
* Check lower configured formats for MIDs missing from the first result.
* Return null on an incomplete response so the caller can resolve tracks
* normally instead of discarding unverified entries.
*/
async getPlayableSongIds(songIds: string[]): Promise<Set<string> | null> {
if (songIds.length === 0) return new Set();
if (songIds.some(isQqNumericId)) return null;
const CHUNK = 100; // ~14 chars/mid * 100 + commas ≈ 1.5KB
const playable = new Set<string>();
let allChunksFailed = true;
const formats = [qqPlaybackQuality(this.quality), ...this.getFallbackQualities()];
for (let i = 0; i < songIds.length; i += CHUNK) {
const slice = songIds.slice(i, i + CHUNK);
try {
const res = await this.api.get("/getMusicPlay", {
params: { songmid: slice.join(","), quality: this.quality, ...this.cookieParams },
});
const playUrlMap: Record<string, { url?: string }> | undefined =
res.data?.data?.playUrl;
if (!playUrlMap) continue; // chunk-level failure, try next
allChunksFailed = false;
for (const [mid, info] of Object.entries(playUrlMap)) {
if (info?.url) playable.add(mid);
let remaining = songIds.slice(i, i + CHUNK);
const unconfirmed = new Set<string>();
for (const quality of formats) {
try {
const res = await this.api.get<QqPlaybackReply>("/getMusicPlay", {
params: { songmid: remaining.join(","), quality, resType: "full", ...this.cookieParams },
});
const playUrlMap = res.data?.data?.playUrl;
if (qqPlaybackErrorCode(res.data) !== undefined || !playUrlMap ||
remaining.some(mid => !Object.hasOwn(playUrlMap, mid) || typeof playUrlMap[mid]?.url !== "string")) return null;
// The wrapper synthesizes empty URLs even if Tencent omitted a MID
// or returned a transient error. Require an upstream row before
// interpreting a blank URL as negative evidence for that quality.
const confirmed = confirmedQqMisses(res.data);
remaining = remaining.filter(mid => {
if (!playUrlMap[mid].url) {
if (!confirmed.has(mid)) unconfirmed.add(mid);
return true;
}
unconfirmed.delete(mid);
playable.add(mid);
return false;
});
if (remaining.length === 0) break;
} catch {
return null;
}
} catch {
// chunk-level failure — keep going so a transient error on one
// chunk doesn't poison the whole batch.
}
if (unconfirmed.size > 0) return null;
}
return allChunksFailed ? null : playable;
return playable;
}
async getSongDetail(songId: string): Promise<Song | null> {
@@ -432,9 +521,9 @@ export class QQMusicProvider implements MusicProvider {
// stub is sufficient to let /play-by-id and /add-by-id flows succeed.
try {
const res = await this.api.get("/getSongInfo", {
params: { songmid: songId, ...this.cookieParams },
params: { ...(isQqNumericId(songId) ? { songid: songId } : { songmid: songId }), ...this.cookieParams },
});
const s = res.data?.response?.data;
const s = res.data?.response?.songinfo?.data ?? res.data?.response?.data;
if (s && s.track_info) {
const t = s.track_info;
return {
@@ -483,11 +572,14 @@ export class QQMusicProvider implements MusicProvider {
* caller can fall back to the minimal stub. */
private async fetchSongDetailViaMusicu(songId: string): Promise<Song | null> {
try {
const numeric = isQqNumericId(songId);
const song_id = Number(songId);
if (numeric && (!Number.isSafeInteger(song_id) || song_id < 1)) return null;
const reqData = JSON.stringify({
req_0: {
module: "music.pf_song_detail_svr",
method: "get_song_detail_yqq",
param: { song_mid: songId, song_type: 0 },
param: { ...(numeric ? { song_id } : { song_mid: songId }), song_type: 0 },
},
});
const res = await qqMusicuApi.get("/cgi-bin/musicu.fcg", {
@@ -842,11 +934,11 @@ export class QQMusicProvider implements MusicProvider {
* A view of the same provider logged in as another account (#164 follow-up):
* a web user's own QQ 音乐 login instead of the bot's shared one.
*
* The per-user view points at the SAME API server (`this.api.defaults.baseURL`)
* The per-user view points at the same guarded API server
* — only the cookie differs, so the shared login keeps its own instance.
*/
withCookie(cookie: string): QQMusicProvider {
const view = new QQMusicProvider(this.api.defaults.baseURL ?? "");
const view = new QQMusicProvider(this.sidecar.defaults.baseURL ?? "", undefined, this.assertSidecarPort);
view.quality = this.quality;
view.setCookie(cookie);
return view;
+185 -6
View File
@@ -6,6 +6,7 @@ import request from "supertest";
import { createPlayerRouter } from "./player.js";
import { BotInstance } from "../../bot/instance.js";
import { PlayQueue } from "../../audio/queue.js";
import type { BotDatabase } from "../../data/database.js";
function song(id: string): Song {
return {
@@ -75,8 +76,8 @@ describe("collectArtistSongs (play-artist all:true)", () => {
});
});
describe("play-artist playback serialization", () => {
it("keeps the queue and audible song consistent when single-song playback overlaps artist playback", async () => {
describe("collection playback serialization", () => {
it.each(["artist", "album", "playlist"])("serializes %s playback and single-song playback", async kind => {
const queue = new PlayQueue();
let audible: string | null = null;
let releaseArtist!: () => void;
@@ -87,7 +88,14 @@ describe("play-artist playback serialization", () => {
const singleArrived = new Promise<void>((resolve) => { notifySingleArrived = resolve; });
const bot: any = {
playGate: Promise.resolve(),
getProviderFor: () => ({ platform: "netease", getArtistSongs: async () => [song("A")], getArtistAllSongs: async () => page(["A"], 1, false) }),
getProviderFor: () => ({
platform: "netease",
getAlbumSongs: async () => [song("A")],
getPlaylistSongs: async () => [song("A")],
getArtistSongs: async () => [song("A")],
getArtistAllSongs: async () => page(["A"], 1, false),
}),
emit: vi.fn(),
getPlayer: () => ({ stop: () => { audible = null; }, resetFailures: () => {} }),
getQueueManager: () => queue,
resolveAndPlay: async (track: Song) => {
@@ -110,7 +118,8 @@ describe("play-artist playback serialization", () => {
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
app.use("/api/player/b/play-song", (_req, _res, next) => { notifySingleArrived(); next(); });
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
const artistRequest = request(app).post("/api/player/b/play-artist").send({ artistId: "artist", platform: "netease" }).then((res) => res);
const collectionRequest = request(app).post(`/api/player/b/play-${kind}`)
.send({ [`${kind}Id`]: "collection", platform: "netease" }).then((res) => res);
await artistStarted;
const singleRequest = request(app).post("/api/player/b/play-song").send({ song: song("B") }).then((res) => res);
// Let the overlapping HTTP request enter the real route while A's URL is pending.
@@ -119,11 +128,181 @@ describe("play-artist playback serialization", () => {
await Promise.resolve();
const whileArtistPending = queue.current()?.id;
releaseArtist();
const [artistResponse, singleResponse] = await Promise.all([artistRequest, singleRequest]);
expect(artistResponse.status).toBe(200);
const [collectionResponse, singleResponse] = await Promise.all([collectionRequest, singleRequest]);
expect(collectionResponse.status).toBe(200);
expect(singleResponse.status).toBe(200);
expect(whileArtistPending).toBe("A");
expect(queue.current()?.id).toBe("B");
expect(audible).toBe("B");
});
});
describe("collection preflight", () => {
it.each(["playlist", "album", "artist"])("checks QQ %s availability using the room's playback account", async kind => {
const queue = new PlayQueue();
const personalTracks = [{ ...song("personal-library-track"), platform: "qq" }];
const readLibrary = vi.fn(async () => personalTracks);
const personal = {
platform: "qq",
getPlaylistSongs: readLibrary,
getAlbumSongs: readLibrary,
getArtistSongs: readLibrary,
getPlayableSongIds: vi.fn(async () => new Set<string>()),
};
const shared = {
platform: "qq",
withCookie: vi.fn(() => personal),
getPlayableSongIds: vi.fn(async () => new Set(["personal-library-track"])),
};
const bot = {
getProviderFor: () => shared,
getQueueManager: () => queue,
getPlayer: () => ({ stop: vi.fn(), resetFailures: vi.fn() }),
runExclusive: (work: () => Promise<unknown>) => work(),
resolveAndPlay: vi.fn(async () => true),
emit: vi.fn(),
};
const db = {
getUserMusicPreference: () => null,
getUserMusicCookie: () => null,
getGrantedMusicAccount: () => ({ cookie: "private-test-cookie", label: "Member's account", accountId: "account" }),
} as unknown as BotDatabase;
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as { user?: unknown }).user = { id: "member", role: "member", bots: new Set(["b"]), capabilities: new Set(["player.control"]) };
next();
});
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any,
db, undefined, undefined, undefined, { perUserMusicAccounts: true }));
const response = await request(app).post(`/api/player/b/play-${kind}`)
.send({ [`${kind}Id`]: "id", platform: "qq" }).expect(200);
expect(response.body).toMatchObject({ ok: true });
expect(response.text).not.toContain("private-test-cookie");
expect(readLibrary).toHaveBeenCalledOnce();
expect(personal.getPlayableSongIds).not.toHaveBeenCalled();
expect(shared.getPlayableSongIds).toHaveBeenCalledWith(["personal-library-track"]);
expect(queue.current()?.id).toBe("personal-library-track");
});
it.each([
["playlist", "empty", 200],
["playlist", "unavailable", 200],
["album", "empty", 200],
["album", "error", 500],
])("preserves current playback if the %s is %s", async (kind, result, status) => {
const queue = new PlayQueue();
queue.add(song("playing"));
queue.play();
const player = { stop: vi.fn(), resetFailures: vi.fn() };
const loadSongs = async () => {
if (result === "error") throw new Error("Upstream failed");
return result === "empty" ? [] : [song("next")];
};
const bot = {
getProviderFor: () => ({
platform: "qq",
getPlaylistSongs: loadSongs,
getAlbumSongs: loadSongs,
getPlayableSongIds: async () => new Set<string>(),
}),
getQueueManager: () => queue,
getPlayer: () => player,
};
const app = express();
app.use(express.json());
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
const response = await request(app).post(`/api/player/b/play-${kind}`).send({ [`${kind}Id`]: "id", platform: "qq" });
expect(response.status).toBe(status);
if (status === 200) expect(response.body).toMatchObject({ ok: false });
expect(player.stop).not.toHaveBeenCalled();
expect(player.resetFailures).not.toHaveBeenCalled();
expect(queue.current()?.id).toBe("playing");
});
});
describe("play a queue position", () => {
function fixture() {
const queue = new PlayQueue();
queue.add(song("playing"));
queue.add(song("unavailable"));
queue.play();
const player = { stop: vi.fn(), resetFailures: vi.fn(), getPlaybackSessionId: () => 1 };
const bot = {
getQueueManager: () => queue,
getPlayer: () => player,
runExclusive: (work: () => Promise<unknown>) => work(),
resolveAndPlay: vi.fn(async (_song: Song, onFailure?: (failure: { message: string }) => void) => {
onFailure?.({ message: "Source returned no stream" });
return false;
}),
emit: vi.fn(),
};
const app = express();
app.use(express.json());
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
return { app, bot, player, queue };
}
it("rejects fractional positions without stopping the playing track", async () => {
const { app, player, queue } = fixture();
expect((await request(app).post("/api/player/b/play-at").send({ index: 0.5 })).status).toBe(400);
expect(player.stop).not.toHaveBeenCalled();
expect(queue.current()?.id).toBe("playing");
});
it("returns the URL failure and publishes the selected stopped track", async () => {
const { app, bot, queue } = fixture();
const response = await request(app).post("/api/player/b/play-at").send({ index: 1 });
expect(response.body).toEqual({ ok: false, message: expect.stringContaining("Source returned no stream") });
expect(bot.emit).toHaveBeenCalledWith("stateChange");
expect(queue.current()?.id).toBe("unavailable");
});
});
it("reports a failed restart while the existing track is still playing", async () => {
const bot = {
runExclusive: (work: () => Promise<unknown>) => work(),
async playSingleSong(_song: Song, _requester: string, failure: (error: { message: string }, continues: boolean) => void) {
failure({ message: "No URL" }, true);
return false;
},
};
const app = express();
app.use(express.json());
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
const response = await request(app).post("/api/player/b/play-song").send({ song: song("playing") });
expect(response.body).toEqual({ ok: false, message: expect.stringContaining("当前曲目继续播放") });
});
it("tries the newly appended track when idle and reports a failed URL lookup", async () => {
const queue = new PlayQueue();
queue.add(song("already-queued"));
const bot = {
getQueueManager: () => queue,
getPlayer: () => ({ getState: () => "idle", resetFailures: vi.fn() }),
runExclusive: (work: () => Promise<unknown>) => work(),
resolveAndPlay: vi.fn(async (_track: Song, onFailure?: (failure: { message: string }) => void) => {
onFailure?.({ message: "No URL" });
return false;
}),
emit: vi.fn(),
};
const app = express();
app.use(express.json());
app.use((req, _res, next) => { (req as any).user = { role: "admin" }; next(); });
app.use("/api/player", createPlayerRouter({ getBot: () => bot } as any, { error: vi.fn() } as any));
const response = await request(app).post("/api/player/b/add-song").send({ song: song("newly-added") });
expect(bot.resolveAndPlay.mock.calls.map(([track]) => track.id)).toEqual(["newly-added"]);
expect(queue.list().map(track => track.id)).toEqual(["already-queued", "newly-added"]);
expect(response.body).toEqual({ ok: false, message: expect.stringContaining("No URL") });
});
+102 -178
View File
@@ -1,5 +1,6 @@
import { Router, type Request } from "express";
import type { BotInstance } from "../../bot/instance.js";
import { blocksProviderForAdvance } from "../../bot/url-retry.js";
import type { QueuedSong } from "../../audio/queue.js";
import type { BotManager } from "../../bot/manager.js";
import type { BotDatabase } from "../../data/database.js";
@@ -42,6 +43,21 @@ export async function collectArtistSongs(
return songs;
}
async function filterCollectionForRoom(
bot: BotInstance,
platform: Song["platform"],
songs: Song[],
): Promise<Song[]> {
if (platform !== "qq") return songs;
// Metadata can come from the caller's account. Room playback uses the
// bot's shared account, so its entitlements must drive the batch check too.
const playbackProvider = bot.getProviderFor("qq") as MusicProvider & {
getPlayableSongIds?: (ids: string[]) => Promise<Set<string> | null>;
};
const available = await playbackProvider.getPlayableSongIds?.(songs.map(song => song.id));
return available ? songs.filter(song => available.has(song.id)) : songs;
}
export function createPlayerRouter(
botManager: BotManager,
logger: Logger,
@@ -104,14 +120,43 @@ export function createPlayerRouter(
return reason ? `无法播放「${label}」:${reason}` : `无法播放「${label}」`;
};
async function startCollection(bot: BotInstance, first: QueuedSong | null) {
let failure: PlayFailure | undefined;
const capture = (reason: PlayFailure) => { failure = reason; };
let started = first ? await bot.resolveAndPlay(first, capture) : false;
if (first && !started && failure?.code !== "risk_control" && bot.getQueueManager().current() === first) {
started = await bot.playNext(20, capture);
}
return { started, reason: failure?.message };
async function startCollection(
bot: BotInstance, songs: Song[], platform: Song["platform"], requestedBy: string | undefined, totalCount: number,
) {
return bot.runExclusive(async () => {
bot.getPlayer().stop();
bot.getPlayer().resetFailures();
const queue = bot.getQueueManager();
queue.clear();
for (const song of songs) {
queue.add({ ...song, platform, requestedBy });
}
bot.cleanupQueuedLocalSongs?.("queue_replaced");
const mode = queue.getMode();
const first: QueuedSong | null = mode === "random" || mode === "rloop"
? queue.playAt(Math.floor(Math.random() * queue.size()))
: queue.play();
// Publish the new idle queue even if the first URL lookup ultimately fails.
bot.emit("stateChange");
let failure: PlayFailure | undefined;
const capture = (reason: PlayFailure) => { failure = reason; };
let started = first ? await bot.resolveAndPlay(first, capture) : false;
if (first && !started && failure && !blocksProviderForAdvance(failure.code) && queue.current() === first) {
// Many collections contain several consecutive unavailable tracks.
started = await bot.playNext(20, capture);
}
const playing = queue.current();
const loaded = songs.length < totalCount
? `已加载 ${songs.length}/${totalCount} 首(其余无法播放)`
: `已加载 ${songs.length} 首`;
const reason = failure?.message;
return started && playing
? { ok: true, message: `${loaded},正在播放:${playing.name}` }
: { ok: false, message: `${loaded},但无法开始播放${reason ? `:${reason}` : "。"}` };
});
}
/** Map API platform string to the corresponding command flag. */
@@ -191,7 +236,14 @@ export function createPlayerRouter(
router.post("/:botId/pause", authorize({ capability: "player.control", guestFlag: "transport" }), simpleCommand("!pause"));
router.post("/:botId/resume", authorize({ capability: "player.control", guestFlag: "transport" }), simpleCommand("!resume"));
router.post("/:botId/next", authorize({ capability: "player.control", guestFlag: "skip" }), simpleCommand("!next"));
router.post("/:botId/next", authorize({ capability: "player.control", guestFlag: "skip" }), async (req, res) => {
try {
const bot: BotInstance = (req as any).bot;
res.json(await bot.skipToNext());
} catch (err) {
res.status(500).json({ error: musicRequestError(err).message });
}
});
router.post("/:botId/prev", authorize({ capability: "player.control" }), simpleCommand("!prev"));
router.post("/:botId/stop", authorize({ capability: "player.control" }), simpleCommand("!stop"));
router.post("/:botId/clear", authorize({ capability: "player.queue", guestFlag: "removeClear" }), simpleCommand("!clear"));
@@ -210,10 +262,7 @@ export function createPlayerRouter(
const resolveFmProvider = () => fmProvider(scope, bot, platform);
const message = await bot.startFm(resolveFmProvider(), requesterName(req), resolveFmProvider);
res.json({
ok:
!message.startsWith("No FM songs") &&
!message.includes("not available") &&
!message.includes("not connected"),
ok: message.startsWith("Personal FM started") || message.startsWith("QQ Radar FM started"),
message,
});
} catch (err) {
@@ -312,10 +361,10 @@ export function createPlayerRouter(
// Jump to a specific index in the queue (without clearing it)
router.post("/:botId/play-at", authorize({ capability: "player.control" }), async (req, res) => {
try {
const bot = (req as any).bot;
const bot: BotInstance = (req as any).bot;
const { index } = req.body;
if (typeof index !== "number" || index < 0) {
res.status(400).json({ error: "index is required" });
if (!Number.isSafeInteger(index) || index < 0) {
res.status(400).json({ error: "index must be a non-negative integer" });
return;
}
// Serialize the index-validation + stop/reset/playAt/resolveAndPlay so a
@@ -326,21 +375,23 @@ export function createPlayerRouter(
// Validate the index BEFORE stopping current playback — otherwise an
// invalid index silently kills the user's current song and leaves the
// queue idle.
if (index >= queue.size()) {
return { status: 400 as const, body: { error: "Invalid queue index" } };
}
bot.getPlayer().stop(true);
bot.getPlayer().resetFailures();
const song = queue.playAt(index);
if (!song) {
return { status: 400 as const, body: { error: "Invalid queue index" } };
}
const ok = await bot.resolveAndPlay(song);
const player = bot.getPlayer();
player.stop(true);
player.resetFailures();
const session = player.getPlaybackSessionId();
bot.emit("stateChange");
let reason: string | undefined;
const ok = await bot.resolveAndPlay(song, failure => { reason = failure.message; });
if (!ok) {
bot.getPlayer().stop();
return { body: { message: `Cannot play: ${song.name}` } };
// Abandon this transition's silence loop, leaving newer playback alone.
if (queue.current() === song && player.getPlaybackSessionId() === session) player.stop();
return { body: { ok: false, message: whyUnplayable(song, reason) } };
}
return { body: { message: `Now playing: ${song.name} - ${song.artist}` } };
return { body: { ok: true, message: `Now playing: ${song.name} - ${song.artist}` } };
});
if (result.status) {
res.status(result.status).json(result.body);
@@ -381,75 +432,20 @@ export function createPlayerRouter(
// which the router's constructor params did not.
const provider = scopedProvider(req, bot, platform);
// Stop current playback
bot.getPlayer().stop();
bot.getPlayer().resetFailures();
const songs = await provider.getPlaylistSongs(playlistId);
if (songs.length === 0) {
res.json({ message: "Playlist is empty" });
res.json({ ok: false, message: "Playlist is empty" });
return;
}
// QQ-specific optimization: many users' QQ playlists contain a
// large fraction of songs that return result=104003 (region/copyright
// restricted). Batch-resolve URLs once and only queue the playable
// ones, otherwise the playback retry loop wastes time guessing.
let queueable: { id: string }[] = songs;
const totalCount = songs.length;
const qqLike = provider as { getPlayableSongIds?: (ids: string[]) => Promise<Set<string> | null> };
if (typeof qqLike.getPlayableSongIds === "function") {
const playable = await qqLike.getPlayableSongIds(songs.map((s: { id: string }) => s.id));
if (playable !== null) {
// Authoritative answer from upstream — even an empty set means
// "we know none are playable", short-circuit immediately rather
// than wasting 20+ retries.
queueable = songs.filter((s: { id: string }) => playable.has(s.id));
}
// If null, the batch endpoint itself errored — fall through to
// the sequential retry path, which still has a chance.
}
const queueable = await filterCollectionForRoom(bot, provider.platform, songs);
if (queueable.length === 0) {
res.json({ ok: false, message: `歌单 ${totalCount} 首歌曲均无法播放` });
return;
}
const queue = bot.getQueueManager();
queue.clear();
for (const song of queueable) {
queue.add({ ...song, platform: provider.platform, requestedBy: requesterName(req) });
}
// Sweep AFTER the queue is rebuilt: the previous queue's local uploads are
// released and deleted, but an empty/failed playlist (early return above)
// leaves the previous queue — and its files — intact.
bot.cleanupQueuedLocalSongs?.("queue_replaced");
// Use queue.play() for sequential, or pick random index for random modes
const mode = queue.getMode();
let first;
if (mode === "random" || mode === "rloop") {
const idx = Math.floor(Math.random() * queue.size());
first = queue.playAt(idx);
} else {
first = queue.play();
}
// If the first picked song can't resolve (e.g., QQ song with no
// streaming entitlement → result 104003), fall back to playNext's
// retry-skip behavior. Use a higher retry budget than the default
// trackEnd auto-advance because user-initiated playlist plays
// commonly have long contiguous runs of unplayable songs.
const { started, reason } = await startCollection(bot, first);
const playing = queue.current();
const loadedMsg = queueable.length < totalCount
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
: `已加载 ${queueable.length} 首`;
if (started && playing) {
res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` });
} else {
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
}
res.json(await startCollection(bot, queueable, provider.platform, requesterName(req), totalCount));
} catch (err) {
const error = musicRequestError(err);
logger.error({ err: error }, "Play playlist failed");
@@ -468,60 +464,20 @@ export function createPlayerRouter(
}
const provider = scopedProvider(req, bot, platform);
// Stop current playback
bot.getPlayer().stop();
bot.getPlayer().resetFailures();
const songs = await provider.getAlbumSongs(albumId);
if (songs.length === 0) {
res.json({ message: "Album is empty" });
res.json({ ok: false, message: "Album is empty" });
return;
}
// QQ-specific optimization: batch-resolve playable IDs to avoid
// wasting retries on region/copyright-restricted tracks.
let queueable: { id: string }[] = songs;
const totalCount = songs.length;
const qqLike = provider as { getPlayableSongIds?: (ids: string[]) => Promise<Set<string> | null> };
if (typeof qqLike.getPlayableSongIds === "function") {
const playable = await qqLike.getPlayableSongIds(songs.map((s: { id: string }) => s.id));
if (playable !== null) {
queueable = songs.filter((s: { id: string }) => playable.has(s.id));
}
}
const queueable = await filterCollectionForRoom(bot, provider.platform, songs);
if (queueable.length === 0) {
res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无法播放` });
return;
}
const queue = bot.getQueueManager();
queue.clear();
for (const song of queueable) {
queue.add({ ...song, platform: provider.platform, requestedBy: requesterName(req) });
}
// Sweep AFTER the queue is rebuilt (see play-playlist).
bot.cleanupQueuedLocalSongs?.("queue_replaced");
const mode = queue.getMode();
let first;
if (mode === "random" || mode === "rloop") {
const idx = Math.floor(Math.random() * queue.size());
first = queue.playAt(idx);
} else {
first = queue.play();
}
const { started, reason } = await startCollection(bot, first);
const playing = queue.current();
const loadedMsg = queueable.length < totalCount
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
: `已加载 ${queueable.length} 首`;
if (started && playing) {
res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` });
} else {
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
}
res.json(await startCollection(bot, queueable, provider.platform, requesterName(req), totalCount));
} catch (err) {
const error = musicRequestError(err);
logger.error({ err: error }, "play-album failed");
@@ -562,55 +518,14 @@ export function createPlayerRouter(
return;
}
// Same QQ batch-resolve optimization as play-album: drop tracks that are
// region/copyright blocked instead of burning retries on them.
let queueable: { id: string }[] = songs;
const totalCount = songs.length;
const qqLike = provider as { getPlayableSongIds?: (ids: string[]) => Promise<Set<string> | null> };
if (typeof qqLike.getPlayableSongIds === "function") {
const playable = await qqLike.getPlayableSongIds(songs.map((s: { id: string }) => s.id));
if (playable !== null) {
queueable = songs.filter((s: { id: string }) => playable.has(s.id));
}
}
const queueable = await filterCollectionForRoom(bot, provider.platform, songs);
if (queueable.length === 0) {
res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无法播放` });
return;
}
// Catalogue and copyright lookups leave current playback running. Only
// the queue replacement and playback itself occupy the shared play gate.
const body = await bot.runExclusive(async () => {
bot.getPlayer().stop();
bot.getPlayer().resetFailures();
const queue = bot.getQueueManager();
queue.clear();
for (const song of queueable) {
queue.add({ ...song, platform: provider.platform, requestedBy: requesterName(req) });
}
// Sweep AFTER the queue is rebuilt (see play-playlist).
bot.cleanupQueuedLocalSongs?.("queue_replaced");
const mode = queue.getMode();
let first;
if (mode === "random" || mode === "rloop") {
const idx = Math.floor(Math.random() * queue.size());
first = queue.playAt(idx);
} else {
first = queue.play();
}
const { started, reason } = await startCollection(bot, first);
const playing = queue.current();
const loadedMsg = queueable.length < totalCount
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
: `已加载 ${queueable.length} 首`;
return started && playing
? { ok: true, message: `${loadedMsg},正在播放:${playing.name}` }
: { ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` };
});
res.json(body);
res.json(await startCollection(bot, queueable, provider.platform, requesterName(req), totalCount));
} catch (err) {
const error = musicRequestError(err);
logger.error({ err: error }, "play-artist failed");
@@ -625,7 +540,7 @@ export function createPlayerRouter(
// requests can't interleave the queue mutation + playback (#119).
router.post("/:botId/play-song", authorize({ capability: "player.control" }), async (req, res) => {
try {
const bot = (req as any).bot;
const bot: BotInstance = (req as any).bot;
const { song } = req.body;
if (!song || !song.id || !song.platform) {
res.status(400).json({ error: "song object with id and platform is required" });
@@ -639,11 +554,15 @@ export function createPlayerRouter(
// clear branch — do NOT also call it here, or it would delete retained
// local uploads in keep-queue mode.
const body = await bot.runExclusive(async () => {
let reason: string | undefined;
const ok = await bot.playSingleSong({ ...song }, requesterName(req), (failure: PlayFailure) => { reason = failure.message; });
let errorMessage = whyUnplayable(song);
const ok = await bot.playSingleSong({ ...song }, requesterName(req), (failure, currentTrackContinues) => {
errorMessage = currentTrackContinues
? `未能重新播放「${song.name || song.id}」,当前曲目继续播放:${failure.message}`
: whyUnplayable(song, failure.message);
});
return ok
? { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` }
: { ok: false, message: whyUnplayable(song, reason) };
: { ok: false, message: errorMessage };
});
res.json(body);
} catch (err) {
@@ -738,7 +657,7 @@ export function createPlayerRouter(
router.post("/:botId/add-song", authorize({ capability: "player.queue", guestFlag: "addToQueue" }), async (req, res) => {
try {
const bot = (req as any).bot;
const bot: BotInstance = (req as any).bot;
const { song } = req.body;
if (!song || !song.id || !song.platform) {
res.status(400).json({ error: "song object with id and platform is required" });
@@ -757,13 +676,18 @@ export function createPlayerRouter(
// If nothing was playing, start this newly-added song immediately.
if (wasIdle) {
queue.playAt(queue.size() - 1);
const added = queue.playAt(queue.size() - 1)!;
bot.getPlayer().resetFailures();
await bot.resolveAndPlay(queue.current()!);
return { message: `Now playing: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` };
let reason: string | undefined;
const ok = await bot.resolveAndPlay(added, failure => { reason = failure.message; });
if (!ok) {
bot.emit("stateChange");
return { ok: false, message: `已加入队列,但${whyUnplayable(added, reason)}` };
}
return { ok: true, message: `Now playing: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` };
}
return { message: `Added to queue: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'} (position ${queue.size()})` };
return { ok: true, message: `Added to queue: ${song.name || 'Unknown'} - ${song.artist || 'Unknown'} (position ${queue.size()})` };
});
res.json(body);
} catch (err) {
+82 -2
View File
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import { interpolateElapsed, type TimingState } from "./player.js";
import { describe, it, expect, vi, afterEach, beforeEach } from "vitest";
import { createPinia, setActivePinia } from "pinia";
import axios from "axios";
import { interpolateElapsed, usePlayerStore, type Song, type TimingState } from "./player.js";
afterEach(() => {
vi.restoreAllMocks();
@@ -42,3 +44,81 @@ describe("interpolateElapsed", () => {
expect(interpolateElapsed(t, false, 180)).toBe(180);
});
});
const track: Song = { id: "song", name: "song", artist: "", album: "", coverUrl: "", duration: 180, platform: "netease" };
describe("playback request timing", () => {
beforeEach(() => {
vi.stubGlobal("window", { matchMedia: () => ({ matches: false }) });
vi.useFakeTimers();
setActivePinia(createPinia());
});
afterEach(() => {
vi.clearAllTimers();
vi.useRealTimers();
vi.unstubAllGlobals();
});
it.each(["playSong", "playPlaylist", "playAlbum", "playArtist", "next", "playAtIndex", "startFm"] as const)(
"keeps the current clock when %s fails",
async (action) => {
const store = usePlayerStore();
store.activeBotId = "a";
const current = timing({ serverElapsed: 63, serverSyncTime: 10_000, wasPlaying: true });
store.timings.a = current;
vi.spyOn(axios, "post").mockResolvedValue({ data: { ok: false, message: "播放失败" } });
if (action === "playSong") await store.playSong(track);
else if (action === "startFm") await store.startFm();
else if (action === "next") await store.next();
else if (action === "playAtIndex") await store.playAtIndex(1);
else await store[action]("collection");
expect(store.timings.a).toEqual(current);
expect(store.notification?.type).toBe("error");
},
);
it("keeps an in-flight elapsed response attached to its original bot", async () => {
const store = usePlayerStore();
const status = {
name: "bot", connected: true, playing: true, paused: false, currentSong: track,
queueSize: 1, volume: 50, playMode: "sequential",
};
store.bots = [{ ...status, id: "a" }, { ...status, id: "b" }];
store.activeBotId = "a";
store.timings.b = timing({ serverElapsed: 10 });
let sendElapsed!: (response: { data: { elapsed: number } }) => void;
const response = new Promise<{ data: { elapsed: number } }>(resolve => { sendElapsed = resolve; });
vi.spyOn(axios, "get").mockReturnValue(response);
const syncing = store.syncElapsed();
store.activeBotId = "b";
sendElapsed({ data: { elapsed: 58 } });
await syncing;
expect(store.timings.a?.serverElapsed).toBe(58);
expect(store.timings.b?.serverElapsed).toBe(10);
});
it("freezes steady elapsed samples and interpolates again when audio advances", async () => {
const store = usePlayerStore();
store.activeBotId = "a";
store.bots = [{
id: "a", name: "bot", connected: true, playing: true, paused: false, currentSong: track,
queueSize: 1, volume: 50, playMode: "sequential",
}];
const poll = vi.spyOn(axios, "get").mockResolvedValue({ data: { elapsed: 60 } });
vi.setSystemTime(10000);
await store.syncElapsed();
vi.setSystemTime(13000);
await store.syncElapsed();
vi.setSystemTime(14000);
expect(store.liveElapsed()).toBe(60);
poll.mockResolvedValue({ data: { elapsed: 61 } });
await store.syncElapsed();
vi.setSystemTime(15000);
expect(store.liveElapsed()).toBe(62);
});
});
+55 -45
View File
@@ -82,6 +82,7 @@ export interface TimingState {
serverElapsed: number;
serverSyncTime: number;
wasPlaying: boolean;
lastPolledElapsed?: number;
}
const HOME_CACHE_TTL = 5 * 60 * 1000;
@@ -312,6 +313,7 @@ export const usePlayerStore = defineStore('player', {
serverElapsed: status.elapsed,
serverSyncTime: Date.now(),
wasPlaying: status.playing && !status.paused,
lastPolledElapsed: undefined,
});
}
@@ -321,6 +323,7 @@ export const usePlayerStore = defineStore('player', {
serverElapsed: status.elapsed ?? 0,
serverSyncTime: Date.now(),
wasPlaying: status.playing && !status.paused,
lastPolledElapsed: undefined,
});
}
},
@@ -396,20 +399,28 @@ export const usePlayerStore = defineStore('player', {
serverElapsed: bot.elapsed,
serverSyncTime: Date.now(),
wasPlaying: bot.playing && !bot.paused,
lastPolledElapsed: undefined,
});
}
}
},
/** Poll server for real elapsed time for active bot */
async syncElapsed() {
if (!this.activeBotId || !this.isPlaying) return;
/** Poll the same bot for authoritative elapsed time. */
async syncElapsed(botId?: string) {
botId ??= this.activeBotId ?? undefined;
if (!botId || !this.bots.some(bot => bot.id === botId && bot.playing && !bot.paused)) return;
const timing = this.timings[botId];
try {
const res = await axios.get(`/api/player/${this.activeBotId}/elapsed`);
this._setTiming(this.activeBotId, {
serverElapsed: res.data.elapsed,
const res = await axios.get(`/api/player/${botId}/elapsed`);
// A newer WebSocket update or poll supersedes this result.
if (this.timings[botId] !== timing) return;
const elapsed = res.data.elapsed;
if (!Number.isFinite(elapsed)) return;
this._setTiming(botId, {
serverElapsed: elapsed,
serverSyncTime: Date.now(),
wasPlaying: true,
wasPlaying: timing?.lastPolledElapsed !== elapsed,
lastPolledElapsed: elapsed,
});
} catch {
// ignore
@@ -417,13 +428,7 @@ export const usePlayerStore = defineStore('player', {
},
async fetchQueue() {
if (!this.activeBotId) return;
try {
const res = await axios.get(`/api/player/${this.activeBotId}/queue`);
this.queues[this.activeBotId] = res.data.queue ?? [];
} catch {
// ignore
}
if (this.activeBotId) await this.fetchQueueForBot(this.activeBotId);
},
async fetchQueueForBot(botId: string) {
@@ -446,10 +451,11 @@ export const usePlayerStore = defineStore('player', {
},
async playAtIndex(index: number) {
if (!this.activeBotId) return;
await axios.post(`/api/player/${this.activeBotId}/play-at`, { index });
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
const botId = this.activeBotId;
if (!botId) return;
const res = await axios.post(`/api/player/${botId}/play-at`, { index });
if (res.data?.ok === false && res.data?.message) this.notify(res.data.message, 'error');
if (res.data?.ok === true) void this.syncElapsed(botId);
},
async play(query: string, platform = 'netease') {
@@ -533,7 +539,8 @@ export const usePlayerStore = defineStore('player', {
},
async playSong(song: Song, skipPartCheck = false) {
if (!this.activeBotId) return;
const botId = this.activeBotId;
if (!botId) return;
if (!skipPartCheck && song.platform === 'bilibili' && !song.id.includes('?p=')) {
const handled = await this.checkBilibiliMultiPart(song, 'play');
if (handled) return;
@@ -541,12 +548,11 @@ export const usePlayerStore = defineStore('player', {
// Guests use the non-destructive "play now" (insert-next + skip) so they
// can't wipe everyone else's queue; members/admins keep the normal behavior.
const endpoint = useSession().isGuest.value ? 'play-now-song' : 'play-song';
const res = await axios.post(`/api/player/${this.activeBotId}/${endpoint}`, { song });
const res = await axios.post(`/api/player/${botId}/${endpoint}`, { song });
if (res.data?.ok === false && res.data?.message) {
this.notify(res.data.message, 'error');
}
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
if (res.data?.ok === true) void this.syncElapsed(botId);
},
async playNextSong(song: Song, skipPartCheck = false) {
@@ -579,18 +585,19 @@ export const usePlayerStore = defineStore('player', {
const handled = await this.checkBilibiliMultiPart(song, 'add');
if (handled) return;
}
await axios.post(`/api/player/${this.activeBotId}/add-song`, { song });
const res = await axios.post(`/api/player/${this.activeBotId}/add-song`, { song });
if (res.data?.ok === false && res.data?.message) this.notify(res.data.message, 'error');
},
async playPlaylist(playlistId: string, platform = 'netease') {
if (!this.activeBotId) return;
const botId = this.activeBotId;
if (!botId) return;
try {
const res = await axios.post(`/api/player/${this.activeBotId}/play-playlist`, { playlistId, platform });
const res = await axios.post(`/api/player/${botId}/play-playlist`, { playlistId, platform });
if (res.data?.message) {
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
}
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
if (res.data?.ok === true) void this.syncElapsed(botId);
} catch (e: any) {
// A 403 here means a guest lacks the "play entire collection" permission
// (issue #103) — surface it instead of failing silently.
@@ -599,14 +606,14 @@ export const usePlayerStore = defineStore('player', {
},
async playAlbum(albumId: string, platform = 'netease') {
if (!this.activeBotId) return;
const botId = this.activeBotId;
if (!botId) return;
try {
const res = await axios.post(`/api/player/${this.activeBotId}/play-album`, { albumId, platform });
const res = await axios.post(`/api/player/${botId}/play-album`, { albumId, platform });
if (res.data?.message) {
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
}
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
if (res.data?.ok === true) void this.syncElapsed(botId);
} catch (e: any) {
this.notify(e?.response?.status === 403 ? '没有权限播放整个专辑' : '播放专辑失败', 'error');
}
@@ -618,18 +625,18 @@ export const usePlayerStore = defineStore('player', {
* trips, so the caller gets a "loading" notice first.
*/
async playArtist(artistId: string, platform = 'netease') {
if (!this.activeBotId) return;
const botId = this.activeBotId;
if (!botId) return;
this.notify('正在载入该歌手的全部歌曲…', 'info');
try {
const res = await axios.post(
`/api/player/${this.activeBotId}/play-artist`,
`/api/player/${botId}/play-artist`,
{ artistId, platform },
);
if (res.data?.message) {
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
}
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
if (res.data?.ok === true) void this.syncElapsed(botId);
} catch (e: any) {
const status = e?.response?.status;
this.notify(
@@ -665,10 +672,11 @@ export const usePlayerStore = defineStore('player', {
},
async next() {
if (!this.activeBotId) return;
await axios.post(`/api/player/${this.activeBotId}/next`);
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
const botId = this.activeBotId;
if (!botId) return;
const res = await axios.post(`/api/player/${botId}/next`);
if (res.data?.ok === false && res.data?.message) this.notify(res.data.message, 'error');
if (res.data?.ok === true) void this.syncElapsed(botId);
},
async prev() {
@@ -710,14 +718,16 @@ export const usePlayerStore = defineStore('player', {
},
async startFm(platform: Source = 'netease') {
if (!this.activeBotId) return;
const res = await axios.post(`/api/player/${this.activeBotId}/fm`, { platform });
if (res.data?.message) {
const botId = this.activeBotId;
if (!botId) return;
const res = await axios.post(`/api/player/${botId}/fm`, { platform });
if (this.activeBotId === botId && res.data?.message) {
this.notify(res.data.message, res.data.ok === false ? 'error' : 'info');
}
this._setTiming(this.activeBotId, { serverElapsed: 0 });
this._syncAfterAction();
this.fetchQueue();
if (res.data?.ok === true) {
void this.syncElapsed(botId);
void this.fetchQueueForBot(botId);
}
},
async fetchFavorites() {