* Add configurable NetEase real IP in web settings
* Match NetEase playback User-Agent to cookie platform
* fix(netease): keep playback UA aligned with cookie profile
---------
Co-authored-by: TIANYAO ZHANG <88520881+ZHANGTIANYAO1@users.noreply.github.com>
The risk-control branch grew its delay per attempt (2.5s, then 7.5s) on the
assumption that a blocked IP unlocks on a timer. Measured behaviour says
otherwise: six back-to-back 128k requests from a blocked host answered
-460, -460, -460, -460, 200 — it lets a few through after a while, it does not
unlock at a fixed moment. So the third attempt mostly bought silence: five
requests and ~4s worst case for the same "still blocked".
Cap the whole risk-controlled budget at two requests (one retry after 2.5s)
and skip the quality ladder in that state, which -460 ignores anyway. Worst
case drops to 2.5s, and when it still fails the message now names the wait
(「约 5 秒后再试」) instead of 「请稍后重试」 — a spinner cannot be acted on, a
number can.
`import-shared` read the cookie from qq.json, which is only the on-disk
copy. After #188 renews credentials through the managed session that file
goes stale, so this route would seed the pool with a dead cookie.
Prefer the running QQ provider's in-memory cookie and fall back to the
cookie store when no QQ provider is mounted (tests that only register
netease keep the old behaviour). Two regressions: the rotated cookie wins
over the file copy, and a provider without a login 409s instead of
creating a dead row.
resolveAndPlay recorded lastPlayFailure only when the retry budget was
exhausted. Every early return (bot offline, local audio disabled) and the
outer catch left it null, so the web route fell back to the catch-all
「区域/版权限制」 for causes that have nothing to do with copyright.
Also move the bilibili detail lookup inside its own try: it is metadata
only, and an upstream 4xx there aborted the resolve before the retry
budget could even start.
-460 is NetEase refusing the caller's IP, not a property of the track, so
asking for a lower quality cannot succeed — it only adds another
RISK_CONTROL_BACKOFF_MS of silence before the same error surfaces. With the
default budget (2 retries + 2 NetEase fallback levels) a blocked host spent
~17s before the user saw anything, which is worse than the instant failure
this replaced. Bail out as soon as the phase changes instead.
The -460 documented in the previous commit has no code-level fix: NetEase
decides by IP, so a cloud-datacenter host gets refused regardless of account,
quality or retry budget. The only real remedy is to let the request leave from
somewhere else.
The sidecar already supports that, and nobody had noticed: `NeteaseCloudMusicApi`
reads a `proxy` REQUEST PARAMETER and tunnels through it itself
(`util/request.js`, via the `tunnel` package — `httpOverHttp`/`httpsOverHttp`).
So this needs **no new dependency, no global-agent patching, and no change to
how the sidecar is started**. It is one string carried on the calls we already
make.
What was added:
- `NeteaseProvider.setProxy()` / `getProxy()`. The value goes into
`requestParams`, a single getter that already existed for the cookie — which
is why all ~20 call sites (search, playlist, album, artist, lyric, playback)
pick it up without touching each one again.
- `config.musicProxy` (default `""` = direct, i.e. exactly the old behaviour).
Only `http(s)://host[:port]` is accepted; anything else falls back to direct
rather than silently breaking every music request.
- `index.ts` reads it, falls back to `HTTPS_PROXY`/`HTTP_PROXY` from the
environment, and logs `NetEase requests will go through a proxy` with the
credentials redacted.
Deliberate limits:
- Only HTTP proxies. The sidecar implements this with a CONNECT tunnel, so a
`socks5://` value would be parsed and then fail. Documented on the setter.
- Audio is NOT proxied. The player pulls the mp3 from NetEase's CDN with ffmpeg,
which knows nothing about this setting. If a deployment needs those requests
to share the API's egress IP, it needs a network-level route, not this option.
- Config wins over the environment: a container-wide `HTTPS_PROXY` set for
unrelated tools must not silently reroute music traffic.
6 new tests: no parameter by default, carried on every call once set, carried on
the playback call specifically, kept alongside the cookie, blank means direct,
values are trimmed.
This is additive and off by default — merging it changes nothing until someone
sets `musicProxy`.
Every playback failure produced the same sentence:
无法播放「XXX」(区域/版权限制)
It was wrong for at least four different causes, all of which take a different
fix:
- the account has no membership → open one (or use the shared login)
- the track is delisted / region-locked → pick another track
- this quality level is not ours → drop the level (or wait for the fix)
- upstream refused the IP (-460) → wait, then retry
Measured on the reporter's own library: a free track (fee=8) returned `url:null`
at exhigh while playing fine at higher — "no copyright" was never true for it.
Three separate debugging sessions went after a copyright problem because the
message said so.
The information was there all along: `/song/url/v1` returns `code`, `fee`,
`payed` and `level` on every response. Nothing read them.
What this does:
- `PlayFailure` / `PlayFailureCode` in provider.ts: one shape for "why", with a
ready-to-render `message` and the raw upstream fields kept separately for logs.
- `netease.getSongUrl` throws `SongUrlUnavailable` instead of returning a bare
`null` for a 200-with-no-URL, classified by the fields above. Providers that
have not adopted it keep returning null — `toPlayFailure` covers both.
- `resolveUrlWithRetry` gains `onExhausted`, called once when the budget is
spent (never on cancellation — pressing stop is not a failure) and carrying
the last attempt's error.
- `BotInstance` keeps the result as `lastPlayFailure` and exposes
`getLastPlayFailure()`. Kept as a field rather than a second return value
because `resolveAndPlay` has ~20 call sites and its boolean is load-bearing in
tests; only the web routes need the explanation.
- `player.ts` renders that cause: 「无法播放「X」:需要会员(exhigh)」,
「…:当前音质无播放权限(higher)」, 「…:无版权或已下架」. Batch paths
(playlist / album / artist) append 「,最近一次:…」 instead of claiming every
track had a copyright problem.
- The failure log line now carries `code`, `quality` and `upstream`
(`{"fee":8,"payed":0,"level":"exhigh"}`) — the fields that were missing from
the log during the previous two investigations.
The old wording survives only as a fallback for a bot that could not name a
cause, so behaviour is unchanged when nothing is known.
15 new tests: the five classifications (VIP / album-only / already-paid /
delisted / quality), upstream fields preserved, `onExhausted` fires exactly once
and never on cancel, still fires for a provider that returns null, and the
message is already displayable.
Note for reviewers: this changes `netease.getSongUrl` from returning null to
throwing. `BotInstance` already wraps it in try/catch on the stream-recovery
path, and `resolveUrlWithRetry` catches everything, so the two production
callers are covered. Anything that wraps `getSongUrl` itself (e.g. the
per-user fallback in #186) needs a `catch` — flagged there.
The account radio only governs the browser player (search, playlists, the
embedded preview). Playback inside the TeamSpeak room — a web-queued song, a
`!play` from chat, auto-advance — resolves through the bot's injected provider,
which is the shared login, unconditionally.
That is the intended design: membership is shared, library isolation is not.
A member without VIP still gets to hear paid tracks in the channel; they just
do not get their own recommendations in the web UI.
It was not obvious from the UI, though. "共享账号(管理员的)" reads like a
channel-wide switch, and a member who picked it would expect their play history
to land on the admin account everywhere — which it does, but for an unrelated
reason. Two notes now say so: one in the admin feature hint (what the toggle
does and does not affect), one under the member radio (that it is web-only).
The order was hardcoded: own account → assigned account → shared. That is the
right default (privacy first), but it leaves one common case stuck: a member's
own NetEase login is real but has no membership, while the admin's does. They
linked their account, so playback keeps using theirs, and every paid track
fails — with no way to say "just use the admin's for playback".
Two things now:
1. An explicit choice — `user_music_prefs` (userId + platform), exposed as
GET/PUT `/api/me/music/:platform/preference` and a radio in the account
card. `preferShared: true` outranks EVERYTHING, including `alwaysPersonal`
(someone who chose membership over their own recommendations wants the
shared login for FM too). It stores a flag, not a cookie — flipping it back
restores the personal account untouched.
2. An automatic fallback for people who never touch the switch. Only
`getSongUrl` is wrapped: if the personal account returns `url: null` or
throws, the same track is retried once on the shared login. Search,
playlists and FM stay on the member's own account — that is the point of
per-user logins, and widening the fallback would leak their library back to
the admin's.
Details:
- The fallback lives in `resolveProviderForRequest`, so every playback entry
point (web click, chat !play, auto-advance, playlists) gets it by
construction, and the shared instance is never mutated.
- `fallbackToShared: false` is available for callers that must stay strictly on
the member's account; the default is on, because "my account has no VIP" is
the complaint that produced this feature.
- The status payload now carries `preferShared` and `featureEnabled`, so the UI
can render the radio without a second round-trip and hide it when the admin
has the feature off (PUT answers 409 in that case).
13 new tests: preference overrides own + assigned + alwaysPersonal, feature-off
ignored, GET/PUT round-trip, per-platform isolation, stored cookie untouched,
non-boolean rejected, 409 when disabled; fallback on null, on throw, keeps the
personal result when it works, can be disabled, leaves the shared instance
untouched.
Measured directly against the sidecar on a cloud host, same song, same minute:
GET /song/url/v1?id=1827600686&level=exhigh → 400
{"code":-460,"message":"检测到您的网络环境存在风险,请稍后再试"}
GET …&cookie=<account cookie> → 200, 320k url
So the "无法播放(区域/版权限制)" everyone was chasing is NetEase rejecting
the host's IP, not a copyright or membership problem. It arrives as a 4xx,
which axios reports as ERR_BAD_REQUEST — indistinguishable from a malformed
request without reading the body — and that is why it looked like a dead end in
the logs.
The previous commit retried everything on a flat 250ms backoff. For -460 that
is useless: the risk window lasts a few seconds, so three re-pokes inside 750ms
all land in it and the budget is spent without ever giving the upstream time to
relax. It also spent the 120ms level-switch delay on it, but -460 ignores which
quality we ask for.
Now:
- `netease.getSongUrl` recognises 400 + `code: -460` and rethrows
`RiskControlError` (provider.ts), so the retry layer can tell "wait this out"
from "this track will never play".
- `resolveUrlWithRetry` waits `RISK_CONTROL_BACKOFF_MS * attempt` (800ms,
1600ms, …) instead of 250ms, and never uses the fast level-switch delay while
risk controlled.
- The failure log now says what actually happened
(`hit NetEase risk control (-460) — backing off`) instead of dumping an axios
error that reads like a broken request.
Everything else keeps the old timing: a plain thrown error still retries at
250ms, a genuine 400 (`code: 400`) is not reclassified, and a 200 with `url:null`
still falls through to the quality ladder.
11 new tests: -460 → RiskControlError, genuine 400 untouched, HTML 400
untouched, message preserved, exponential wait, no 120ms switch under risk
control, recovery stops spending, cancellation during a wait.
A cookie file on a live deployment held this:
MUSIC_A_T=1456043741268; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 ...;
Path=/api/clientlog;;MUSIC_R_T=...; Max-Age=...; Path=/eapi/feedback; ...
That is a `Set-Cookie` header pasted whole. The cookie is then handed to the
sidecar as `?cookie=<the whole thing>`, so `Max-Age`, `Expires` and `Path` are
read as cookie NAMES and the string grows to several KB before URL-encoding.
Measured on that box (data/logs/bot.log):
- 34 of 34 `/song/url/v1` calls failed with `ERR_BAD_REQUEST` (HTTP 400);
- the same failure is still happening today, e.g. 17:14 and 17:20 local;
- every one surfaced to the user as 「无法播放(区域/版权限制)」.
So the message people were chasing for weeks is not a copyright signal at all
— it is the sidecar rejecting a malformed request.
`normalizeCookie()` drops attribute pairs, the `Set-Cookie:` prefix, CR/LF and
duplicate names, and keeps only real `name=value` pairs. It is applied:
- on `save()`, so nothing malformed reaches the file again;
- on `load()`, and **written back when it differs** — an existing deployment is
repaired in place without asking anyone to scan a QR code again;
- in `setCookie()` of all four providers, including Kugou, which parses into a
map and would otherwise store `max-age` as a device field.
jellyfin is excluded: its blob is JSON (accessToken/userId/deviceId), not a
cookie header, and normalising it would shred the payload. A test pins that.
Valid cookies are untouched — `normalizeCookie` is idempotent and byte-exact on
a clean string, and a clean file is not rewritten.
This does not overlap with the play-URL retry PR: that one retries a genuine
`url: null`, this one stops the request from being rejected before it is sent.
Both are needed — retrying a 400 just gets four more 400s.
Two failure modes look identical to the user — 「无法播放(区域/版权限制)」 — but
need different handling, and both were hitting the same code path:
1. **Transient.** NetEase intermittently answers `url: null` for a song that
resolves fine a moment later. Repeating the SAME request fixes it, but the
user had to click play repeatedly to be that retry.
2. **Quality gap.** Measured against a real library: a track can be playable at
192k ("higher") while BOTH 320k ("exhigh") and 128k ("standard") return
`url: null`. So the ladder is not continuous and "just drop to the cheapest"
would still fail — every level below the current one has to be tried.
`resolveAndPlay` now resolves through `bot/url-retry.ts`:
- Phase 1: `1 + config.playUrlRetries` attempts (default 2, clamped 0..5) at the
configured quality, 250ms linear backoff between them.
- Phase 2: one attempt per lower level from `provider.getFallbackQualities()`
(NetEase: exhigh → higher → standard), 120ms apart — switching level is a
different request, not a re-poke of the same one.
- Cancel (stop / disconnect) is checked before every attempt, so the budget
never retries into a dead connection.
- A thrown error is retried exactly like an empty result: a sidecar timeout
looks identical to the user.
- Failure is logged once per track, not once per attempt.
Every queue path funnels into `resolveAndPlay` (web click, chat !play,
auto-advance, FM), so playlists and albums get the same budget for free — that
is where "click the playlist four times before it starts" came from.
`config.playUrlRetries` is exposed on GET/POST `/api/bot/settings`. A config
without the field falls back to 2 — retries are ON by default because the whole
point is to be invisible. Set it to 0 to restore the previous fail-fast path.