Commit Graph
616 Commits
Author SHA1 Message Date
TIANYAO ZHANG ea05787cb7 Merge remote-tracking branch 'origin/main' into review/185-hardening
# Conflicts:
#	src/music/netease.ts
2026-11-18 16:53:23 +08:00
TIANYAO ZHANG 406ecda7d7 fix(playback): keep retry changes independent of proxy settings 2026-11-18 16:52:58 +08:00
YilingandTIANYAO ZHANG 2792a86a6c fix(netease): support configurable realIP and align playback User-Agent (#190)
* 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>
2026-11-18 16:49:36 +08:00
TIANYAO ZHANG 2b657ae338 Merge pull request #191 from NoSetViolin/codex/fix-bilibili-189
fix(bilibili): 修复部分 CDN 403 并保留视频分 P 参数
2026-11-18 16:49:28 +08:00
TIANYAO ZHANG 35fa3a95df Merge pull request #188 from NoSetViolin/zty-main-pr
feat(qq): 支持 QQ 音乐登录凭据自动续期
2026-11-18 16:49:20 +08:00
TIANYAO ZHANG 568d49f837 Merge pull request #184 from jiayuLian/fix/cookie-normalize
fix(music): cookie 里存的是整条 Set-Cookie,导致 /song/url 一律返回 400
2026-11-18 16:47:31 +08:00
TIANYAO ZHANG f2a72e3162 Merge pull request #178 from zbn297427669/fix/upstream-test-declick-ramp
test: catch bot tests up with the de-click transport ramp
2026-11-18 16:45:49 +08:00
TIANYAO ZHANG 9928035282 Merge cookie normalization into QQ session renewal 2026-11-18 16:43:49 +08:00
TIANYAO ZHANG 79e9cd797c fix(bilibili): read the page query from the pasted video link 2026-11-18 16:40:27 +08:00
TIANYAO ZHANG 51debb915c fix(music): handle multiple cookie headers and invalid saved values 2026-11-18 16:39:42 +08:00
NoSetViolin b7779ab108 fix(bilibili): preserve video pages and CDN playback headers 2026-11-12 18:07:52 +09:00
jiayuLian 97ee05f1ef tune(playback): spend two requests on -460, not three with a 7.5s tail
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.
2026-11-11 22:44:15 +08:00
jiayuLian 178935a63d fix(playback): give every failure a cause, not just the retried ones
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.
2026-11-11 22:19:58 +08:00
NoSetViolin c3d06cb09a fix(qq): preserve login and playback key expiry 2026-11-11 11:09:42 +09:00
NoSetViolin 72e0d3a439 feat(qq): renew music sessions automatically 2026-11-09 23:07:45 +09:00
jiayuLian d2c44ed256 fix(playback): stop walking the quality ladder once -460 hits
-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.
2026-11-09 20:13:39 +08:00
jiayuLian d8a8574323 tune(playback): -460 backoff 800ms -> 2500ms, matching the observed risk-control window 2026-11-08 19:34:17 +08:00
jiayuLian 2daae59014 feat(music): optional outbound proxy for the NetEase sidecar
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`.
2026-11-08 11:21:37 +00:00
jiayuLian 4c25cfe5e5 fix(playback): name the real reason instead of 「区域/版权限制」
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.
2026-11-08 18:28:36 +08:00
jiayuLian e9995c1e30 fix(playback): back off properly when NetEase risk control answers -460
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.
2026-11-08 17:53:43 +08:00
jiayuLian 4ac3309e34 fix(music): normalise pasted cookies so /song/url stops answering 400
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.
2026-11-08 17:41:58 +08:00
jiayuLian c2771ab9a7 fix(playback): retry and downgrade quality before reporting 无法播放
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.
2026-11-08 17:30:02 +08:00
zbn297427669andClaude Code ba645e5ccb test: catch bot tests up with the de-click transport ramp
Upstream a0f0b49..6f165b5 added the pause/resume fade tail but shipped no
test updates, leaving 5 assertions red (also reproducible on pristine
upstream/main, so not merge-induced).

- instance-recovery/instance harnesses: stub players borrow
  AudioPlayer.prototype.pause/resume, which now call this.setTransportRamp().
  Give the stubs that method or they throw TypeError on pause/resume.
- voice-failure: pausing deliberately emits a fade tail, so the frame count
  no longer freezes at exactly 50. Assert the de-click fade completes, then
  that the scheduler and elapsed clock are genuinely frozen — the actual
  behavior under test.

No production code changed.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-02 15:58:44 +08:00
TIANYAO ZHANG 17008ae52e Merge pull request #177 from EvolvedGhost/fix/audio-declick-seek v1.15.4 2026-10-22 09:00:11 +08:00
EvolvedGhost 6f165b5e88 fix(audio): preserve in-progress pause fade on stop 2026-10-17 23:42:07 +08:00
EvolvedGhost 7ee8b6f986 fix(audio): reset gain after graceful stop 2026-10-17 23:40:20 +08:00
EvolvedGhost 7896c9c9bf fix(audio): fade out on stop command 2026-10-17 23:35:23 +08:00
EvolvedGhost a0f0b49a4e fix(audio): prevent pops during playback controls 2026-10-17 23:30:18 +08:00
TIANYAO ZHANG c26998d296 Merge pull request #176 from NoSetViolin/main
整理设置页分类和创建实例布局,增加主题色与跟随系统外观
v1.15.3
2026-10-14 18:24:20 +08:00
NoSetViolin 8d750d19b0 feat: reorganize settings and add synced appearance preferences 2026-10-12 18:26:53 +09:00
TIANYAO ZHANG 28c128d0c9 fix: harden long-video recovery and voice transport handling (#161) v1.15.2 2026-10-04 01:27:52 +08:00
TIANYAO ZHANG e5879ea106 docs: describe v1.15.1 playback and privacy fixes v1.15.1 2026-10-03 21:03:06 +08:00
TIANYAO ZHANG 44a1457baa fix: isolate embedded music API credential logs 2026-10-03 21:03:05 +08:00
TIANYAO ZHANG a4c0239a59 fix: drain FFmpeg stderr and sanitize playback diagnostics 2026-10-03 21:03:04 +08:00
TIANYAO ZHANG 5258ba951b chore: prepare v1.15.0 release and exclude generated test copies v1.15.0 2026-10-03 17:25:02 +08:00
TIANYAO ZHANG d16aca2ba6 fix: honor artist shuffle permissions and discard stale page requests 2026-10-03 17:25:01 +08:00
TIANYAO ZHANG 9bcddb1881 fix: preserve pause intent and deduplicate stream recovery lookups 2026-10-03 17:17:53 +08:00
TIANYAO ZHANG cf83916f39 fix: serialize artist playback and keep incomplete QQ catalogs retryable 2026-10-03 17:17:35 +08:00
TIANYAO ZHANG f8b03acca3 fix: fence profile updates and check TeamSpeak permission failures 2026-10-03 17:17:35 +08:00
TIANYAO ZHANG b9c79c8138 fix: revoke API keys on password rotation and audit key owners 2026-10-03 17:17:34 +08:00
TIANYAO ZHANG 79fb8443be fix: fence stream recovery and EOF advancement by playback session 2026-10-03 16:55:34 +08:00
TIANYAO ZHANG c904190912 Merge pull request #170 from ZHANGTIANYAO1/fix/issue-161-bilibili-long-stream
# Conflicts:
#	src/bot/instance.test.ts
2026-10-03 16:50:49 +08:00
TIANYAO ZHANG 41b81a6193 Merge pull request #175 from zzstar101/feat/artist-search 2026-10-03 16:50:09 +08:00
TIANYAO ZHANG f495ca0ff4 Merge pull request #174 from razaxq/main 2026-10-03 16:50:09 +08:00
TIANYAO ZHANG bdb33df89d Merge pull request #173 from senlinjun/feat/restapi 2026-10-03 16:50:09 +08:00
TIANYAO ZHANG 3423bf502c docs: plan reviewed PR fixes and release validation 2026-10-03 16:50:08 +08:00
zzstar101 b6ad536bb7 feat(web): artist search, artist pages, and full-catalogue playback
Adds artist support for the NetEase and QQ providers plus the matching UI.

Backend:
- SearchResult gains `artists`; new optional MusicProvider methods
  getArtistDetail / getArtistSongs / getArtistAlbums / getArtistAllSongs.
- NetEase: /cloudsearch type=100 for artist search, /artists, /artist/songs,
  /artist/album and /artist/desc for the artist page.
- QQ: singer search rides along in the existing musicu.fcg batch
  (search_type=1); singer detail via music.web_singer_info_svr. QQ exposes no
  working singer-song paging endpoint, so the full catalogue is built from the
  hot 50 plus every album of the singer (album search filtered by singerMID,
  songs fetched per album, de-duplicated, cached for 10 minutes). A failed
  album sweep is never cached and degrades to the hot list.
- API: GET /api/music/artist/:id and POST /api/player/:botId/play-artist
  (player.control capability, guest flag playCollection); /search/all now
  aggregates artists too.

Frontend:
- Search history in localStorage (max 10, per platform, never shared between
  users), shown as a dropdown under the search box and as 最近搜索 chips.
- Artist row in the search results; new /artist/:id page (portrait, aliases,
  stats, description, top songs, album shelf) with 播放 / 随机播放, which queue
  the singer's whole catalogue.
- playArtist store action.

Tests cover the provider mappers, the new routes, the play-artist collector
(paging, de-duplication, 500-track cap), permission gating and the new views.
2026-10-02 01:36:03 +08:00
razaxq af4ca56fd3 fix(ts6): update the real music client profile 2026-10-01 21:32:21 +08:00
senlinjun bf7858db74 docs(api): document /api/me/music, bilibili parts and personal-FM behavior from v1.14.0
- new /api/me/music section (per-user NetEase account linking, key-compatible)
- GET /api/music/bilibili/parts endpoint
- /api/player/:botId/fm note: prefers the caller's own linked NetEase account
2026-09-29 21:55:53 +08:00
senlinjun e4eea8276a Merge remote-tracking branch 'origin/main' 2026-09-29 21:52:14 +08:00