fix(playback): keep retry changes independent of proxy settings

This commit is contained in:
TIANYAO ZHANG committed 2026-11-18 16:52:58 +08:00
1 parent 97ee05f1ef
commit 406ecda7d7
4 files changed
+20 -172

No files matched your search

Regular → Executable
-23
View File
@@ -150,18 +150,6 @@ export interface BotConfig {
* a hand-edited config cannot turn every failed track into a long stall.
*/
playUrlRetries: number;
/**
* Outbound HTTP proxy for the NetEase sidecar, e.g. `http://192.168.1.2:8118`.
*
* NetEase rejects cloud-datacenter IPs with `-460` ("网络环境存在风险") no matter
* which account is used, so on a VPS the only fix is to send the request out
* through somewhere else. Empty (the default) = direct, i.e. unchanged.
*
* Only `http://` proxies are supported — the sidecar implements this with a
* CONNECT tunnel. When left empty, `HTTPS_PROXY`/`HTTP_PROXY` from the
* environment is used as a fallback (see index.ts).
*/
musicProxy: string;
// Public base URL used when generating share links (e.g. the bot专属链接).
// Leave empty to use the browser's current origin. Example:
// "https://music.example.com" or "http://1.2.3.4:3000"
@@ -220,7 +208,6 @@ export function getDefaultConfig(): BotConfig {
// Two extra attempts: enough to ride out a transient NetEase hiccup without
// making a genuinely unlicensed track feel stuck (~1s of backoff total).
playUrlRetries: 2,
musicProxy: "",
publicUrl: "",
trustProxy: false,
guestMode: {
@@ -434,15 +421,6 @@ export function loadConfig(path: string): BotConfig {
? Math.min(5, Math.max(0, Math.trunc(rawRetries)))
: defaults.playUrlRetries;
// Outbound proxy for the NetEase sidecar. Only http(s) URLs are kept: a
// stray value here would silently break every music request, so anything
// unparseable is dropped back to "direct" instead of being passed through.
const rawMusicProxy = partial.musicProxy;
const musicProxy =
typeof rawMusicProxy === "string" && /^https?:\/\/[^\s]+$/i.test(rawMusicProxy.trim())
? rawMusicProxy.trim()
: defaults.musicProxy;
// Voice ducking is opt-in and the retained-volume percentage is consumed
// directly by the audio path. Only a plain-object block with correctly
// typed, finite and in-range fields may override the safe defaults.
@@ -506,7 +484,6 @@ export function loadConfig(path: string): BotConfig {
savedQueuesEnabled,
playKeepsQueue,
playUrlRetries,
musicProxy,
voiceDucking,
defaultPlatform: defaultPlatformPref,
};
Regular → Executable
-21
View File
@@ -81,27 +81,6 @@ async function main() {
const cookieStore = createCookieStore(COOKIE_DIR);
const avatarStore = createAvatarStore(AVATAR_DIR);
// Outbound proxy for the NetEase sidecar. On a cloud host NetEase answers
// -460 ("网络环境存在风险") by IP, so the request has to leave through somewhere
// else. Config wins over the environment: a container-wide HTTPS_PROXY set
// for unrelated tools must not silently reroute music traffic.
const musicProxy =
config.musicProxy ||
process.env.HTTPS_PROXY ||
process.env.https_proxy ||
process.env.HTTP_PROXY ||
process.env.http_proxy ||
"";
if (musicProxy) {
neteaseProvider.setProxy(musicProxy);
// Credentials in a proxy URL are common; never put them in the log.
logger.info(
{ proxy: musicProxy.replace(/\/\/[^@/]+@/, "//***@") },
"NetEase requests will go through a proxy",
);
}
const neteaseCookie = cookieStore.load("netease");
if (neteaseCookie) neteaseProvider.setCookie(neteaseCookie);
const qqCookie = cookieStore.load("qq");
-70
View File
@@ -485,73 +485,3 @@ describe("NetEase — why a track has no URL", () => {
expect(err.failure.upstream).toMatchObject({ fee: 8, payed: 0, level: "higher", br: 192000 });
});
});
// ---------------------------------------------------------------------------
// Outbound proxy
//
// On a cloud host NetEase answers -460 by IP, so the request has to leave from
// somewhere else. The sidecar (NeteaseCloudMusicApi) supports this natively via
// a `proxy` request parameter — no new dependency, no global-agent patching.
// These tests pin that it is carried on EVERY call and that the default stays
// exactly as before.
// ---------------------------------------------------------------------------
describe("NetEase — outbound proxy", () => {
function capture() {
const seen: Array<Record<string, unknown>> = [];
const p = new NeteaseProvider("http://127.0.0.1:3001");
(p as unknown as { api: { get: (u: string, c: any) => Promise<unknown> } }).api = {
get: async (_url: string, cfg: any) => {
seen.push({ ...cfg?.params });
return { data: { result: {}, data: [{ url: null, code: 200, fee: 8, level: "exhigh" }] } };
},
};
return { p, seen };
}
it("sends no proxy parameter by default — behaviour is unchanged", async () => {
const { p, seen } = capture();
await p.search("x").catch(() => {});
expect(seen.length).toBeGreaterThan(0);
for (const params of seen) expect(params.proxy).toBeUndefined();
});
it("carries the proxy on every call once configured", async () => {
const { p, seen } = capture();
p.setProxy("http://192.168.1.9:8118");
await p.search("x").catch(() => {});
expect(seen.length).toBeGreaterThan(0);
for (const params of seen) expect(params.proxy).toBe("http://192.168.1.9:8118");
});
it("carries it on the playback call too — that is the one that gets -460", async () => {
const { p, seen } = capture();
p.setProxy("http://192.168.1.9:8118");
await p.getSongUrl("1", "standard").catch(() => {});
expect(seen).toHaveLength(1);
expect(seen[0]).toMatchObject({ id: "1", level: "standard", proxy: "http://192.168.1.9:8118" });
});
it("keeps the cookie alongside the proxy", async () => {
const { p, seen } = capture();
p.setCookie("MUSIC_U=abc");
p.setProxy("http://h:1");
await p.getSongUrl("1").catch(() => {});
// cookie is normalised on the way in, so compare loosely.
expect(String(seen[0].cookie)).toContain("MUSIC_U=abc");
expect(seen[0].proxy).toBe("http://h:1");
});
it("treats a blank value as direct service", async () => {
const { p, seen } = capture();
p.setProxy(" ");
await p.search("x").catch(() => {});
for (const params of seen) expect(params.proxy).toBeUndefined();
expect(p.getProxy()).toBe("");
});
it("trims the value it is given", () => {
const p = new NeteaseProvider("http://x");
p.setProxy(" http://h:1 ");
expect(p.getProxy()).toBe("http://h:1");
});
});
+20 -58
View File
@@ -209,8 +209,6 @@ export class NeteaseProvider implements MusicProvider {
private api: AxiosInstance;
private cookie = "";
private quality = "exhigh";
/** Outbound HTTP proxy for the sidecar's own requests. "" = direct. */
private proxy = "";
private readonly baseUrl: string;
constructor(baseUrl: string) {
@@ -233,49 +231,13 @@ export class NeteaseProvider implements MusicProvider {
return this.cookie ? { cookie: this.cookie } : {};
}
/**
* Outbound proxy for every sidecar call.
*
* NetEase limits by IP: a cloud-datacenter address answers `-460`
* ("检测到您的网络环境存在风险") on most requests no matter which account asks,
* while the same account from a residential IP works. There is no code-level
* fix — the request has to originate somewhere else.
*
* The sidecar already knows how: `NeteaseCloudMusicApi` reads a `proxy`
* request parameter and tunnels through it itself (`util/request.js`, via the
* `tunnel` package). So this needs no new dependency and no global-agent
* patching — just carry the value.
*
* Only `http://` proxies work (the sidecar implements this with CONNECT).
* Empty means direct, i.e. exactly the previous behaviour.
*/
setProxy(proxy: string): void {
this.proxy = (proxy ?? "").trim();
}
getProxy(): string {
return this.proxy;
}
private get proxyParams(): Record<string, string> {
return this.proxy ? { proxy: this.proxy } : {};
}
/**
* Everything every call needs. One getter so a field added here cannot be
* forgotten on any of the ~20 call sites.
*/
private get requestParams(): Record<string, string> {
return { ...this.cookieParams, ...this.proxyParams };
}
async search(query: string, limit = 20, offset = 0): Promise<SearchResult> {
// /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.requestParams },
params: { keywords: query, type: 1, limit, offset, ...this.cookieParams },
}),
this.api.get("/cloudsearch", {
params: {
@@ -283,14 +245,14 @@ export class NeteaseProvider implements MusicProvider {
type: 1000,
limit,
offset,
...this.requestParams,
...this.cookieParams,
},
}),
this.api.get("/cloudsearch", {
params: { keywords: query, type: 10, limit, offset, ...this.requestParams },
params: { keywords: query, type: 10, limit, offset, ...this.cookieParams },
}),
this.api.get("/cloudsearch", {
params: { keywords: query, type: 100, limit, offset, ...this.requestParams },
params: { keywords: query, type: 100, limit, offset, ...this.cookieParams },
}),
]);
@@ -318,7 +280,7 @@ export class NeteaseProvider implements MusicProvider {
let res;
try {
res = await this.api.get("/song/url/v1", {
params: { id: songId, level, ...this.requestParams },
params: { id: songId, level, ...this.cookieParams },
});
} catch (err) {
// -460 arrives as HTTP 400, and left as-is it looks like "this track is
@@ -359,21 +321,21 @@ export class NeteaseProvider implements MusicProvider {
async getSongDetail(songId: string): Promise<Song | null> {
const res = await this.api.get("/song/detail", {
params: { ids: songId, ...this.requestParams },
params: { ids: songId, ...this.cookieParams },
});
return mapNeteaseSongs(res.data?.songs)[0] ?? null;
}
async getPlaylistSongs(playlistId: string): Promise<Song[]> {
const res = await this.api.get("/playlist/track/all", {
params: { id: playlistId, ...this.requestParams },
params: { id: playlistId, ...this.cookieParams },
});
return mapNeteaseSongs(res.data?.songs);
}
async getRecommendPlaylists(): Promise<Playlist[]> {
const res = await this.api.get("/personalized", {
params: { limit: 10, ...this.requestParams },
params: { limit: 10, ...this.cookieParams },
});
return (res.data?.result ?? []).map((p: any) => ({
id: String(p.id),
@@ -386,7 +348,7 @@ export class NeteaseProvider implements MusicProvider {
async getAlbumSongs(albumId: string): Promise<Song[]> {
const res = await this.api.get("/album", {
params: { id: albumId, ...this.requestParams },
params: { id: albumId, ...this.cookieParams },
});
return mapNeteaseSongs(res.data?.songs);
}
@@ -396,7 +358,7 @@ export class NeteaseProvider implements MusicProvider {
// separately via /artist/songs (order=hot) so the artist page's three
// upstream calls stay independent of each other.
const res = await this.api.get("/artists", {
params: { id: artistId, ...this.requestParams },
params: { id: artistId, ...this.cookieParams },
});
const a = res.data?.artist;
if (!a) return null;
@@ -413,7 +375,7 @@ export class NeteaseProvider implements MusicProvider {
limit,
offset: 0,
order: "hot",
...this.requestParams,
...this.cookieParams,
},
});
return mapNeteaseSongs(res.data?.songs);
@@ -421,7 +383,7 @@ export class NeteaseProvider implements MusicProvider {
async getArtistAlbums(artistId: string, limit = 20): Promise<Album[]> {
const res = await this.api.get("/artist/album", {
params: { id: artistId, limit, offset: 0, ...this.requestParams },
params: { id: artistId, limit, offset: 0, ...this.cookieParams },
});
return mapNeteaseAlbums(res.data?.hotAlbums);
}
@@ -442,7 +404,7 @@ export class NeteaseProvider implements MusicProvider {
limit: safeLimit,
offset: safeOffset,
order: "hot",
...this.requestParams,
...this.cookieParams,
},
});
const songs = mapNeteaseSongs(res.data?.songs);
@@ -456,7 +418,7 @@ export class NeteaseProvider implements MusicProvider {
async getLyrics(songId: string): Promise<LyricLine[]> {
const res = await this.api.get("/lyric", {
params: { id: songId, ...this.requestParams },
params: { id: songId, ...this.cookieParams },
});
return parseLyrics(
res.data?.lrc?.lyric ?? "",
@@ -552,7 +514,7 @@ export class NeteaseProvider implements MusicProvider {
if (!this.cookie) return { loggedIn: false };
try {
const res = await this.api.get("/login/status", {
params: { ...this.requestParams },
params: { ...this.cookieParams },
});
const profile = res.data?.data?.profile;
if (profile) {
@@ -570,21 +532,21 @@ export class NeteaseProvider implements MusicProvider {
async getPersonalFm(): Promise<Song[]> {
const res = await this.api.get("/personal_fm", {
params: { ...this.requestParams },
params: { ...this.cookieParams },
});
return mapNeteaseSongs(res.data?.data);
}
async getDailyRecommendSongs(): Promise<Song[]> {
const res = await this.api.get("/recommend/songs", {
params: { ...this.requestParams },
params: { ...this.cookieParams },
});
return mapNeteaseSongs(res.data?.data?.dailySongs);
}
async getPlaylistDetail(playlistId: string): Promise<PlaylistDetail | null> {
const res = await this.api.get("/playlist/detail", {
params: { id: playlistId, ...this.requestParams },
params: { id: playlistId, ...this.cookieParams },
});
const p = res.data?.playlist;
if (!p) return null;
@@ -600,13 +562,13 @@ export class NeteaseProvider implements MusicProvider {
async getUserPlaylists(): Promise<Playlist[]> {
// First get user ID from login status
const statusRes = await this.api.get("/login/status", {
params: { ...this.requestParams },
params: { ...this.cookieParams },
});
const uid = statusRes.data?.data?.profile?.userId;
if (!uid) return [];
const res = await this.api.get("/user/playlist", {
params: { uid, ...this.requestParams },
params: { uid, ...this.cookieParams },
});
return (res.data?.playlist ?? []).map((p: any) => ({
id: String(p.id),