diff --git a/README.md b/README.md index f432132..f9f290b 100644 --- a/README.md +++ b/README.md @@ -999,7 +999,14 @@ 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.1 播放、续播与队列修复 +### 最新版本 — 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 音乐和酷狗的完整曲目提前断流时,机器人会在有限次数内刷新地址,从已播位置续播。停止、切歌和断开连接会取消旧曲目的恢复。 - 网页加载空歌单、预检失败或选择无效队列位置时会保留原播放。进度条会跟随实际音频进度,切歌失败会显示原因。更新机器人头像时结束的短曲也能正常推进队列。 diff --git a/package-lock.json b/package-lock.json index cd8514b..1959380 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "tsmusicbot", - "version": "1.16.1", + "version": "1.16.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "tsmusicbot", - "version": "1.16.1", + "version": "1.16.2", "license": "MIT", "dependencies": { "@discordjs/opus": "^0.10.0", diff --git a/package.json b/package.json index e7a7384..0f9015d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tsmusicbot", - "version": "1.16.1", + "version": "1.16.2", "description": "TeamSpeak music bot with NetEase Cloud Music and QQ Music support", "type": "module", "engines": { diff --git a/src/music/netease-playlist-budget.test.ts b/src/music/netease-playlist-budget.test.ts new file mode 100644 index 0000000..93eda08 --- /dev/null +++ b/src/music/netease-playlist-budget.test.ts @@ -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(); + 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); + }); +}); diff --git a/src/music/netease.ts b/src/music/netease.ts index 33bf6d1..b36d19e 100644 --- a/src/music/netease.ts +++ b/src/music/netease.ts @@ -268,22 +268,43 @@ export class NeteaseProvider implements MusicProvider { } private async mapPlaylistCards(rows: NeteasePlaylistSummary[], cookie: Record): Promise { - const cards: Playlist[] = []; - for (const row of rows) { + 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) { - // Cloud tracks can overlap the reported count or be hidden from this account. + 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 { - const detail = await this.getPlaylistDetail(id, cookie); - songCount = detail?.songCount ?? songCount; + // 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 if this playlist's detail is unavailable. + // Keep the list count on failure or cancellation at the shared deadline. } } - cards.push({ id, name: row.name, coverUrl: row.coverImgUrl ?? row.picUrl ?? "", songCount, platform: "netease" }); + }; + try { + await Promise.all(Array.from({ length: Math.min(4, lookups.length) }, enrich)); + } finally { + clearTimeout(timer); } return cards; } @@ -628,9 +649,10 @@ export class NeteaseProvider implements MusicProvider { return mapNeteaseSongs(res.data?.data?.dailySongs); } - async getPlaylistDetail(playlistId: string, cookie = this.cookieParams): Promise { + async getPlaylistDetail(playlistId: string, cookie = this.cookieParams, signal?: AbortSignal): Promise { const res = await this.api.get("/playlist/detail", { params: { id: playlistId, ...cookie }, + ...(signal && { signal }), }); const p = res.data?.playlist; if (!p) return null;