mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-02 19:02:50 +08:00
Integrate upstream and honor music-account revocations during FM
This commit is contained in:
commit
a47917afb1
17 files changed
+288
-50
No files matched your search
@@ -355,6 +355,12 @@ QQ 音源启用时,`QQ_MUSIC_MANAGED_SESSION` 默认为 `1`。在 **设置 →
|
||||
|
||||
设置 `QQ_MUSIC_MANAGED_SESSION=0` 并重启可关闭自动续期。机器人继续使用当前的 QQ 播放 Cookie,并从 `cookies/qq.json` 兼容读取旧部署的 Cookie。
|
||||
|
||||
### 每用户音乐账号
|
||||
|
||||
管理员可在设置中开启「每个成员使用自己的音乐账号」,默认关闭。成员可扫码绑定自己的网易云,也可接受管理员分配的网易云、QQ 音乐、酷狗或 B 站账号。网页搜索、歌单和推荐默认优先使用自己的绑定,其次使用分配账号,最后使用机器人共享账号。成员也可在「我的音乐账号」中主动选择共享账号。房间播歌使用机器人共享账号。
|
||||
|
||||
从共享账号导入时,账号池保存当前 Cookie 的副本。共享账号续期或更换后,管理员可在账号池中更新该条目的 Cookie。
|
||||
|
||||
### WebUI 页面说明
|
||||
|
||||
| 页面 | 功能 |
|
||||
|
||||
@@ -50,6 +50,7 @@ describe("buildFfmpegArgs", () => {
|
||||
"https://szbdyd.com/audio.m4s",
|
||||
"https://stream.mcdn.szbdyd.com/audio.m4s",
|
||||
"https://xy219x131x72x38xy.mcdn.bilivideo.cn.szbdyd.com/audio.m4s",
|
||||
"https://b-bacb4fc51cs41d5p0dxdau053w.edge.mountaintoys.cn/audio.m4s",
|
||||
"HTTPS://UPOS-SZ-MIRRORCOS.BILIVIDEO.COM:443/audio.m4s",
|
||||
"https://upos-sz-mirrorcos.bilivideo.com./audio.m4s",
|
||||
])("uses Bilibili headers and input-side seeking for the actual CDN host in %s", (url) => {
|
||||
@@ -70,6 +71,8 @@ describe("buildFfmpegArgs", () => {
|
||||
"https://bilibili.com.evil.example/audio.m4s",
|
||||
"https://evilbilibili.com/audio.m4s",
|
||||
"https://szbdyd.com.evil.example/audio.m4s",
|
||||
"https://mountaintoys.cn.evil.example/audio.m4s",
|
||||
"https://evilmountaintoys.cn/audio.m4s",
|
||||
"https://evil.example/audio.m4s?redirect=https://upos-sz-mirrorcos.bilivideo.com/x",
|
||||
"https://bilibili.com@evil.example/audio.m4s",
|
||||
])("does not trust Bilibili text outside an allowed hostname in %s", (url) => {
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ export function buildFfmpegArgs(url: string, seekSeconds: number): string[] {
|
||||
}
|
||||
const isHttp = httpHostname !== null;
|
||||
const isBilibili = httpHostname !== null &&
|
||||
["bilivideo.com", "bilivideo.cn", "bilibili.com", "szbdyd.com"].some(
|
||||
["bilivideo.com", "bilivideo.cn", "bilibili.com", "szbdyd.com", "mountaintoys.cn"].some(
|
||||
domain => httpHostname === domain || httpHostname.endsWith(`.${domain}`),
|
||||
);
|
||||
|
||||
|
||||
@@ -29,6 +29,10 @@ function makeBot() {
|
||||
player.getVolume = () => 50;
|
||||
player.pause = AudioPlayer.prototype.pause;
|
||||
player.resume = AudioPlayer.prototype.resume;
|
||||
// The real pause()/resume() drive the de-click transport ramp
|
||||
// (a0f0b49..6f165b5). A stub player must expose it too, or the prototype
|
||||
// methods throw "setTransportRamp is not a function".
|
||||
player.setTransportRamp = vi.fn();
|
||||
player.play = vi.fn((_url: string, position: number) => { player.sessionId++; player.elapsed = position; player.state = "playing"; });
|
||||
player.stop = vi.fn(() => { player.sessionId++; player.state = "idle"; });
|
||||
const provider = { getSongUrl: vi.fn(async (): Promise<{ url: string } | null> => ({ url: "fresh" })) };
|
||||
|
||||
@@ -396,6 +396,20 @@ const resolveAndPlay = BotInstance.prototype.resolveAndPlay as (
|
||||
this: unknown,
|
||||
song: any,
|
||||
) => Promise<boolean>;
|
||||
|
||||
it("re-resolves an active web FM account before fetching more songs", async () => {
|
||||
const old = { platform: "netease", getCookie: () => "old", getPersonalFm: vi.fn(async () => []) };
|
||||
const shared = { platform: "netease", getCookie: () => "shared", getPersonalFm: vi.fn(async () => []) };
|
||||
const context = {
|
||||
isFmMode: true,
|
||||
fmProvider: old,
|
||||
resolveFmProvider: () => shared,
|
||||
logger: { error: vi.fn() },
|
||||
};
|
||||
await (BotInstance.prototype as unknown as { refillFm(): Promise<void> }).refillFm.call(context);
|
||||
expect(old.getPersonalFm).not.toHaveBeenCalled();
|
||||
expect(shared.getPersonalFm).toHaveBeenCalledOnce();
|
||||
});
|
||||
const setupPlayerEvents = (BotInstance.prototype as any).setupPlayerEvents as (
|
||||
this: unknown,
|
||||
) => void;
|
||||
@@ -1544,6 +1558,36 @@ describe("BotInstance live-queue persistence (#119)", () => {
|
||||
});
|
||||
|
||||
describe("BotInstance Bilibili multi-P resolution", () => {
|
||||
it("passes the page from a TeamSpeak video link to the Bilibili provider", async () => {
|
||||
const song = {
|
||||
id: "BV1yxHQeYEuE?p=2",
|
||||
name: "Video - P2",
|
||||
artist: "Uploader",
|
||||
album: "",
|
||||
duration: 180,
|
||||
coverUrl: "",
|
||||
platform: "bilibili" as const,
|
||||
};
|
||||
const provider = { platform: "bilibili", getSongDetail: vi.fn().mockResolvedValue(song) };
|
||||
const ctx = {
|
||||
config: { commandPrefix: "!" },
|
||||
assertProviderEnabled: vi.fn(),
|
||||
getProviderFor: vi.fn().mockReturnValue(provider),
|
||||
};
|
||||
const args = "[URL]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2[/URL]";
|
||||
|
||||
const result = await (BotInstance.prototype as any).resolvePlayQuery.call(ctx, {
|
||||
name: "play",
|
||||
args,
|
||||
rawArgs: [args],
|
||||
flags: new Set(),
|
||||
});
|
||||
|
||||
expect(ctx.getProviderFor).toHaveBeenCalledWith("bilibili");
|
||||
expect(provider.getSongDetail).toHaveBeenCalledWith("BV1yxHQeYEuE?p=2");
|
||||
expect(result.song).toEqual(song);
|
||||
});
|
||||
|
||||
it("resolves multi-P search result to P1 with accurate duration and name", async () => {
|
||||
const multiPSongDetail = {
|
||||
id: "BV1multiP?p=1",
|
||||
@@ -1780,6 +1824,10 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
player.getPlaybackSessionId = AudioPlayer.prototype.getPlaybackSessionId;
|
||||
player.pause = AudioPlayer.prototype.pause;
|
||||
player.resume = AudioPlayer.prototype.resume;
|
||||
// The real pause()/resume() drive the de-click transport ramp
|
||||
// (a0f0b49..6f165b5). A stub player must expose it too, or the prototype
|
||||
// methods throw "setTransportRamp is not a function".
|
||||
player.setTransportRamp = vi.fn();
|
||||
player.play = vi.fn(() => { player.sessionId++; player.state = "playing"; });
|
||||
const provider = { getSongUrl: vi.fn(async () => ({ url: "fresh" })) };
|
||||
const advances: string[] = [];
|
||||
|
||||
+20
-5
@@ -9,6 +9,7 @@ import {
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
|
||||
import type { MusicProvider, Platform, Song } from "../music/provider.js";
|
||||
import { musicRequestError } from "../music/request-error.js";
|
||||
import {
|
||||
parseCommand,
|
||||
canRunCommand,
|
||||
@@ -198,6 +199,7 @@ export class BotInstance extends EventEmitter {
|
||||
private profileManager: BotProfileManager;
|
||||
private isFmMode = false;
|
||||
private fmProvider: MusicProvider | null = null;
|
||||
private resolveFmProvider?: () => MusicProvider;
|
||||
private fmRequesterName: string | undefined;
|
||||
/** Results of the most recent !search, for "#N" selection (issue #90). */
|
||||
private lastSearchResults: Song[] = [];
|
||||
@@ -980,6 +982,7 @@ export class BotInstance extends EventEmitter {
|
||||
private disableFmMode(): void {
|
||||
this.isFmMode = false;
|
||||
this.fmProvider = null;
|
||||
this.resolveFmProvider = undefined;
|
||||
this.fmRequesterName = undefined;
|
||||
}
|
||||
|
||||
@@ -1807,7 +1810,11 @@ export class BotInstance extends EventEmitter {
|
||||
return this.startFm(this.getProvider(cmd.flags), requesterName);
|
||||
}
|
||||
|
||||
async startFm(provider: MusicProvider = this.neteaseProvider, requesterName?: string): Promise<string> {
|
||||
async startFm(
|
||||
provider: MusicProvider = this.neteaseProvider,
|
||||
requesterName?: string,
|
||||
resolveProvider?: () => MusicProvider,
|
||||
): Promise<string> {
|
||||
// Match the !fm chat-command guard: refuse before mutating the queue when
|
||||
// offline, so the web /fm route can't wipe the queue + flip into FM mode
|
||||
// while nothing can actually play.
|
||||
@@ -1829,6 +1836,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.queue.setMode(PlayMode.Random);
|
||||
this.isFmMode = true;
|
||||
this.fmProvider = provider;
|
||||
this.resolveFmProvider = resolveProvider;
|
||||
this.fmRequesterName = requesterName?.trim() || undefined;
|
||||
this.player.resetFailures();
|
||||
|
||||
@@ -1874,17 +1882,23 @@ export class BotInstance extends EventEmitter {
|
||||
}
|
||||
|
||||
private async refillFm(): Promise<void> {
|
||||
const provider = this.fmProvider;
|
||||
if (!this.isFmMode || !provider?.getPersonalFm) return;
|
||||
if (!this.isFmMode || !this.fmProvider) return;
|
||||
const resolveProvider = this.resolveFmProvider;
|
||||
try {
|
||||
const current = this.fmProvider;
|
||||
const resolved = resolveProvider?.() ?? current;
|
||||
// Keep a provider's FM cursor while its login remains unchanged.
|
||||
const provider = resolved !== current && resolved.getCookie() !== current.getCookie() ? resolved : current;
|
||||
this.fmProvider = provider;
|
||||
if (!provider.getPersonalFm) return;
|
||||
const songs = await provider.getPersonalFm();
|
||||
if (songs.length === 0) return;
|
||||
if (!this.isFmMode || this.fmProvider !== provider || this.resolveFmProvider !== resolveProvider || songs.length === 0) return;
|
||||
for (const song of songs) {
|
||||
this.queue.add(this.withRequester({ ...song, platform: provider.platform }, this.fmRequesterName));
|
||||
}
|
||||
this.logger.debug({ count: songs.length, platform: provider.platform }, "FM queue refilled");
|
||||
} catch (err) {
|
||||
this.logger.error({ err }, "Failed to refill FM queue");
|
||||
this.logger.error({ err: musicRequestError(err) }, "Failed to refill FM queue");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2037,6 +2051,7 @@ export class BotInstance extends EventEmitter {
|
||||
if (st.isFmMode && st.fmPlatform) {
|
||||
this.isFmMode = true;
|
||||
this.fmProvider = this.getProviderFor(st.fmPlatform as Platform);
|
||||
this.resolveFmProvider = undefined;
|
||||
}
|
||||
const current = this.queue.current();
|
||||
if (current) {
|
||||
|
||||
@@ -101,6 +101,34 @@ describe("parseSongRef (#90 exact-song selection)", () => {
|
||||
expect(parseSongRef("https://www.bilibili.com/video/BV1yxHQeYEuE")).toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" });
|
||||
expect(parseSongRef("https://b23.tv/BV1yxHQeYEuE")).toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE?p=2",
|
||||
"https://b23.tv/BV1yxHQeYEuE?p=2",
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE/?from=share&p=2&vd_source=test#reply",
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE/?from=share?p=3&p=2",
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE/?p=%32",
|
||||
"[URL]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2[/URL]",
|
||||
"[url]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2#reply[/url]",
|
||||
"[URL=https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2]点击播放[/URL]",
|
||||
"参考 https://example.com/?p=9 视频 https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2 请播放",
|
||||
])("preserves the Bilibili page query in %s", (input) => {
|
||||
expect(parseSongRef(input)).toEqual({ id: "BV1yxHQeYEuE?p=2", platform: "bilibili" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
"?p=2extra",
|
||||
"?p=-2",
|
||||
"?page=2",
|
||||
"?sp=2",
|
||||
"?from=share?p=2",
|
||||
"?from=share%3Fp%3D2",
|
||||
"?from=share#reply&p=2",
|
||||
"#reply?p=2",
|
||||
])("ignores an invalid or unrelated Bilibili page query %s", (query) => {
|
||||
expect(parseSongRef(`https://www.bilibili.com/video/BV1yxHQeYEuE${query}`))
|
||||
.toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseSelectionIndex (#90 pick from last search)", () => {
|
||||
|
||||
+5
-1
@@ -69,7 +69,11 @@ export function parseSongRef(raw: string): SongRef | null {
|
||||
// a "BV..." token never collides with them).
|
||||
const bv = /BV[0-9A-Za-z]{8,12}/.exec(q);
|
||||
if (bv && (/^BV[0-9A-Za-z]{8,12}$/.test(q) || /bilibili\.com|b23\.tv/i.test(q))) {
|
||||
return { id: bv[0], platform: "bilibili" };
|
||||
// Extract the query attached to this BV id, including in [URL=...] tags.
|
||||
const suffix = q.slice(bv.index + bv[0].length);
|
||||
const query = /^\/?\?([^#\s[\]]*)/.exec(suffix)?.[1];
|
||||
const page = new URLSearchParams(query).get("p");
|
||||
return { id: page && /^\d+$/.test(page) ? `${bv[0]}?p=${page}` : bv[0], platform: "bilibili" };
|
||||
}
|
||||
|
||||
// NetEase song URL. Only treat `id=N` as a SONG id when the URL is not a
|
||||
|
||||
@@ -65,9 +65,17 @@ describe("BotInstance persistent voice send failure", () => {
|
||||
expect(frames).toBe(50);
|
||||
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 });
|
||||
vi.advanceTimersByTime(3000);
|
||||
expect(frames).toBe(50);
|
||||
expect(h.player.getElapsed()).toBe(1);
|
||||
// Pausing emits a short de-click fade tail (pauseFrames) so the last
|
||||
// audible frames ramp down instead of cutting off (a0f0b49). What this
|
||||
// test guards is what happens AFTER that: the scheduler must go quiet
|
||||
// and elapsed must stop advancing.
|
||||
expect(h.player.getState()).toBe("paused");
|
||||
const framesAfterFade = frames;
|
||||
const elapsedAfterFade = h.player.getElapsed();
|
||||
expect(framesAfterFade).toBeLessThan(50 + 20);
|
||||
vi.advanceTimersByTime(3000);
|
||||
expect(frames).toBe(framesAfterFade);
|
||||
expect(h.player.getElapsed()).toBe(elapsedAfterFade);
|
||||
} finally { h.player.stop(); }
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { once } from "node:events";
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import {
|
||||
parseLyrics,
|
||||
@@ -8,6 +11,63 @@ import {
|
||||
NeteaseProvider,
|
||||
} from "./netease.js";
|
||||
|
||||
describe("NeteaseProvider playback user agent", () => {
|
||||
it("matches the playback UA to each account's platform without changing cookies or other requests", async () => {
|
||||
const requests: URL[] = [];
|
||||
const server = createServer((req, res) => {
|
||||
requests.push(new URL(req.url!, "http://localhost"));
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ code: 200, data: [{ url: "https://example.com/song.mp3" }] }));
|
||||
});
|
||||
server.listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
try {
|
||||
const provider = new NeteaseProvider(
|
||||
`http://127.0.0.1:${(server.address() as AddressInfo).port}`,
|
||||
);
|
||||
const cases = [
|
||||
["", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared; os=pc", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared; os=android", "Android"],
|
||||
["MUSIC_U=shared; os=android; os=iphone", "iPhone"],
|
||||
["MUSIC_U=shared; os=iphone", "iPhone"],
|
||||
["MUSIC_U=shared; os=linux", "Linux"],
|
||||
["MUSIC_U=shared; os=unknown", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared; os=%69phone", "iPhone"],
|
||||
["MUSIC_U=shared; os=%invalid", "NeteaseMusicDesktop"],
|
||||
];
|
||||
for (const [cookie, uaFamily] of cases) {
|
||||
provider.setCookie(cookie);
|
||||
expect(await provider.getSongUrl("1", "standard")).toMatchObject({ url: "https://example.com/song.mp3" });
|
||||
const params = requests.at(-1)!.searchParams;
|
||||
expect(params.get("ua")).toContain(uaFamily);
|
||||
expect(params.get("level")).toBe("standard");
|
||||
expect(params.get("cookie")).toBe(cookie || null);
|
||||
expect(provider.getCookie()).toBe(cookie);
|
||||
}
|
||||
|
||||
provider.setCookie("MUSIC_U=shared; os=pc");
|
||||
const personal = provider.withCookie("MUSIC_U=personal; os=android");
|
||||
await personal.getSongUrl("2");
|
||||
expect(requests.at(-1)!.searchParams.get("ua")).toContain("Android");
|
||||
expect(requests.at(-1)!.searchParams.get("cookie")).toBe("MUSIC_U=personal; os=android");
|
||||
await provider.getSongUrl("3");
|
||||
expect(requests.at(-1)!.searchParams.get("ua")).toContain("NeteaseMusicDesktop");
|
||||
expect(provider.getCookie()).toBe("MUSIC_U=shared; os=pc");
|
||||
|
||||
requests.length = 0;
|
||||
await provider.search("hello");
|
||||
await provider.getQrCode();
|
||||
expect(requests).toHaveLength(6);
|
||||
expect(requests.every((url) => !url.searchParams.has("ua"))).toBe(true);
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve, reject) => server.close((err) => err ? reject(err) : resolve()));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("NetEase adapter", () => {
|
||||
it("parses LRC format lyrics", () => {
|
||||
const lrc = `[00:00.00] 作词 : 周杰伦
|
||||
|
||||
+24
-1
@@ -125,6 +125,29 @@ export const NETEASE_QUALITY_LEVELS = [
|
||||
{ value: "jymaster", label: "超清母带", bitrate: 4000 },
|
||||
] as const;
|
||||
|
||||
function getPlaybackUserAgent(cookie: string): string {
|
||||
let decoded = cookie;
|
||||
try {
|
||||
decoded = decodeURIComponent(cookie);
|
||||
} catch {
|
||||
// A malformed cookie escape must not prevent a playback request.
|
||||
}
|
||||
// The sidecar's cookie parser keeps the last value of a repeated key.
|
||||
const platform = [...decoded.matchAll(/(?:^|;)\s*os\s*=\s*([^;=]*)(?=;|$)/g)].at(-1)?.[1].trim();
|
||||
// NCM API 4.32.0 defaults cookie profiles to PC but eapi's UA to iPhone.
|
||||
// Match its client profiles here, and scope the override to playback only.
|
||||
switch (platform) {
|
||||
case "android":
|
||||
return "NeteaseMusic/9.1.65.240927161425(9001065);Dalvik/2.1.0 (Linux; U; Android 14; 23013RK75C Build/UKQ1.230804.001)";
|
||||
case "iphone":
|
||||
return "NeteaseMusic 9.0.90/5038 (iPhone; iOS 16.2; zh_CN)";
|
||||
case "linux":
|
||||
return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36";
|
||||
default:
|
||||
return "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/91.0.4472.164 NeteaseMusicDesktop/3.0.18.203152";
|
||||
}
|
||||
}
|
||||
|
||||
export class NeteaseProvider implements MusicProvider {
|
||||
readonly platform = "netease" as const;
|
||||
private api: AxiosInstance;
|
||||
@@ -199,7 +222,7 @@ export class NeteaseProvider implements MusicProvider {
|
||||
async getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null> {
|
||||
const level = quality ?? this.quality;
|
||||
const res = await this.api.get("/song/url/v1", {
|
||||
params: { id: songId, level, ...this.cookieParams },
|
||||
params: { id: songId, level, ua: getPlaybackUserAgent(this.cookie), ...this.cookieParams },
|
||||
});
|
||||
const item = res.data?.data?.[0];
|
||||
const url = item?.url;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { isAxiosError } from "axios";
|
||||
|
||||
/** Axios errors can include music-account cookies in the message or config. */
|
||||
export function musicRequestError(error: unknown): Error {
|
||||
if (isAxiosError(error)) {
|
||||
const status = error.response?.status;
|
||||
return new Error(typeof status === "number" ? `Music service request failed (HTTP ${status})` : "Music service request failed");
|
||||
}
|
||||
return error instanceof Error ? error : new Error("Music service request failed");
|
||||
}
|
||||
+4
-2
@@ -3,6 +3,7 @@ import type { ParamsDictionary } from "express-serve-static-core";
|
||||
import type { MusicProvider } from "../../music/provider.js";
|
||||
import type { QQMusicProvider } from "../../music/qq.js";
|
||||
import { normalizeCookie } from "../../music/cookie-normalize.js";
|
||||
import { musicRequestError } from "../../music/request-error.js";
|
||||
import { YouTubeProvider } from "../../music/youtube.js";
|
||||
import type { CookieStore } from "../../music/auth.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
@@ -92,8 +93,9 @@ export function createAuthRouter(
|
||||
const renewal = platform === "qq" ? qqSession?.getStatus() : undefined;
|
||||
res.json({ platform: provider.platform, source: "shared", ...status, ...renewal });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Auth status check failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Auth status check failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import express from "express";
|
||||
import cookieParser from "cookie-parser";
|
||||
import request from "supertest";
|
||||
import pino from "pino";
|
||||
import { AxiosError } from "axios";
|
||||
import { mkdtempSync, rmSync, readFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
@@ -58,6 +59,18 @@ describe("music router GET /search offset pagination", () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(netease.search).toHaveBeenCalledWith("hello", 20, 0);
|
||||
});
|
||||
|
||||
it("keeps provider request credentials out of search errors", async () => {
|
||||
const logger = pino({ level: "silent" });
|
||||
const logError = vi.spyOn(logger, "error");
|
||||
const privateCookie = "MUSIC_U=test-private-session";
|
||||
vi.mocked(netease.search).mockRejectedValueOnce(new AxiosError(`Provider request failed: ${privateCookie}`));
|
||||
const route = express();
|
||||
route.use("/api/music", createMusicRouter(netease, fakeProvider("qq"), fakeProvider("bilibili"), logger));
|
||||
const res = await request(route).get("/api/music/search?q=test").expect(500);
|
||||
expect(res.text).not.toContain(privateCookie);
|
||||
expect(JSON.stringify(logError.mock.calls)).not.toContain(privateCookie);
|
||||
});
|
||||
});
|
||||
|
||||
describe("music router provider gating (enabledProviders) + jellyfin endpoints", () => {
|
||||
|
||||
+25
-18
@@ -1,5 +1,6 @@
|
||||
import express, { Router, type Request, type Response } from "express";
|
||||
import type { MusicProvider, Song, Album, SearchResult } from "../../music/provider.js";
|
||||
import { musicRequestError } from "../../music/request-error.js";
|
||||
import { YouTubeProvider } from "../../music/youtube.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import { isProviderEnabled, defaultPlatform, saveConfig, type BotConfig } from "../../data/config.js";
|
||||
@@ -193,8 +194,9 @@ export function createMusicRouter(
|
||||
);
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Search failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Search failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -263,8 +265,9 @@ export function createMusicRouter(
|
||||
|
||||
res.json({ songs, albums, playlists, artists });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Unified search failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Unified search failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -283,7 +286,7 @@ export function createMusicRouter(
|
||||
}
|
||||
res.json(song);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -294,7 +297,7 @@ export function createMusicRouter(
|
||||
const songs = await provider.getPlaylistSongs(req.params.id);
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -305,7 +308,7 @@ export function createMusicRouter(
|
||||
const playlists = await provider.getRecommendPlaylists();
|
||||
res.json({ playlists });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -316,7 +319,7 @@ export function createMusicRouter(
|
||||
const songs = await provider.getAlbumSongs(req.params.id);
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -327,7 +330,7 @@ export function createMusicRouter(
|
||||
const lyrics = await provider.getLyrics(req.params.id);
|
||||
res.json({ lyrics });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -357,7 +360,7 @@ export function createMusicRouter(
|
||||
}
|
||||
res.json({ artist, songs, albums });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -372,8 +375,9 @@ export function createMusicRouter(
|
||||
const songs = await provider.getDailyRecommendSongs();
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get daily recommend songs failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get daily recommend songs failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -388,8 +392,9 @@ export function createMusicRouter(
|
||||
const songs = await provider.getPersonalFm();
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get personal FM failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get personal FM failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -404,8 +409,9 @@ export function createMusicRouter(
|
||||
const playlists = await provider.getUserPlaylists();
|
||||
res.json({ playlists });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get user playlists failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get user playlists failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -424,8 +430,9 @@ export function createMusicRouter(
|
||||
}
|
||||
res.json({ playlist: detail });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get playlist detail failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get playlist detail failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+16
-11
@@ -2,6 +2,7 @@ import { Router, type Request } from "express";
|
||||
import type { BotManager } from "../../bot/manager.js";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
import type { MusicProvider, Song, ArtistSongPage } from "../../music/provider.js";
|
||||
import { musicRequestError } from "../../music/request-error.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import { parseCommand } from "../../bot/commands.js";
|
||||
import { requireBotAccess } from "../middleware/requirePermission.js";
|
||||
@@ -67,7 +68,7 @@ export function createPlayerRouter(
|
||||
* driven it. `alwaysPersonal` keeps that guarantee while the toggle is off;
|
||||
* with the toggle on, FM simply inherits the same account as everything else.
|
||||
*/
|
||||
const fmProvider = (req: Request, bot: any, platform: unknown): MusicProvider => {
|
||||
const fmProvider = (req: Pick<Request, "user">, bot: any, platform: unknown): MusicProvider => {
|
||||
const shared = sharedProviderFor(bot, platform);
|
||||
return resolveProviderForRequest(req, shared.platform, shared, { database, config }, {
|
||||
alwaysPersonal: true,
|
||||
@@ -183,8 +184,9 @@ export function createPlayerRouter(
|
||||
}
|
||||
// Resolve FM recommendations with the caller's account. The bot resolves
|
||||
// each queued track's playback URL using the shared account.
|
||||
const provider = fmProvider(req, bot, platform);
|
||||
const message = await bot.startFm(provider, requesterName(req));
|
||||
const scope = { user: req.user };
|
||||
const resolveFmProvider = () => fmProvider(scope, bot, platform);
|
||||
const message = await bot.startFm(resolveFmProvider(), requesterName(req), resolveFmProvider);
|
||||
res.json({
|
||||
ok:
|
||||
!message.startsWith("No FM songs") &&
|
||||
@@ -193,7 +195,7 @@ export function createPlayerRouter(
|
||||
message,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -430,8 +432,9 @@ export function createPlayerRouter(
|
||||
res.json({ ok: false, message: `${loadedMsg},但无法开始播放。` });
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Play playlist failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Play playlist failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -504,8 +507,9 @@ export function createPlayerRouter(
|
||||
res.json({ ok: false, message: `${loadedMsg},但无法开始播放。` });
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err }, "play-album failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "play-album failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -593,8 +597,9 @@ export function createPlayerRouter(
|
||||
});
|
||||
res.json(body);
|
||||
} catch (err) {
|
||||
logger.error({ err }, "play-artist failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "play-artist failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -776,7 +781,7 @@ export function createPlayerRouter(
|
||||
|
||||
res.json({ message: `Added: ${song.name} - ${song.artist} (position ${queue.size()})` });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -43,6 +43,8 @@ interface ScopedUser {
|
||||
role?: string;
|
||||
}
|
||||
|
||||
type ScopeRequest = Pick<Request, "user">;
|
||||
|
||||
/** Whether per-user music accounts are switched on for this router instance. */
|
||||
export function perUserMusicEnabled(deps: MusicScopeDeps): boolean {
|
||||
return deps.config?.perUserMusicAccounts === true;
|
||||
@@ -53,7 +55,7 @@ export function perUserMusicEnabled(deps: MusicScopeDeps): boolean {
|
||||
* qualify: they all map to one anonymous identity, so a linked or assigned
|
||||
* account would leak across every guest on the instance.
|
||||
*/
|
||||
function scopedUser(req: Request | undefined, deps: MusicScopeDeps): ScopedUser | null {
|
||||
function scopedUser(req: ScopeRequest | undefined): ScopedUser | null {
|
||||
if (!req) return null;
|
||||
const user = (req as { user?: ScopedUser }).user;
|
||||
if (!user?.id || user.role === "guest") return null;
|
||||
@@ -70,13 +72,13 @@ function scopedUser(req: Request | undefined, deps: MusicScopeDeps): ScopedUser
|
||||
* on only widens the scope to search/playlists/playback URLs.
|
||||
*/
|
||||
export function personalCookieFor(
|
||||
req: Request | undefined,
|
||||
req: ScopeRequest | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
alwaysPersonal = false,
|
||||
): string | null {
|
||||
if (!alwaysPersonal && !perUserMusicEnabled(deps)) return null;
|
||||
const user = scopedUser(req, deps);
|
||||
const user = scopedUser(req);
|
||||
if (!user || !deps.database) return null;
|
||||
const cookie = deps.database.getUserMusicCookie(user.id!, platform);
|
||||
return cookie && cookie.trim() ? cookie : null;
|
||||
@@ -92,12 +94,12 @@ export function personalCookieFor(
|
||||
* the feature.
|
||||
*/
|
||||
export function grantedAccountFor(
|
||||
req: Request | undefined,
|
||||
req: ScopeRequest | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
): GrantedMusicAccount | null {
|
||||
if (!perUserMusicEnabled(deps)) return null;
|
||||
const user = scopedUser(req, deps);
|
||||
const user = scopedUser(req);
|
||||
if (!user || !deps.database) return null;
|
||||
return deps.database.getGrantedMusicAccount(user.id!, platform);
|
||||
}
|
||||
@@ -111,12 +113,12 @@ export function grantedAccountFor(
|
||||
* assignment — it is an explicit instruction, not a fallback.
|
||||
*/
|
||||
export function preferSharedFor(
|
||||
req: Request | undefined,
|
||||
req: ScopeRequest | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
): boolean {
|
||||
if (!perUserMusicEnabled(deps)) return false;
|
||||
const user = scopedUser(req, deps);
|
||||
const user = scopedUser(req);
|
||||
if (!user || !deps.database) return false;
|
||||
return deps.database.getUserMusicPreference(user.id!, platform)?.preferShared === true;
|
||||
}
|
||||
@@ -136,7 +138,7 @@ export interface ResolvedMusicCookie {
|
||||
* Returns null when the shared login applies.
|
||||
*/
|
||||
export function resolveMusicCookie(
|
||||
req: Request | undefined,
|
||||
req: ScopeRequest | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
options: { alwaysPersonal?: boolean } = {},
|
||||
@@ -201,7 +203,7 @@ function withSharedPlaybackFallback(view: MusicProvider, shared: MusicProvider):
|
||||
* not break search/playback for that user.
|
||||
*/
|
||||
export function resolveProviderForRequest(
|
||||
req: Request | undefined,
|
||||
req: ScopeRequest | undefined,
|
||||
platform: string,
|
||||
shared: MusicProvider,
|
||||
deps: MusicScopeDeps,
|
||||
|
||||
Reference in new issue
Block a user