`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.
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 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.
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.
Every member saw the admin's library: the bot keeps one shared login per
platform (data/cookies/<platform>.json) and search, playlists and playback
URLs all read through it. #164 added a personal NetEase login, but only for
私人FM — the rest still came from the shared account.
On top of that, most members do not own a paid login, so "everyone links their
own" is not enough: the admin has to be able to hand out accounts.
What this adds, behind one admin switch (`perUserMusicAccounts`, default off):
- One login per request, resolved in this order: the caller's OWN linked
account, then an account an admin ASSIGNED, then the bot's shared login.
- An admin-owned pool (`music_accounts`) plus per-member assignments
(`music_account_grants`, PK userId+platform = one per platform). Assignments
are capacity-checked inside a transaction, so an exclusive account cannot be
handed to two members by two concurrent clicks. `enabled = 0` is an instant
rollback of every grant without deleting them.
- Own-beats-assigned, and the two live in separate tables: a member scanning
their own QR code never overwrites an admin's assignment, and unlinking on
the member side never revokes what the admin granted.
- QQ / Kugou / Bilibili now implement `withCookie`, so all four sources can be
isolated. Only NetEase exposes QR self-linking (it is the only one with
`pollQrLogin`); the rest accept an assigned account, which is the workflow
that actually matters for members without a paid login.
- `/api/music-accounts` is admin-only (`requireAdmin`, not `bot.manage`):
members must never see which account was handed to whom. Cookies are masked
in every response.
Switch off = no behaviour change at all, except 私人FM keeps the #164 behaviour
through `alwaysPersonal`.
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.
With several people sharing one bot, personal FM always followed the one
account the bot was logged in with. Each signed-in (non-guest) web user
can now scan a QR code under Settings → 账户 to link their own NetEase
account; FM they start from the WebUI then comes from their account.
- user_music_cookies table (per user + platform, dropped with the user).
- NeteaseProvider.pollQrLogin returns the cookie without storing it, so
a personal login can never replace the bot's shared account;
checkQrCodeStatus is now built on it. withCookie gives a view bound to
another account.
- /api/me/music/netease: status / qrcode / qrcode/status / unlink, acting
only on req.user. The cookie never leaves the server.
- POST /api/player/:botId/fm uses the caller's linked account for
NetEase. Songs still resolve through the shared provider when played.
TeamSpeak chat !fm keeps using the shared account: chat users are not
tied to web accounts.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The bcrypt change-password case runs six bcryptjs rounds (one hash to create
the user, four verifies, one hash for the new password). bcryptjs is pure JS,
so it takes ~4.5s on an idle machine against vitest's 5s default — and tipped
over whenever the full suite saturated the CPU. It read as an intermittent
failure but the work is genuinely slow, not hung.
The new #149 tests spawn real ffmpeg processes, which added enough CPU
pressure to turn an occasional flake into a near-every-run failure, so fix it
rather than leave a suite that cries wolf.
Raise this one case to 20s. Suite is now stably green across repeated full
runs: 138 files / 2109 tests.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Add three default-off capabilities that stop the play queue from being lost,
all gated behind admin/independent toggles so existing behavior is unchanged
until an operator opts in:
- Named save/load of queues (Feature 1): new saved_queues table (per-user +
reserved __shared__ owner, capped at 50 queues / 1000 songs, JSON song blob
that degrades to empty on corruption); /api/saved-queues router (list/save/
load/delete with ownership 404s, inert 403 when disabled); chat commands
!save / !load [-a] / !queues; BotInstance.loadSavedQueue (replace/append).
- Auto-restore live queue across restart (Feature 2): PlayQueue.snapshot/restore,
queue_state table (one row per bot), a debounced snapshot writer driven off
stateChange, and restore+resume on connect. Cancels the pending snapshot on
disconnect so a stale write can't wipe the row a restart must restore.
- playKeepsQueue (Feature 3): BotInstance.playSingleSong funnels chat !play and
the web /play-song route through one place; when enabled a single-song play
inserts-after-current and jumps instead of clearing the queue.
Config gains savedQueuesEnabled + playKeepsQueue (both default false, strict-
coerced on load like spotify.enabled); the settings API round-trips them.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Runtime playback settings were kept only in memory (AudioPlayer.volume,
PlayQueue.mode, each provider's quality field), so restarting the bot reset
them to defaults and users had to re-tune volume and quality every time (#125).
Persist and restore them via the repo's existing storage:
- Volume and play mode are per-bot, stored on new bot_instances columns
(volume, play_mode) with a schema migration; restored when the instance is
(re)built, written by cmdVol / cmdMode which every entry point (chat command,
WebUI, REST) funnels through. Volume and mode are written independently so a
transient !fm/!artist mode switch never overwrites the user's saved !mode.
- Per-provider audio quality is global (shared providers), stored in a new
config.json `audioQuality` block; applied to the providers at startup and
re-snapshotted on POST /api/music/quality.
Queue, current song, progress and FM/artist sessions stay ephemeral.
Adds tests for config sanitize/round-trip, DB player-settings + migration,
cmdVol/cmdMode persistence + construction-time restore, and quality persistence
through the REST endpoint. Documents the behavior in the README.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Make the default playback source a user-configurable setting so servers
that mostly play e.g. Bilibili no longer need to type `-b` on every
`!play`. Previously defaultPlatform() always picked the first enabled
provider by a fixed priority order, with no way to override it.
- config: add optional `defaultPlatform: GateableProvider | null`.
loadConfig sanitizes it — kept only when it names a known provider that
is also currently enabled, else null. defaultPlatform() returns the
preference when enabled, otherwise falls back to the fixed priority order.
- POST /api/bot/settings accepts `defaultPlatform` (validated against the
possibly-updated enabledProviders; null/"" clears it), and reconciles a
stored default that a new enabledProviders list no longer allows. GET and
POST responses expose the field.
- WebUI: new "默认音源" section with a source picker; saving refreshes the
store's default source so it takes effect immediately without a restart.
- Tests: extend config defaultPlatform priority tests and add coverage for
the settings endpoint and /providers routing.
- README: document `defaultPlatform` in the enabledProviders section.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Revert the jellyfin-only default introduced by PR #123 so upgrading
users keep their online sources; Jellyfin becomes opt-in:
- default enabledProviders is now the online set (netease/qq/bilibili/
youtube/kugou); defaultPlatform() uses a fixed priority order
(netease -> qq -> kugou -> jellyfin -> bilibili -> youtube) instead
of jellyfin-first, so chat/REST/WebUI default to netease again
- Settings: Jellyfin card is always visible with a new enable toggle
(its enabled bit is enabledProviders membership); guards against
clobbering other providers before the list loads
- Setup wizard: saving the Jellyfin step auto-enables the source when
a server URL was entered
- Search/player store fallbacks flip from jellyfin to netease; !help
no longer hardcodes Jellyfin lines
- tests: update default-platform assertions, add coverage for the new
default set, legacy configs without enabledProviders, priority
order, and explicit jellyfin-only configs
- README: reframe Jellyfin as optional (badges, command table, quality
tiers, dedicated section, changelog), document the enabledProviders
default and the v1.10.0 jellyfin-only window fix, credit @ItsEricRao
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Merges feature/play-history-requester (@Fa1nttt) into main.
The PR records the WebUI/TeamSpeak requester on queued songs and persists it
to play history (schema migration for requestedBy), rendering it as a badge in
SongCard (gray for 游客/guest).
Conflicts (frontend platform union) resolved to keep both 'spotify' (from #118)
and the new requestedBy/playedAt fields.
Integration fix: the Spotify playback branch in resolveAndPlay (added by #118,
which did not exist on the PR's base) also records play history — added
`requestedBy: song.requestedBy` there so Spotify tracks carry attribution too,
matching the non-Spotify path.
Verified on the merged tree: tsc --noEmit clean, full suite 1309/1309, web build clean.
Co-Authored-By: Fa1nttt <noreply@github.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add the /api/spotify {login,callback,status} router behind the SpotifyOAuthLike
seam (DI-tested with supertest, no network). Build ONE process-wide SpotifyOAuth
in index.ts (clientId/redirectUri from config; store via the already-exported
createFileOAuthTokenStore) and thread that same instance into BOTH createWebServer
AND BotManager -> BotInstance -> SpotifyController, so a web login authorizes
playback (C3.1). Reuses the existing file token store (no token-store.ts).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Construct one SpotifyController per bot (config.spotify + per-bot work/config
dirs under DATA_DIR, threaded via BotManager + index). resolveAndPlay now
routes spotify: sentinels through controller.ensureStarted/playTrack +
player.playPcmStream (falling back to the Stage-1 message when unavailable),
fences/pauses the sidecar on source transitions, advances via controller
"trackEnded", and delegates pause/resume/stop transport. Correction C4:
no re-attach on a spotify->spotify handoff (playPcmStream once across tracks,
no player.stop() — playPcmStream fences the prior ffmpeg internally); occupancy
auto-pause/resume + updateAutoPause + a new BotInstance.seek() (web seek route)
also delegate to the sidecar.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Spotify tracks are metadata-only until the librespot audio backend lands, so
they are surfaced only from the dedicated Spotify tab, not the default
all-sources search. Conscious decision from the whole-branch review (#112).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>