mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-01 02:12:50 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20283aa6a7 | ||
|
|
dfa15fd5a5 | ||
|
|
19c9a32850 | ||
|
|
39b94ffdf2 | ||
|
|
a44324b748 | ||
|
|
11081ec4f8 | ||
|
|
0b3bb0c3dd |
No files matched your search
@@ -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) |
|
||||
@@ -997,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 音乐和酷狗的完整曲目提前断流时,机器人会在有限次数内刷新地址,从已播位置续播。停止、切歌和断开连接会取消旧曲目的恢复。
|
||||
- 网页加载空歌单、预检失败或选择无效队列位置时会保留原播放。进度条会跟随实际音频进度,切歌失败会显示原因。更新机器人头像时结束的短曲也能正常推进队列。
|
||||
|
||||
Generated
+2
-2
@@ -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",
|
||||
|
||||
+1
-1
@@ -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": {
|
||||
|
||||
+1
-1
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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([
|
||||
|
||||
+108
-38
@@ -1,5 +1,6 @@
|
||||
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 {
|
||||
@@ -229,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;
|
||||
@@ -236,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,
|
||||
@@ -256,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: {
|
||||
@@ -270,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);
|
||||
|
||||
@@ -356,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[]> {
|
||||
@@ -508,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;
|
||||
@@ -575,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;
|
||||
@@ -586,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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user