Compare commits

..
Author SHA1 Message Date
TIANYAO ZHANG dd8e8c5950 docs: explain offline Docker deployment 2026-11-18 16:50:45 +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 51debb915c fix(music): handle multiple cookie headers and invalid saved values 2026-11-18 16:39:42 +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
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 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
整理设置页分类和创建实例布局,增加主题色与跟随系统外观
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
45 changed files with 1302 additions and 142 deletions

No files matched your search

+37 -11
View File
@@ -103,12 +103,12 @@ npm start
### 方式三:Docker 一键部署 ### 方式三:Docker 一键部署
所有依赖已内置(Node.js、FFmpeg、Opus 编码器),无需安装任何额外软件。 需要 Docker 和 Docker Compose v2。默认从 GitHub Container Registry(GHCR)拉取预构建镜像,镜像已包含 Node.js、FFmpeg 和 Opus 编码器。
```bash ```bash
git clone https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git git clone https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
cd teamspeak-music-bot/scripts/docker cd teamspeak-music-bot/scripts/docker
docker-compose up -d docker compose up -d
``` ```
打开浏览器访问 **http://localhost:3000** 打开浏览器访问 **http://localhost:3000**
@@ -116,15 +116,14 @@ docker-compose up -d
<details> <details>
<summary>Docker 详细说明</summary> <summary>Docker 详细说明</summary>
- 首次构建需要几分钟(编译原生模块)
- 默认使用 `host` 网络模式,机器人可直接连接局域网 TS3 服务器 - 默认使用 `host` 网络模式,机器人可直接连接局域网 TS3 服务器
- 数据持久化在 Docker 命名卷 `tsmusicbot-data` 中(数据库、Cookie、日志) - 数据持久化在 Docker 命名卷 `tsmusicbot-data` 中(数据库、Cookie、日志)
- 内置健康检查(`/api/health`),支持 Docker 自动重启 - 内置健康检查(`/api/health`),支持 Docker 自动重启
```bash ```bash
docker logs -f tsmusicbot # 查看日志 docker logs -f tsmusicbot # 查看日志
docker-compose down # 停止 docker compose down # 停止
docker-compose up -d --build # 代码更新后重新构建 docker compose pull && docker compose up -d # 更新预构建镜像
``` ```
如果 TS3 服务器在其他机器上,编辑 `docker-compose.yml`: 如果 TS3 服务器在其他机器上,编辑 `docker-compose.yml`:
@@ -136,6 +135,36 @@ ports:
</details> </details>
#### 无法访问 GHCR 时部署
**离线导入发布镜像。** 在能访问 GHCR 的机器上拉取项目官方发布镜像并导出。下面以 `1.15.4` 和 `linux/amd64` 为例,请选择所需发布版本以及部署服务器的架构(`linux/amd64` 或 `linux/arm64`)。Git 发布标签带 `v`,镜像标签不带 `v`。
```bash
image=ghcr.io/zhangtianyao1/teamspeak-music-bot:1.15.4
docker pull --platform linux/amd64 "$image"
docker image save -o tsmusicbot-1.15.4.tar "$image"
```
将归档和同版本的 `scripts/docker/docker-compose.yml` 复制到部署服务器。在 Compose 文件中把 `image:` 改为上面导入的完整镜像名和标签,然后在该文件所在目录运行:
```bash
docker image load -i tsmusicbot-1.15.4.tar
docker compose config --images
docker compose up -d --pull never
```
升级时导入新版本的镜像并更新 `image:` 的标签,再在同一部署目录运行启动命令,以继续使用现有的数据卷。
**从发布源码本地构建。** 若部署机可以访问构建依赖但无法访问 GHCR,可下载或克隆对应发布标签的源码。在 `scripts/docker/docker-compose.yml` 中把 `image:` 替换成下列配置,保持它位于 `services.tsmusicbot` 下:
```yaml
build:
context: ../..
dockerfile: scripts/docker/Dockerfile
```
进入源码的 `scripts/docker` 目录,运行 `docker compose up -d --build`。构建需要获取 `node:22-slim` 基础镜像,以及 Dockerfile 使用的 apt、npm 和原生依赖下载源。升级时切换到所需的新发布标签并重新构建。
### 方式四:Linux 安装脚本 ### 方式四:Linux 安装脚本
Linux 下有两个脚本,按需二选一: Linux 下有两个脚本,按需二选一:
@@ -302,11 +331,8 @@ npm start
```bash ```bash
cd scripts/docker cd scripts/docker
# 拉取最新代码 # 拉取预构建镜像并重新启动
git pull docker compose pull && docker compose up -d
# 重新构建并启动(数据自动保留)
docker-compose up -d --build
``` ```
> 数据(数据库、Cookie、日志)保存在 Docker 命名卷 `tsmusicbot-data` 中,更新不会丢失。 > 数据(数据库、Cookie、日志)保存在 Docker 命名卷 `tsmusicbot-data` 中,更新不会丢失。
@@ -915,7 +941,7 @@ A:B站搜索需要 buvid3 匿名 Cookie(程序启动时自动获取)。如
A:YouTube 是可选音源,需要手动安装 `yt-dlp`。详见 [可选:YouTube 音源](#可选youtube-音源) 章节。快速验证:在项目根目录执行 `bin/yt-dlp --version`(或系统 `yt-dlp --version`),能打印版本号即可。若 yt-dlp 已安装但仍搜索失败,通常是网络/地域问题或 yt-dlp 版本过旧(执行 `yt-dlp -U` 升级)。 A:YouTube 是可选音源,需要手动安装 `yt-dlp`。详见 [可选:YouTube 音源](#可选youtube-音源) 章节。快速验证:在项目根目录执行 `bin/yt-dlp --version`(或系统 `yt-dlp --version`),能打印版本号即可。若 yt-dlp 已安装但仍搜索失败,通常是网络/地域问题或 yt-dlp 版本过旧(执行 `yt-dlp -U` 升级)。
**Q:如何更新到新版本?** **Q:如何更新到新版本?**
A:`git pull` 拉取最新代码,然后 `npm install && npm run build && npm start` 重新构建启动。Docker 用户执行 `docker-compose up -d --build`。 A:`git pull` 拉取最新代码,然后 `npm install && npm run build && npm start` 重新构建启动。使用预构建镜像的 Docker 用户执行 `docker compose pull && docker compose up -d`,离线导入或本地构建用户按各自的部署步骤升级。
**Q:忘记管理员密码怎么办?** **Q:忘记管理员密码怎么办?**
A:直接操作 SQLite 数据库。最简单的办法是清空 `users` 表然后重新进入 first-run 流程:`sqlite3 data/tsmusicbot.db "DELETE FROM users; DELETE FROM sessions;"`,重启后浏览器会自动跳转 `/first-run` 让你重新创建管理员。详细方法见 [从 WebUI 无鉴权版本升级](#从-webui-无鉴权版本升级重要)。 A:直接操作 SQLite 数据库。最简单的办法是清空 `users` 表然后重新进入 first-run 流程:`sqlite3 data/tsmusicbot.db "DELETE FROM users; DELETE FROM sessions;"`,重启后浏览器会自动跳转 `/first-run` 让你重新创建管理员。详细方法见 [从 WebUI 无鉴权版本升级](#从-webui-无鉴权版本升级重要)。
+101 -17
View File
@@ -206,6 +206,14 @@ export class AudioPlayer extends EventEmitter {
private duckingRampStartedAt = 0; private duckingRampStartedAt = 0;
private duckingRampDurationMs = 0; private duckingRampDurationMs = 0;
private pcmBuffer: Buffer = Buffer.alloc(0); private pcmBuffer: Buffer = Buffer.alloc(0);
private transitionSilence = false;
private pauseFrames = 0;
private resumeSilenceFrames = 0;
private stopAfterPauseTail = false;
private transportRampStart: number | null = null;
private transportRampEnd: number | null = null;
private transportRampFrom = 1;
private transportRampTo = 1;
private logger: Logger; private logger: Logger;
private frameLoopRunning = false; private frameLoopRunning = false;
private nextFrameTime = 0; private nextFrameTime = 0;
@@ -256,7 +264,7 @@ export class AudioPlayer extends EventEmitter {
play(url: string, seekSeconds = 0, songDuration = 0): void { play(url: string, seekSeconds = 0, songDuration = 0): void {
// 1. 停止当前所有播放,自增 sessionId 屏蔽旧回调 ( // 1. 停止当前所有播放,自增 sessionId 屏蔽旧回调 (
this.stop(); this.stop(true);
const currentSessionId = this.sessionId; const currentSessionId = this.sessionId;
this.currentUrl = url; this.currentUrl = url;
@@ -270,7 +278,7 @@ export class AudioPlayer extends EventEmitter {
if (this.consecutiveFailures >= AudioPlayer.MAX_CONSECUTIVE_FAILURES) { if (this.consecutiveFailures >= AudioPlayer.MAX_CONSECUTIVE_FAILURES) {
this.logger.error({ failures: this.consecutiveFailures }, "FFmpeg failures limit reached"); this.logger.error({ failures: this.consecutiveFailures }, "FFmpeg failures limit reached");
this.state = "idle"; this.stop();
this.emit("error", new Error("ffmpeg unavailable")); this.emit("error", new Error("ffmpeg unavailable"));
return; return;
} }
@@ -497,7 +505,7 @@ export class AudioPlayer extends EventEmitter {
playPcmStream(readable: Readable, opts: { onExternalEnd?: () => void } = {}): void { playPcmStream(readable: Readable, opts: { onExternalEnd?: () => void } = {}): void {
// 1. Fence current playback: stop() bumps sessionId, clears pcmBuffer, kills // 1. Fence current playback: stop() bumps sessionId, clears pcmBuffer, kills
// any ffmpeg, and DETACHES (never destroys) any prior external stream. // any ffmpeg, and DETACHES (never destroys) any prior external stream.
this.stop(); this.stop(true);
const currentSessionId = this.sessionId; const currentSessionId = this.sessionId;
this.externalMode = true; this.externalMode = true;
@@ -587,7 +595,26 @@ export class AudioPlayer extends EventEmitter {
this.onExternalEnd = null; this.onExternalEnd = null;
} }
stop(): void { stopWithFade(): void {
if (this.externalMode || this.state === "idle") {
this.stop();
return;
}
this.stopAfterPauseTail = true;
if (this.state === "playing") {
this.pauseFrames = 9;
this.setTransportRamp(0, 0, 5);
this.state = "paused";
} else if (this.pauseFrames === 0) {
this.stop();
}
}
stop(keepAlive = false): void {
const wasRunning = this.frameLoopRunning;
const deadline = this.nextFrameTime;
this.transitionSilence = keepAlive;
this.stopAfterPauseTail = false;
// 3. 递增 ID 是最有效的逻辑“隔离墙” // 3. 递增 ID 是最有效的逻辑“隔离墙”
this.sessionId++; this.sessionId++;
this.frameLoopRunning = false; this.frameLoopRunning = false;
@@ -630,6 +657,17 @@ export class AudioPlayer extends EventEmitter {
this.seekOffset = 0; this.seekOffset = 0;
this.framesPlayed = 0; this.framesPlayed = 0;
this.healthyFrames = 0; this.healthyFrames = 0;
this.pauseFrames = 0;
this.resumeSilenceFrames = 0;
this.transportRampStart = null;
this.transportRampEnd = null;
this.transportRampFrom = 1;
this.transportRampTo = 1;
if (keepAlive) {
this.frameLoopRunning = true;
this.nextFrameTime = wasRunning ? Math.max(performance.now(), deadline - FRAME_DURATION_MS) : performance.now();
this.scheduleNextFrame();
}
} }
private forceCleanup(proc: ChildProcess, pid: number): void { private forceCleanup(proc: ChildProcess, pid: number): void {
@@ -675,8 +713,25 @@ export class AudioPlayer extends EventEmitter {
if (loopSessionId !== this.sessionId || !this.frameLoopRunning) return; if (loopSessionId !== this.sessionId || !this.frameLoopRunning) return;
const framesBeforeTick = this.framesPlayed; const framesBeforeTick = this.framesPlayed;
if (this.state === "playing") this.sendNextFrame(); if (this.state === "paused") {
else if (this.state === "paused") this.nextFrameTime = performance.now(); if (this.pauseFrames > 0) {
this.pauseFrames--;
if (this.pauseFrames > 3) this.sendNextFrame();
else this.emitSilenceFrame(false);
} else {
this.nextFrameTime = performance.now();
if (this.stopAfterPauseTail) {
this.stop();
return;
}
}
}
else if (this.state === "idle" && this.transitionSilence) this.emitSilenceFrame(false);
else if (this.state === "playing" && this.resumeSilenceFrames > 0) {
this.resumeSilenceFrames--;
this.emitSilenceFrame(false);
}
else if (this.state === "playing") this.sendNextFrame();
const frameSent = this.framesPlayed > framesBeforeTick; const frameSent = this.framesPlayed > framesBeforeTick;
// 检测pcmBuffer不足PCM_FRAME_BYTES导致连续循环卡死: // 检测pcmBuffer不足PCM_FRAME_BYTES导致连续循环卡死:
@@ -748,7 +803,7 @@ export class AudioPlayer extends EventEmitter {
// R3-4: likewise gated on state==="playing" — a drained/EOF'd stream must // R3-4: likewise gated on state==="playing" — a drained/EOF'd stream must
// not emit trackEnd while paused; end-detection resumes on resume(). // not emit trackEnd while paused; end-detection resumes on resume().
if (this.state === "playing" && !this.externalMode && !this.ffmpeg && this.pcmBuffer.length < PCM_FRAME_BYTES) { if (this.state === "playing" && !this.externalMode && !this.ffmpeg && !this.downloader && this.pcmBuffer.length < PCM_FRAME_BYTES) {
this.frameLoopRunning = false; this.frameLoopRunning = false;
// Outer gate guarantees state==="playing"; end directly (no !=="idle" guard). // Outer gate guarantees state==="playing"; end directly (no !=="idle" guard).
this.state = "idle"; this.state = "idle";
@@ -764,12 +819,12 @@ export class AudioPlayer extends EventEmitter {
private sendNextFrame(): void { private sendNextFrame(): void {
if (this.pcmBuffer.length < PCM_FRAME_BYTES) { if (this.pcmBuffer.length < PCM_FRAME_BYTES) {
// External mode: the sidecar PCM stream is long-lived and must NOT end on // Keep the voice timeline continuous while the source is preparing/stalled.
// a transient underrun. Emit an encoded silence frame so the 20ms voice // URL silence must not advance elapsed time or hide the stall watchdog.
// timeline stays continuous instead of returning (which would desync TS). if (this.externalMode || this.ffmpeg || this.downloader || this.transitionSilence) this.emitSilenceFrame(this.externalMode);
if (this.externalMode) this.emitSilenceFrame();
return; return;
} }
this.transitionSilence = false;
const pcmFrame = this.pcmBuffer.subarray(0, PCM_FRAME_BYTES); const pcmFrame = this.pcmBuffer.subarray(0, PCM_FRAME_BYTES);
this.pcmBuffer = this.pcmBuffer.subarray(PCM_FRAME_BYTES); this.pcmBuffer = this.pcmBuffer.subarray(PCM_FRAME_BYTES);
@@ -798,11 +853,11 @@ export class AudioPlayer extends EventEmitter {
} }
} }
private emitSilenceFrame(): void { private emitSilenceFrame(advanceTimeline = true): void {
try { try {
const opusFrame = this.encoder.encode(Buffer.alloc(PCM_FRAME_BYTES)); const opusFrame = this.encoder.encode(Buffer.alloc(PCM_FRAME_BYTES));
this.emit("frame", opusFrame); this.emit("frame", opusFrame);
this.framesPlayed++; if (advanceTimeline) this.framesPlayed++;
} catch (err) { } catch (err) {
this.emit("error", err as Error); this.emit("error", err as Error);
} }
@@ -813,8 +868,10 @@ export class AudioPlayer extends EventEmitter {
const now = performance.now(); const now = performance.now();
const startDuckingGain = this.duckingGainAt(now); const startDuckingGain = this.duckingGainAt(now);
const endDuckingGain = this.duckingGainAt(now + FRAME_DURATION_MS); const endDuckingGain = this.duckingGainAt(now + FRAME_DURATION_MS);
const startFactor = baseFactor * startDuckingGain; const startTransportGain = this.transportGainAt(now);
const endFactor = baseFactor * endDuckingGain; const endTransportGain = this.transportGainAt(now + FRAME_DURATION_MS);
const startFactor = baseFactor * startDuckingGain * startTransportGain;
const endFactor = baseFactor * endDuckingGain * endTransportGain;
if (startFactor >= 1 && endFactor >= 1) { if (startFactor >= 1 && endFactor >= 1) {
return Buffer.from(pcm); return Buffer.from(pcm);
@@ -844,6 +901,25 @@ export class AudioPlayer extends EventEmitter {
return out; return out;
} }
private setTransportRamp(target: number, delayFrames = 0, durationFrames = 3): void {
const now = performance.now();
const from = this.transportGainAt(now);
this.transportRampStart = now + FRAME_DURATION_MS * delayFrames;
this.transportRampEnd = this.transportRampStart + FRAME_DURATION_MS * durationFrames;
this.transportRampFrom = from;
this.transportRampTo = target;
}
private transportGainAt(at: number): number {
if (this.transportRampStart === null || this.transportRampEnd === null) return this.transportRampTo;
const progress = Math.max(0, Math.min(1, (at - this.transportRampStart) / (this.transportRampEnd - this.transportRampStart)));
if (progress >= 1) {
this.transportRampStart = null;
this.transportRampEnd = null;
}
return this.transportRampFrom + (this.transportRampTo - this.transportRampFrom) * progress;
}
private duckingGainAt(at: number): number { private duckingGainAt(at: number): number {
if (this.duckingRampDurationMs <= 0) return this.duckingTargetGain; if (this.duckingRampDurationMs <= 0) return this.duckingTargetGain;
@@ -868,11 +944,19 @@ export class AudioPlayer extends EventEmitter {
// transport is delegated to the SpotifyController by the caller (Task 7). // transport is delegated to the SpotifyController by the caller (Task 7).
if (this.externalMode) return; if (this.externalMode) return;
if (this.currentUrl && Number.isFinite(seconds) && seconds >= 0) { if (this.currentUrl && Number.isFinite(seconds) && seconds >= 0) {
const paused = this.state === "paused";
this.play(this.currentUrl, seconds, this.currentSongDuration); this.play(this.currentUrl, seconds, this.currentSongDuration);
if (paused && this.state === "playing") this.pause();
} }
} }
pause(): void { if (this.state === "playing") this.state = "paused"; } pause(): void {
resume(): void { if (this.state === "paused") { this.state = "playing"; this.nextFrameTime = performance.now(); } } if (this.state === "playing") {
this.pauseFrames = 9;
this.setTransportRamp(0, 0, 5);
this.state = "paused";
}
}
resume(): void { if (this.state === "paused") { this.pauseFrames = 0; this.resumeSilenceFrames = 3; this.setTransportRamp(1, 3, 5); this.state = "playing"; } }
resetFailures(): void { this.consecutiveFailures = 0; } resetFailures(): void { this.consecutiveFailures = 0; }
setVolume(vol: number): void { this.volume = Math.max(0, Math.min(100, vol)); } setVolume(vol: number): void { this.volume = Math.max(0, Math.min(100, vol)); }
getVolume(): number { return this.volume; } getVolume(): number { return this.volume; }
+4
View File
@@ -29,6 +29,10 @@ function makeBot() {
player.getVolume = () => 50; player.getVolume = () => 50;
player.pause = AudioPlayer.prototype.pause; player.pause = AudioPlayer.prototype.pause;
player.resume = AudioPlayer.prototype.resume; 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.play = vi.fn((_url: string, position: number) => { player.sessionId++; player.elapsed = position; player.state = "playing"; });
player.stop = vi.fn(() => { player.sessionId++; player.state = "idle"; }); player.stop = vi.fn(() => { player.sessionId++; player.state = "idle"; });
const provider = { getSongUrl: vi.fn(async (): Promise<{ url: string } | null> => ({ url: "fresh" })) }; const provider = { getSongUrl: vi.fn(async (): Promise<{ url: string } | null> => ({ url: "fresh" })) };
+4
View File
@@ -1780,6 +1780,10 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
player.getPlaybackSessionId = AudioPlayer.prototype.getPlaybackSessionId; player.getPlaybackSessionId = AudioPlayer.prototype.getPlaybackSessionId;
player.pause = AudioPlayer.prototype.pause; player.pause = AudioPlayer.prototype.pause;
player.resume = AudioPlayer.prototype.resume; 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"; }); player.play = vi.fn(() => { player.sessionId++; player.state = "playing"; });
const provider = { getSongUrl: vi.fn(async () => ({ url: "fresh" })) }; const provider = { getSongUrl: vi.fn(async () => ({ url: "fresh" })) };
const advances: string[] = []; const advances: string[] = [];
+5 -2
View File
@@ -1547,11 +1547,13 @@ export class BotInstance extends EventEmitter {
private cmdStop(): string { private cmdStop(): string {
// Read the current song BEFORE queue.clear() so we can tell whether the // Read the current song BEFORE queue.clear() so we can tell whether the
// sidecar needs stopping. // sidecar needs stopping.
if (this.queue.current()?.platform === "spotify") { const isSpotify = this.queue.current()?.platform === "spotify";
if (isSpotify) {
this.spotifyController.stop(); this.spotifyController.stop();
} }
this.currentSourceIsSpotify = false; this.currentSourceIsSpotify = false;
this.player.stop(); if (isSpotify) this.player.stop();
else this.player.stopWithFade();
this.jellyfinReporter?.onStop(); this.jellyfinReporter?.onStop();
this.autoPaused = false; this.autoPaused = false;
this.queue.clear(); this.queue.clear();
@@ -2103,6 +2105,7 @@ export class BotInstance extends EventEmitter {
this.isAdvancing = true; this.isAdvancing = true;
let started = false; let started = false;
try { try {
if (this.player.getState() !== "idle") this.player.stop(true);
this.voteSkipUsers.clear(); this.voteSkipUsers.clear();
const next = this.queue.next(); const next = this.queue.next();
if (next) { if (next) {
+10 -2
View File
@@ -65,9 +65,17 @@ describe("BotInstance persistent voice send failure", () => {
expect(frames).toBe(50); expect(frames).toBe(50);
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 }); h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 });
vi.advanceTimersByTime(3000); vi.advanceTimersByTime(3000);
expect(frames).toBe(50); // Pausing emits a short de-click fade tail (pauseFrames) so the last
expect(h.player.getElapsed()).toBe(1); // 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"); 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(); } } finally { h.player.stop(); }
}); });
+23 -1
View File
@@ -37,13 +37,35 @@ describe("database", () => {
const userCols = botDb.db.prepare("PRAGMA table_info(users)").all() as Array<{ name: string }>; const userCols = botDb.db.prepare("PRAGMA table_info(users)").all() as Array<{ name: string }>;
const userColNames = userCols.map((c) => c.name).sort(); const userColNames = userCols.map((c) => c.name).sort();
expect(userColNames).toEqual(["createdAt", "id", "passwordHash", "role", "updatedAt", "username"]); expect(userColNames).toEqual(["accentColor", "createdAt", "id", "passwordHash", "role", "updatedAt", "username"]);
const sessionCols = botDb.db.prepare("PRAGMA table_info(sessions)").all() as Array<{ name: string }>; const sessionCols = botDb.db.prepare("PRAGMA table_info(sessions)").all() as Array<{ name: string }>;
const sessionColNames = sessionCols.map((c) => c.name).sort(); const sessionColNames = sessionCols.map((c) => c.name).sort();
expect(sessionColNames).toEqual(["createdAt", "expiresAt", "id", "lastSeenAt", "userId"]); expect(sessionColNames).toEqual(["createdAt", "expiresAt", "id", "lastSeenAt", "userId"]);
}); });
it("migrates existing accounts and preserves their accent across database reopen", async () => {
const dir = mkdtempSync(join(tmpdir(), 'tsmb-accent-'));
const path = join(dir, 'test.db');
let db = createDatabase(path);
try {
const user = await createUserStore(db.db).createUser('alice', 'test-password', 'member');
db.db.exec('ALTER TABLE users DROP COLUMN accentColor');
db.close();
db = createDatabase(path);
const users = createUserStore(db.db);
expect(users.getAccentColor(user.id)).toBe('#335eea');
users.setAccentColor(user.id, '#0891b2');
db.close();
db = createDatabase(path);
expect(createUserStore(db.db).getAccentColor(user.id)).toBe('#0891b2');
expect(createUserStore(db.db).findById(user.id)?.username).toBe('alice');
} finally {
db.close();
rmSync(dir, { recursive: true, force: true });
}
});
it("creates user_audit table on init", () => { it("creates user_audit table on init", () => {
const tables = botDb.db const tables = botDb.db
.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name") .prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
+3
View File
@@ -210,6 +210,9 @@ function migrateSchema(db: Database.Database): void {
if (!userColNames.includes("role")) { if (!userColNames.includes("role")) {
db.exec("ALTER TABLE users ADD COLUMN role TEXT NOT NULL DEFAULT 'admin'"); db.exec("ALTER TABLE users ADD COLUMN role TEXT NOT NULL DEFAULT 'admin'");
} }
if (!userColNames.includes("accentColor")) {
db.exec("ALTER TABLE users ADD COLUMN accentColor TEXT NOT NULL DEFAULT '#335eea'");
}
const historyColumns = db.prepare("PRAGMA table_info(play_history)").all() as Array<{ name: string }>; const historyColumns = db.prepare("PRAGMA table_info(play_history)").all() as Array<{ name: string }>;
const historyColNames = historyColumns.map((c) => c.name); const historyColNames = historyColumns.map((c) => c.name);
+8
View File
@@ -22,6 +22,8 @@ export interface UserRow {
} }
export interface UserStore { export interface UserStore {
getAccentColor(userId: string): string;
setAccentColor(userId: string, color: string): boolean;
countUsers(): number; countUsers(): number;
countAdmins(): number; countAdmins(): number;
createUser(username: string, password: string, role: UserRole): Promise<UserRow>; createUser(username: string, password: string, role: UserRole): Promise<UserRow>;
@@ -68,6 +70,12 @@ export function createUserStore(db: Database.Database): UserStore {
const deleteUserStmt = db.prepare("DELETE FROM users WHERE id = ?"); const deleteUserStmt = db.prepare("DELETE FROM users WHERE id = ?");
return { return {
getAccentColor(userId) {
return (db.prepare("SELECT accentColor FROM users WHERE id = ?").get(userId) as { accentColor: string } | undefined)?.accentColor ?? "#335eea";
},
setAccentColor(userId, color) {
return db.prepare("UPDATE users SET accentColor = ?, updatedAt = ? WHERE id = ? AND role != 'guest'").run(color, Date.now(), userId).changes > 0;
},
countUsers() { countUsers() {
return (countStmt.get() as { n: number }).n; return (countStmt.get() as { n: number }).n;
}, },
+75
View File
@@ -0,0 +1,75 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createCookieStore } from "./auth.js";
let dir: string;
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), "cookie-store-"));
});
afterEach(() => {
fs.rmSync(dir, { recursive: true, force: true });
});
/** The blob a live deployment actually had on disk (abridged). */
const BLOB =
"MUSIC_A_T=1456043741268; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 21:48:40 GMT; Path=/api/clientlog;" +
";MUSIC_R_T=1456043923317; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 21:48:40 GMT; Path=/eapi/feedback;" +
";MUSIC_U=00ABCDEF0123456789abcdef; Max-Age=1296000; Path=/";
describe("cookie store", () => {
it("normalises on save, so a pasted header never reaches the file", () => {
const store = createCookieStore(dir);
store.save("netease", BLOB);
const onDisk = JSON.parse(fs.readFileSync(path.join(dir, "netease.json"), "utf-8"));
expect(onDisk.cookie).toBe("MUSIC_A_T=1456043741268; MUSIC_R_T=1456043923317; MUSIC_U=00ABCDEF0123456789abcdef");
expect(onDisk.cookie).not.toContain("Max-Age");
});
it("repairs a file that was already written by an older build", () => {
const file = path.join(dir, "netease.json");
fs.writeFileSync(file, JSON.stringify({ cookie: BLOB }), "utf-8");
const store = createCookieStore(dir);
expect(store.load("netease")).toBe(
"MUSIC_A_T=1456043741268; MUSIC_R_T=1456043923317; MUSIC_U=00ABCDEF0123456789abcdef",
);
// Written back, so the next start does not have to repair it again.
const onDisk = JSON.parse(fs.readFileSync(file, "utf-8"));
expect(onDisk.cookie).not.toContain("Path=");
});
it("keeps a valid cookie byte-for-byte and does not rewrite the file", () => {
const file = path.join(dir, "netease.json");
const valid = "MUSIC_U=abc; __csrf=def";
fs.writeFileSync(file, JSON.stringify({ cookie: valid, updatedAt: "2026-01-01T00:00:00.000Z" }), "utf-8");
const before = fs.readFileSync(file, "utf-8");
expect(createCookieStore(dir).load("netease")).toBe(valid);
expect(fs.readFileSync(file, "utf-8")).toBe(before);
});
// jellyfin stores JSON (token / userId / deviceId), not a cookie header.
// Normalising it would shred every '=' and comma in the payload.
it("leaves the jellyfin credential blob untouched", () => {
const blob = JSON.stringify({ accessToken: "a=b", userId: "u1", deviceId: "d1" });
const store = createCookieStore(dir);
store.save("jellyfin", blob);
expect(store.load("jellyfin")).toBe(blob);
});
it("returns an empty string for a missing or corrupt file", () => {
const store = createCookieStore(dir);
expect(store.load("qq")).toBe("");
fs.writeFileSync(path.join(dir, "qq.json"), "{not json", "utf-8");
expect(store.load("qq")).toBe("");
});
it("ignores a well-formed JSON file with a non-string cookie", () => {
fs.writeFileSync(path.join(dir, "qq.json"), JSON.stringify({ cookie: { invalid: true } }));
expect(createCookieStore(dir).load("qq")).toBe("");
});
});
+39 -7
View File
@@ -1,10 +1,22 @@
import fs from "node:fs"; import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { normalizeCookie } from "./cookie-normalize.js";
/** Platforms with a persisted credential blob. For jellyfin the "cookie" is a /** Platforms with a persisted credential blob. For jellyfin the "cookie" is a
* JSON string carrying the access token / userId / deviceId (see jellyfin.ts). */ * JSON string carrying the access token / userId / deviceId (see jellyfin.ts). */
type CookiePlatform = "netease" | "qq" | "bilibili" | "kugou" | "jellyfin"; type CookiePlatform = "netease" | "qq" | "bilibili" | "kugou" | "jellyfin";
/**
* Everything except jellyfin stores a `Cookie:` header value, which people paste
* by hand and therefore paste wrong — usually the whole `Set-Cookie` line, with
* `Max-Age` / `Expires` / `Path` in it. Those get read as cookie names and the
* sidecar answers 400, which the user sees as 「无法播放(区域/版权限制)」.
* jellyfin's blob is JSON and must not be touched.
*/
function storesCookieHeader(platform: CookiePlatform): boolean {
return platform !== "jellyfin";
}
export interface CookieStore { export interface CookieStore {
save(platform: CookiePlatform, cookie: string): void; save(platform: CookiePlatform, cookie: string): void;
load(platform: CookiePlatform): string; load(platform: CookiePlatform): string;
@@ -15,25 +27,45 @@ export function createCookieStore(cookieDir: string): CookieStore {
fs.mkdirSync(cookieDir, { recursive: true }); fs.mkdirSync(cookieDir, { recursive: true });
} }
function write(platform: CookiePlatform, cookie: string): void {
const filePath = path.join(cookieDir, `${platform}.json`);
fs.writeFileSync(
filePath,
JSON.stringify({ cookie, updatedAt: new Date().toISOString() }),
{ encoding: "utf-8", mode: 0o600 }
);
}
return { return {
save(platform: CookiePlatform, cookie: string): void { save(platform: CookiePlatform, cookie: string): void {
const filePath = path.join(cookieDir, `${platform}.json`); write(platform, storesCookieHeader(platform) ? normalizeCookie(cookie) : cookie);
fs.writeFileSync(
filePath,
JSON.stringify({ cookie, updatedAt: new Date().toISOString() }),
{ encoding: "utf-8", mode: 0o600 }
);
}, },
load(platform: CookiePlatform): string { load(platform: CookiePlatform): string {
const filePath = path.join(cookieDir, `${platform}.json`); const filePath = path.join(cookieDir, `${platform}.json`);
if (!fs.existsSync(filePath)) return ""; if (!fs.existsSync(filePath)) return "";
let stored: string;
try { try {
const data = JSON.parse(fs.readFileSync(filePath, "utf-8")); const data = JSON.parse(fs.readFileSync(filePath, "utf-8"));
return data.cookie ?? ""; if (typeof data?.cookie !== "string") return "";
stored = data.cookie;
} catch { } catch {
return ""; return "";
} }
if (!storesCookieHeader(platform)) return stored;
const clean = normalizeCookie(stored);
if (clean === stored) return clean;
// Repair in place: an existing deployment already has the header blob on
// disk, and fixing it here means the next request is clean without making
// anyone scan a QR code again. Best-effort — a read-only volume must not
// take the bot down, the cleaned value is still returned.
try {
write(platform, clean);
} catch {
/* keep serving the cleaned in-memory value */
}
return clean;
}, },
}; };
} }
+2 -1
View File
@@ -1,3 +1,4 @@
import { normalizeCookie } from "./cookie-normalize.js";
import { createHash } from "node:crypto"; import { createHash } from "node:crypto";
import axios, { type AxiosInstance } from "axios"; import axios, { type AxiosInstance } from "axios";
import type { import type {
@@ -461,7 +462,7 @@ export class BiliBiliProvider implements MusicProvider {
} }
setCookie(cookie: string): void { setCookie(cookie: string): void {
this.cookie = cookie; this.cookie = normalizeCookie(cookie);
} }
getCookie(): string { getCookie(): string {
+85
View File
@@ -0,0 +1,85 @@
import { describe, expect, it } from "vitest";
import { isNormalizedCookie, normalizeCookie } from "./cookie-normalize.js";
/**
* The exact shape found in a live deployment's data/cookies/netease.json. Every
* `/song/url/v1` call answered 400 while this was stored, and the user saw
* 「无法播放(区域/版权限制)」 on every play attempt.
*/
const HEADER_BLOB = [
"MUSIC_A_T=1456043741268; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 21:48:40 GMT; Path=/api/clientlog;",
";MUSIC_R_T=1456043923317; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 21:48:40 GMT; Path=/eapi/feedback;",
";NMTID=00Oyuu_9EnDq_rMBEMIuKakmlo4dukAAAGht0p3Kw; Max-Age=315360000; Expires=Tue, 04 Nov 2036 18:34:33 GMT; Path=/;",
";MUSIC_U=00ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef0123456; Max-Age=1296000; Expires=Mon, 23 Nov 2026 09:32:11 GMT; Path=/;",
";__csrf=8f14e45fceea167a5a36dedd4bea2543; Max-Age=1296000; Expires=Mon, 23 Nov 2026 09:32:11 GMT; Path=/;",
].join("");
describe("normalizeCookie", () => {
it("keeps only the real cookie pairs from a pasted Set-Cookie blob", () => {
expect(normalizeCookie(HEADER_BLOB)).toBe(
"MUSIC_A_T=1456043741268; MUSIC_R_T=1456043923317; NMTID=00Oyuu_9EnDq_rMBEMIuKakmlo4dukAAAGht0p3Kw; " +
"MUSIC_U=00ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef0123456789ABCDEF0123456789abcdef0123456; " +
"__csrf=8f14e45fceea167a5a36dedd4bea2543",
);
});
it("drops every attribute name so it cannot be read as a cookie", () => {
const out = normalizeCookie(HEADER_BLOB);
for (const attr of ["Max-Age", "Expires", "Path", "Domain", "Secure", "HttpOnly", "SameSite"]) {
expect(out).not.toContain(`${attr}=`);
}
});
it("shrinks the query string enough to stop the 400", () => {
// The real blob repeats one attribute set per request path, so it grows
// several KB and the re-encoded query is what the sidecar rejects. The
// fixture is the same shape at a smaller scale; what matters is that the
// bulk (attributes) is gone and only the payload survives.
expect(normalizeCookie(HEADER_BLOB).length).toBeLessThan(HEADER_BLOB.length * 0.6);
});
it("leaves an already-valid cookie untouched", () => {
const valid = "MUSIC_U=abc123; __csrf=def456; NMTID=xyz";
expect(normalizeCookie(valid)).toBe(valid);
expect(isNormalizedCookie(valid)).toBe(true);
});
it("is idempotent", () => {
const once = normalizeCookie(HEADER_BLOB);
expect(normalizeCookie(once)).toBe(once);
});
it("strips a pasted `Set-Cookie:` / `Cookie:` prefix", () => {
expect(normalizeCookie("Set-Cookie: MUSIC_U=abc; Path=/")).toBe("MUSIC_U=abc");
expect(normalizeCookie("cookie: MUSIC_U=abc")).toBe("MUSIC_U=abc");
});
it("keeps each cookie from multiple pasted Set-Cookie lines", () => {
expect(normalizeCookie("Set-Cookie: MUSIC_U=abc; Path=/\r\nSet-Cookie: __csrf=def; HttpOnly"))
.toBe("MUSIC_U=abc; __csrf=def");
});
it("empties out a blob that carries no real cookie at all", () => {
expect(normalizeCookie("Max-Age=1; Expires=Thu, 25 Nov 2094 21:48:40 GMT; Path=/")).toBe("");
});
it("removes CR/LF left inside a value by a multi-line paste", () => {
expect(normalizeCookie("MUSIC_U=abc\r\ndef; __csrf=x")).toBe("MUSIC_U=abcdef; __csrf=x");
});
it("keeps the last value when a name repeats", () => {
expect(normalizeCookie("MUSIC_A_T=1; MUSIC_A_T=2")).toBe("MUSIC_A_T=2");
});
it("keeps '=' inside a value (base64 padding)", () => {
expect(normalizeCookie("MUSIC_U=abc==; Path=/")).toBe("MUSIC_U=abc==");
});
it("drops nameless fragments and empty values", () => {
expect(normalizeCookie(";; =x; MUSIC_U=abc; empty=;")).toBe("MUSIC_U=abc");
});
it("handles the empty string", () => {
expect(normalizeCookie("")).toBe("");
});
});
+91
View File
@@ -0,0 +1,91 @@
/**
* Cookies for the music platforms are pasted in by hand, and what people paste
* is usually not a cookie — it is the raw `Set-Cookie` header, attributes and
* all:
*
* MUSIC_A_T=145...; Max-Age=2147483647; Expires=Thu, 25 Nov 2094 ...; Path=/api/clientlog;
* ;MUSIC_R_T=145...; Max-Age=2147483647; Expires=...; Path=/eapi/feedback; ...
*
* Every `;`-separated fragment with an `=` is treated as a cookie pair, so
* `Max-Age`, `Expires` and `Path` become cookie NAMES. The string then gets
* passed to the sidecar API as `?cookie=...`, and two things happen:
*
* 1. the sidecar answers **400** instead of a song URL. Measured on a live
* deployment: 34 of 34 `/song/url/v1` calls failed with ERR_BAD_REQUEST
* while the cookie file held a header blob, and every one of those surfaced
* to the user as 「无法播放(区域/版权限制)」;
* 2. the query string grows to several KB (5 KB of header re-encoded becomes
* closer to 10 KB), which can also trip the HTTP request-line limit.
*
* Normalising both on the way in (setCookie) and on the way out (loading the
* stored file) repairs existing deployments without asking anyone to log in
* again. Nothing about a VALID cookie changes — see the tests.
*/
/**
* Attributes that belong to a Set-Cookie LINE, never to a Cookie header. Kept
* lowercase for the comparison. `size` is Chrome-specific, `partitioned` and
* `priority` are newer additions, and `comment`/`version` are RFC 2109 leftovers
* that still show up in hand-copied blobs.
*/
const SET_COOKIE_ATTRIBUTES = new Set([
"max-age",
"expires",
"path",
"domain",
"secure",
"httponly",
"samesite",
"priority",
"partitioned",
"version",
"comment",
"size",
"sameparty",
]);
/** RFC 6265 cookie-name (token) — anything else is header noise, not a name. */
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
/**
* Turn whatever was pasted into a syntactically valid `Cookie:` header value.
*
* - handles pasted `Set-Cookie:` / `Cookie:` header lines
* - drops attribute pairs (`Max-Age`, `Expires`, `Path`, ...)
* - drops fragments without `=` (`;;`, trailing separators)
* - drops values that are empty, which the sidecar reads as "unset anyway"
* - strips CR/LF, which a multi-line paste leaves inside values and which make
* the outgoing query string invalid
* - de-duplicates by name, last one wins (a header blob repeats MUSIC_A_T a
* dozen times for different paths; the payload is identical each time)
*
* Idempotent: normalising an already-normalised cookie returns it unchanged.
*/
export function normalizeCookie(raw: string): string {
if (!raw) return "";
const text = raw.trim().replace(/^[ \t]*(?:set-)?cookie[ \t]*:[ \t]*/gim, ";");
const pairs = new Map<string, string>();
for (const fragment of text.split(";")) {
const eq = fragment.indexOf("=");
if (eq <= 0) continue;
const name = fragment.slice(0, eq).trim();
// A value may legitimately contain '=' (base64 padding), so keep the rest.
const value = fragment.slice(eq + 1).replace(/[\r\n]+/g, "").trim();
if (!name || !value) continue;
if (!TOKEN.test(name)) continue;
if (SET_COOKIE_ATTRIBUTES.has(name.toLowerCase())) continue;
pairs.set(name, value);
}
return [...pairs].map(([name, value]) => `${name}=${value}`).join("; ");
}
/** True when `raw` is already a clean cookie header and normalising is a no-op. */
export function isNormalizedCookie(raw: string): boolean {
return normalizeCookie(raw) === raw;
}
+4 -1
View File
@@ -15,6 +15,7 @@
* residential IP is required. QR login and VIP audio could not be verified in * residential IP is required. QR login and VIP audio could not be verified in
* the build environment. * the build environment.
*/ */
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios"; import axios, { type AxiosInstance } from "axios";
import crypto from "node:crypto"; import crypto from "node:crypto";
import zlib from "node:zlib"; import zlib from "node:zlib";
@@ -442,7 +443,9 @@ export class KugouProvider implements MusicProvider {
// --- Cookie persistence (CookieStore stores a flat "k=v; k=v" string) ------ // --- Cookie persistence (CookieStore stores a flat "k=v; k=v" string) ------
setCookie(cookie: string): void { setCookie(cookie: string): void {
const map: CookieMap = {}; const map: CookieMap = {};
for (const part of (cookie || "").split(";")) { // Normalise first: a pasted `Set-Cookie` line would otherwise land
// Max-Age/Expires/Path in the map as cookie names.
for (const part of normalizeCookie(cookie).split(";")) {
const eq = part.indexOf("="); const eq = part.indexOf("=");
if (eq < 0) continue; if (eq < 0) continue;
const k = part.slice(0, eq).trim(); const k = part.slice(0, eq).trim();
+4 -1
View File
@@ -1,3 +1,4 @@
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios"; import axios, { type AxiosInstance } from "axios";
import type { import type {
MusicProvider, MusicProvider,
@@ -390,7 +391,9 @@ export class NeteaseProvider implements MusicProvider {
} }
setCookie(cookie: string): void { setCookie(cookie: string): void {
this.cookie = cookie; // Normalised so a pasted `Set-Cookie` line cannot put Max-Age/Expires/Path
// into the query string — that is what made the sidecar answer 400.
this.cookie = normalizeCookie(cookie);
} }
getCookie(): string { getCookie(): string {
+4 -1
View File
@@ -1,3 +1,4 @@
import { normalizeCookie } from "./cookie-normalize.js";
import axios, { type AxiosInstance } from "axios"; import axios, { type AxiosInstance } from "axios";
import type { import type {
MusicProvider, MusicProvider,
@@ -818,7 +819,9 @@ export class QQMusicProvider implements MusicProvider {
} }
setCookie(cookie: string): void { setCookie(cookie: string): void {
this.cookie = cookie; // Normalised: see music/cookie-normalize.ts for why a pasted Set-Cookie
// line breaks every request.
this.cookie = normalizeCookie(cookie);
// Reset radar pagination so a re-login (different account) starts from the // Reset radar pagination so a re-login (different account) starts from the
// first page rather than inheriting the previous account's cursor. // first page rather than inheriting the previous account's cursor.
this.radarPage = 1; this.radarPage = 1;
+2 -1
View File
@@ -285,7 +285,7 @@ export function createPlayerRouter(
if (index >= queue.size()) { if (index >= queue.size()) {
return { status: 400 as const, body: { error: "Invalid queue index" } }; return { status: 400 as const, body: { error: "Invalid queue index" } };
} }
bot.getPlayer().stop(); bot.getPlayer().stop(true);
bot.getPlayer().resetFailures(); bot.getPlayer().resetFailures();
const song = queue.playAt(index); const song = queue.playAt(index);
if (!song) { if (!song) {
@@ -293,6 +293,7 @@ export function createPlayerRouter(
} }
const ok = await bot.resolveAndPlay(song); const ok = await bot.resolveAndPlay(song);
if (!ok) { if (!ok) {
bot.getPlayer().stop();
return { body: { message: `Cannot play: ${song.name}` } }; return { body: { message: `Cannot play: ${song.name}` } };
} }
return { body: { message: `Now playing: ${song.name} - ${song.artist}` } }; return { body: { message: `Now playing: ${song.name} - ${song.artist}` } };
+25
View File
@@ -127,6 +127,29 @@ describe("session router", () => {
expect(anon.status).toBe(401); expect(anon.status).toBe(401);
}); });
it("stores accent preferences per account and returns them to other sessions", async () => {
const alice = await users.createUser("alice", "pw-alice", "member");
const bob = await users.createUser("bob", "pw-bob", "member");
const cookieA = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`;
const cookieB = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`;
const updated = await request(app).put('/api/session/preferences').set('Cookie', cookieA)
.send({ accentColor: '#8B5CF6', userId: bob.id });
expect(updated.status).toBe(200);
expect(updated.body.accentColor).toBe('#8b5cf6');
expect((await request(app).get('/api/session/me').set('Cookie', cookieB)).body.accentColor).toBe('#8b5cf6');
expect(users.getAccentColor(bob.id)).toBe('#335eea');
});
it("rejects anonymous and invalid preference updates without altering the account", async () => {
const alice = await users.createUser("alice", "pw-alice", "member");
const cookie = `${SESSION_COOKIE_NAME}=${sessions.createSession(alice.id).token}`;
expect((await request(app).put('/api/session/preferences').send({ accentColor: '#8b5cf6' })).status).toBe(401);
for (const accentColor of ['red', '#fff', '#zzzzzz', null, 123]) {
expect((await request(app).put('/api/session/preferences').set('Cookie', cookie).send({ accentColor })).status).toBe(400);
}
expect(users.getAccentColor(alice.id)).toBe('#335eea');
});
it("POST /logout deletes the session and clears the cookie", async () => { it("POST /logout deletes the session and clears the cookie", async () => {
await users.createUser("alice", "pw-alice", "admin"); await users.createUser("alice", "pw-alice", "admin");
const loginRes = await request(app) const loginRes = await request(app)
@@ -300,6 +323,8 @@ describe("session router — guest mode", () => {
expect(me.body.guest.addToQueue).toBe(true); expect(me.body.guest.addToQueue).toBe(true);
expect(me.body.guest.playNext).toBe(true); expect(me.body.guest.playNext).toBe(true);
expect(me.body.capabilities).toEqual([]); expect(me.body.capabilities).toEqual([]);
expect(me.body.accentColor).toBeNull();
expect((await request(app).put('/api/session/preferences').set('Cookie', cookie).send({ accentColor: '#8b5cf6' })).status).toBe(403);
}); });
it("GET /needs-setup exposes guestAllowed", async () => { it("GET /needs-setup exposes guestAllowed", async () => {
+18
View File
@@ -182,9 +182,27 @@ export function createSessionRouter(
capabilities: [...ctx.capabilities], capabilities: [...ctx.capabilities],
bots: ctx.bots === "all" ? "all" : [...ctx.bots], bots: ctx.bots === "all" ? "all" : [...ctx.bots],
guest: ctx.guest ?? null, guest: ctx.guest ?? null,
accentColor: user.role === "guest" ? null : users.getAccentColor(user.id),
}); });
}); });
router.put("/preferences", requireAuthInline, (req, res) => {
if (req.user!.role === "guest") {
res.status(403).json({ error: "guests store appearance preferences locally" });
return;
}
const color = req.body?.accentColor;
if (typeof color !== "string" || !/^#[0-9a-fA-F]{6}$/.test(color)) {
res.status(400).json({ error: "invalid accent color" });
return;
}
if (!users.setAccentColor(req.user!.id, color.toLowerCase())) {
res.status(404).json({ error: "user not found" });
return;
}
res.json({ accentColor: color.toLowerCase() });
});
router.post("/change-password", requireAuthInline, async (req, res) => { router.post("/change-password", requireAuthInline, async (req, res) => {
const { oldPassword, newPassword } = req.body ?? {}; const { oldPassword, newPassword } = req.body ?? {};
if (typeof oldPassword !== "string") { if (typeof oldPassword !== "string") {
+2 -2
View File
@@ -35,8 +35,8 @@
full square. Android reads the manifest instead. --> full square. Android reads the manifest instead. -->
<link rel="apple-touch-icon" href="/apple-touch-icon.png"> <link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="manifest" href="/site.webmanifest"> <link rel="manifest" href="/site.webmanifest">
<!-- Matches --bg-primary of the dark theme, which is what the app starts in <meta name="color-scheme" content="light dark">
(stores/player.ts defaults to 'dark' and never follows the OS scheme). --> <!-- Updated at startup and whenever the resolved appearance changes. -->
<meta name="theme-color" content="#222222"> <meta name="theme-color" content="#222222">
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Barlow:wght@400;500;600;700;800&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@400;500;600;700;800&display=swap" rel="stylesheet">
+10 -3
View File
@@ -1,5 +1,5 @@
<template> <template>
<div class="app" :data-theme="theme"> <div class="app" :data-theme="theme" :style="accentStyle">
<Navbar /> <Navbar />
<main class="main-content"> <main class="main-content">
<RouterView /> <RouterView />
@@ -82,7 +82,7 @@
<Icon icon="mdi:music-box-multiple" class="tab-icon" /> <Icon icon="mdi:music-box-multiple" class="tab-icon" />
<span class="tab-label">音乐库</span> <span class="tab-label">音乐库</span>
</RouterLink> </RouterLink>
<RouterLink v-if="!session.isGuest.value" to="/settings" class="m-tab" :class="{ active: route.path.startsWith('/settings') }"> <RouterLink to="/settings" class="m-tab" :class="{ active: route.path.startsWith('/settings') }">
<Icon icon="mdi:cog" class="tab-icon" /> <Icon icon="mdi:cog" class="tab-icon" />
<span class="tab-label">设置</span> <span class="tab-label">设置</span>
</RouterLink> </RouterLink>
@@ -98,6 +98,7 @@ import { usePlayerStore } from './stores/player.js';
import { useDecoupledSlider } from './composables/useDecoupledSlider.js'; import { useDecoupledSlider } from './composables/useDecoupledSlider.js';
import { useWebSocket } from './composables/useWebSocket.js'; import { useWebSocket } from './composables/useWebSocket.js';
import { useSession } from './composables/useSession.js'; import { useSession } from './composables/useSession.js';
import { accentTokens } from './styles/accent.js';
import Navbar from './components/Navbar.vue'; import Navbar from './components/Navbar.vue';
import Player from './components/Player.vue'; import Player from './components/Player.vue';
import CoverArt from './components/CoverArt.vue'; import CoverArt from './components/CoverArt.vue';
@@ -113,6 +114,10 @@ const canTransport = computed(() => can('player.control') || guestCan('transport
const canSkip = computed(() => can('player.control') || guestCan('skip')); const canSkip = computed(() => can('player.control') || guestCan('skip'));
const canModeCtl = computed(() => can('player.control') || guestCan('playMode')); const canModeCtl = computed(() => can('player.control') || guestCan('playMode'));
const theme = computed(() => playerStore.theme); const theme = computed(() => playerStore.theme);
const accentStyle = computed(() => accentTokens(playerStore.accentColor));
watch(() => `${session.currentUser.value?.id ?? ''}:${session.currentUser.value?.accentColor ?? ''}`, () => {
playerStore.loadAccentColor(session.currentUser.value?.accentColor);
}, { immediate: true });
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const { connect } = useWebSocket(); const { connect } = useWebSocket();
@@ -331,8 +336,9 @@ function cycleMobileMode() {
playerStore.setMode(nextMode); playerStore.setMode(nextMode);
} }
let stopThemeSync: (() => void) | undefined;
onMounted(async () => { onMounted(async () => {
playerStore.loadTheme(); stopThemeSync = playerStore.loadTheme();
connect(); connect();
// Hydrate favorites once per session so deep-links / hard refreshes onto // Hydrate favorites once per session so deep-links / hard refreshes onto
// Search or Playlist render hearts correctly without first visiting Home. // Search or Playlist render hearts correctly without first visiting Home.
@@ -355,6 +361,7 @@ onMounted(async () => {
}); });
onUnmounted(() => { onUnmounted(() => {
stopThemeSync?.();
if (syncTimer) clearInterval(syncTimer); if (syncTimer) clearInterval(syncTimer);
if (mobileRaf !== null) cancelAnimationFrame(mobileRaf); if (mobileRaf !== null) cancelAnimationFrame(mobileRaf);
}); });
+104
View File
@@ -0,0 +1,104 @@
<template>
<div class="rgb-picker">
<button ref="trigger" type="button" class="picker-trigger" :aria-expanded="open" aria-controls="accent-rgb-panel" @click="toggle"><span class="trigger-swatch" :style="{ background: modelValue }" />自定义颜色<Icon :icon="open ? 'mdi:chevron-up' : 'mdi:chevron-down'" /></button>
<Teleport to="body">
<div v-if="open" class="picker-dismiss" @pointerdown="close" />
<section v-if="open" id="accent-rgb-panel" ref="panel" class="picker-panel" :data-theme="theme" :style="[position, accentTokens(modelValue)]" role="dialog" aria-label="自定义颜色" @keydown.esc.stop.prevent="close">
<header>自定义颜色<button type="button" aria-label="关闭调色板" @click="close"><Icon icon="mdi:close" /></button></header>
<div ref="palette" class="color-palette" :style="{ backgroundColor: `hsl(${hue}, 100%, 50%)` }" tabindex="0" role="slider" aria-label="饱和度与明度" aria-valuemin="0" aria-valuemax="100" :aria-valuenow="Math.round(saturation * 100)" :aria-valuetext="`饱和度 ${Math.round(saturation * 100)}%,明度 ${Math.round(value * 100)}%`" @pointerdown="startPalette" @pointermove="movePalette" @pointerup="endPalette" @pointercancel="endPalette" @keydown="paletteKey"><span class="palette-cursor" :style="{ left: `${saturation * 100}%`, top: `${(1 - value) * 100}%`, background: modelValue }" /></div>
<div class="hue-row"><span class="preview-swatch" :style="{ background: modelValue }" /><input class="hue-strip" type="range" min="0" max="360" :value="hue" aria-label="色相" @input="changeHue" /></div>
<div class="rgb-values"><label v-for="(channel, index) in channels" :key="channel.key"><span>{{ channel.key }}</span><input type="number" min="0" max="255" step="1" :value="rgb[index]" :aria-label="`${channel.name}通道色值`" @change="updateChannel(index, $event)" @blur="updateChannel(index, $event)" @keydown.enter.prevent="updateChannel(index, $event)" /></label></div>
<p>在色板上选取颜色,或输入 RGB 色值</p>
</section>
</Teleport>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { Icon } from '@iconify/vue';
import { accentTokens } from '../styles/accent';
const props = defineProps<{ modelValue: string }>();
const emit = defineEmits<{ 'update:modelValue': [color: string] }>();
const open = ref(false);
const theme = ref('dark');
const trigger = ref<HTMLButtonElement>();
const panel = ref<HTMLElement>();
const palette = ref<HTMLElement>();
const position = ref({ left: '0px', top: '0px' });
const hue = ref(0), saturation = ref(0), value = ref(0);
let dragging: number | null = null;
const channels = [{ key: 'R', name: '红色' }, { key: 'G', name: '绿色' }, { key: 'B', name: '蓝色' }];
const rgb = computed(() => [1, 3, 5].map(offset => parseInt(props.modelValue.slice(offset, offset + 2), 16)));
watch(rgb, ([red, green, blue]) => {
const [r, g, b] = [red / 255, green / 255, blue / 255];
const max = Math.max(r, g, b), min = Math.min(r, g, b), delta = max - min;
value.value = max; saturation.value = max ? delta / max : 0;
if (delta) hue.value = ((max === r ? (g - b) / delta : max === g ? (b - r) / delta + 2 : (r - g) / delta + 4) * 60 + 360) % 360;
}, { immediate: true });
function emitRgb(next: number[]) { emit('update:modelValue', '#' + next.map(channel => Math.round(channel).toString(16).padStart(2, '0')).join('')); }
function emitHsv() {
const h = hue.value / 60, c = value.value * saturation.value, x = c * (1 - Math.abs(h % 2 - 1)), m = value.value - c;
const components = [[c,x,0],[x,c,0],[0,c,x],[0,x,c],[x,0,c],[c,0,x]][Math.floor(h) % 6];
emitRgb(components.map(component => (component + m) * 255));
}
function locate() {
if (!trigger.value || !panel.value) return;
const rect = trigger.value.getBoundingClientRect(), width = panel.value.offsetWidth, height = panel.value.offsetHeight;
position.value = { left: `${Math.max(12, Math.min(rect.left, window.innerWidth - width - 12))}px`, top: `${rect.bottom + 8 + height <= window.innerHeight - 12 ? rect.bottom + 8 : Math.max(12, rect.top - height - 8)}px` };
}
async function toggle() {
if (open.value) return close();
theme.value = trigger.value?.closest('[data-theme]')?.getAttribute('data-theme') || 'dark';
open.value = true; await nextTick(); locate(); palette.value?.focus({ preventScroll: true });
window.addEventListener('resize', locate); window.addEventListener('scroll', locate, true); document.addEventListener('keydown', escape);
}
function removeListeners() { window.removeEventListener('resize', locate); window.removeEventListener('scroll', locate, true); document.removeEventListener('keydown', escape); }
function close() { open.value = false; dragging = null; removeListeners(); trigger.value?.focus({ preventScroll: true }); }
function escape(event: KeyboardEvent) { if (event.key === 'Escape') close(); }
onBeforeUnmount(removeListeners);
function selectPalette(event: PointerEvent) {
const rect = palette.value!.getBoundingClientRect();
saturation.value = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width));
value.value = 1 - Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height)); emitHsv();
}
function startPalette(event: PointerEvent) { if (event.button !== 0) return; dragging = event.pointerId; palette.value?.setPointerCapture(event.pointerId); palette.value?.focus({ preventScroll: true }); selectPalette(event); }
function movePalette(event: PointerEvent) { if (dragging === event.pointerId) selectPalette(event); }
function endPalette(event: PointerEvent) { if (dragging !== event.pointerId) return; if (palette.value?.hasPointerCapture(event.pointerId)) palette.value.releasePointerCapture(event.pointerId); dragging = null; }
function paletteKey(event: KeyboardEvent) {
if (!['ArrowLeft','ArrowRight','ArrowUp','ArrowDown'].includes(event.key)) return;
event.preventDefault(); const step = event.shiftKey ? .1 : .01;
saturation.value = Math.max(0, Math.min(1, saturation.value + (event.key === 'ArrowRight' ? step : event.key === 'ArrowLeft' ? -step : 0)));
value.value = Math.max(0, Math.min(1, value.value + (event.key === 'ArrowUp' ? step : event.key === 'ArrowDown' ? -step : 0))); emitHsv();
}
function changeHue(event: Event) { hue.value = Number((event.target as HTMLInputElement).value); emitHsv(); }
function updateChannel(index: number, event: Event) {
const input = event.target as HTMLInputElement;
if (!input.value.trim() || !Number.isFinite(Number(input.value))) { input.value = String(rgb.value[index]); return; }
const next = [...rgb.value]; next[index] = Math.max(0, Math.min(255, Math.round(Number(input.value)))); input.value = String(next[index]); emitRgb(next);
}
</script>
<style scoped lang="scss">
.rgb-picker { width: 100%; }
.picker-trigger { display: inline-flex; align-items: center; gap: 10px; padding: 8px 12px; border: 1px solid var(--border-color); border-radius: var(--radius-md); background: var(--hover-bg); color: var(--text-primary); font-size: 13px; cursor: pointer; }
.picker-trigger:hover { border-color: var(--color-primary); }
.picker-trigger > svg { color: var(--text-secondary); font-size: 18px; }
.trigger-swatch { width: 24px; height: 24px; border: 1px solid var(--border-color); border-radius: 6px; }
.picker-dismiss { position: fixed; inset: 0; z-index: 149; }
.picker-panel { position: fixed; z-index: 150; width: min(320px, calc(100vw - 24px)); box-sizing: border-box; max-height: calc(100dvh - 24px); overflow-y: auto; padding: 18px; border: 1px solid var(--border-color); border-radius: 16px; background: var(--bg-secondary); color: var(--text-primary); box-shadow: 0 16px 48px rgba(0,0,0,.24), 0 2px 8px rgba(0,0,0,.12); }
.picker-panel header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; font-size: 14px; font-weight: 600; }
.picker-panel header button { display: grid; place-items: center; width: 26px; height: 26px; border: 0; border-radius: 6px; background: transparent; color: var(--text-secondary); font-size: 18px; cursor: pointer; }
.picker-panel header button:hover { background: var(--hover-bg); }
.color-palette { position: relative; height: 180px; border-radius: 9px; background-image: linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent); cursor: crosshair; touch-action: none; }
.palette-cursor { position: absolute; width: 16px; height: 16px; box-sizing: border-box; border: 2px solid #fff; border-radius: 50%; transform: translate(-50%,-50%); box-shadow: 0 0 0 1px rgba(0,0,0,.45), 0 1px 4px rgba(0,0,0,.3); pointer-events: none; }
.hue-row { display: flex; align-items: center; gap: 12px; margin: 18px 0; }
.preview-swatch { flex-shrink: 0; width: 28px; height: 28px; border-radius: 8px; border: 1px solid var(--border-color); }
.hue-strip { appearance: none; min-width: 0; width: 100%; height: 12px; border-radius: 999px; background: linear-gradient(to right,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00); cursor: pointer; }
.hue-strip::-webkit-slider-thumb { appearance: none; width: 16px; height: 20px; border: 2px solid white; border-radius: 6px; background: transparent; box-shadow: 0 0 0 1px rgba(0,0,0,.35); }
.hue-strip::-moz-range-thumb { width: 12px; height: 16px; border: 2px solid white; border-radius: 6px; background: transparent; box-shadow: 0 0 0 1px rgba(0,0,0,.35); }
.rgb-values { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 10px; }
.rgb-values label { display: flex; flex-direction: column; gap: 6px; text-align: center; font-size: 11px; color: var(--text-secondary); }
.rgb-values input { width: 100%; box-sizing: border-box; padding: 8px; text-align: center; border: 1px solid var(--border-color); border-radius: 7px; background: var(--bg-primary); color: var(--text-primary); font: 13px var(--font-mono); appearance: textfield; }
.rgb-values input::-webkit-inner-spin-button, .rgb-values input::-webkit-outer-spin-button { appearance: none; margin: 0; }
.picker-panel :focus-visible, .picker-trigger:focus-visible { outline: 2px solid var(--color-primary); outline-offset: 3px; }
.picker-panel p { margin: 14px 0 0; color: var(--text-tertiary); font-size: 11px; text-align: center; }
</style>
+1 -1
View File
@@ -87,7 +87,7 @@ function clear() {
font-size: 12px; font-size: 12px;
font-weight: 600; font-weight: 600;
transition: all var(--transition-fast); transition: all var(--transition-fast);
&:hover { background: var(--color-primary); color: white; } &:hover { background: var(--color-primary); color: var(--color-on-primary); }
} }
.btn-danger { .btn-danger {
+2 -2
View File
@@ -207,7 +207,7 @@ function formatDuration(seconds: number): string {
.part-badge { .part-badge {
background: var(--color-primary); background: var(--color-primary);
color: white; color: var(--color-on-primary);
} }
.part-name { .part-name {
@@ -254,7 +254,7 @@ function formatDuration(seconds: number): string {
.btn-primary { .btn-primary {
padding: 10px 20px; padding: 10px 20px;
background: var(--color-primary); background: var(--color-primary);
color: white; color: var(--color-on-primary);
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
font-size: 13px; font-size: 13px;
font-weight: 600; font-weight: 600;
+11 -4
View File
@@ -104,7 +104,7 @@
</div> </div>
</div> </div>
<RouterLink v-if="!session.isGuest.value" to="/settings" class="settings-btn"> <RouterLink to="/settings" class="settings-btn" aria-label="设置" title="设置">
<Icon icon="mdi:cog" /> <Icon icon="mdi:cog" />
</RouterLink> </RouterLink>
@@ -655,7 +655,7 @@ onUnmounted(() => {
&.primary { &.primary {
background: var(--color-primary); background: var(--color-primary);
color: #fff; color: var(--color-on-primary);
border-color: var(--color-primary); border-color: var(--color-primary);
} }
@@ -665,9 +665,16 @@ onUnmounted(() => {
} }
.settings-btn { .settings-btn {
font-size: 22px; display: grid;
place-items: center;
width: 36px;
height: 36px;
flex-shrink: 0;
font-size: 20px;
line-height: 1;
opacity: 0.6; opacity: 0.6;
transition: opacity var(--transition-fast); transition: opacity var(--transition-fast);
svg { display: block; width: 20px; height: 20px; }
&:hover { opacity: 1; } &:hover { opacity: 1; }
@media (max-width: 768px) { @media (max-width: 768px) {
@@ -750,7 +757,7 @@ onUnmounted(() => {
&.primary { &.primary {
background: var(--color-primary); background: var(--color-primary);
border-color: var(--color-primary); border-color: var(--color-primary);
color: #fff; color: var(--color-on-primary);
&:hover { &:hover {
filter: brightness(1.08); filter: brightness(1.08);
+1 -1
View File
@@ -426,7 +426,7 @@ function cycleMode() {
align-items: center; align-items: center;
justify-content: center; justify-content: center;
font-size: 18px; font-size: 18px;
color: white; color: var(--color-on-primary);
transition: transform var(--transition-fast); transition: transform var(--transition-fast);
&:hover { transform: scale(1.08); } &:hover { transform: scale(1.08); }
&:active { transform: scale(0.95); } &:active { transform: scale(0.95); }
+16
View File
@@ -7,6 +7,7 @@ interface User {
capabilities?: string[]; capabilities?: string[];
bots?: "all" | string[]; bots?: "all" | string[];
guest?: Record<string, boolean> | null; guest?: Record<string, boolean> | null;
accentColor?: string | null;
} }
const currentUser = ref<User | null>(null); const currentUser = ref<User | null>(null);
@@ -112,6 +113,20 @@ async function logout(): Promise<void> {
currentUser.value = null; currentUser.value = null;
} }
async function saveAccentColor(accentColor: string): Promise<void> {
const userId = currentUser.value?.id;
const res = await fetch('/api/session/preferences', {
method: 'PUT', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ accentColor }),
});
if (!res.ok) throw new Error('主题色保存失败,请稍后重试。');
const saved = await res.json();
if (currentUser.value?.id === userId && currentUser.value) {
currentUser.value = { ...currentUser.value, accentColor: saved.accentColor };
}
}
function can(cap: string): boolean { function can(cap: string): boolean {
const u = currentUser.value; const u = currentUser.value;
return !!u && (u.role === "admin" || (u.capabilities ?? []).includes(cap)); return !!u && (u.role === "admin" || (u.capabilities ?? []).includes(cap));
@@ -143,6 +158,7 @@ export function useSession() {
logout, logout,
setup, setup,
continueAsGuest, continueAsGuest,
saveAccentColor,
can, can,
guestCan, guestCan,
canControlBot, canControlBot,
+2
View File
@@ -5,7 +5,9 @@ import router from './router/index.js';
import { installApiClient } from './api/http.js'; import { installApiClient } from './api/http.js';
import './styles/global.scss'; import './styles/global.scss';
import './styles/mobile.scss'; import './styles/mobile.scss';
import { applyDocumentTheme, readThemePreference, resolveTheme } from './styles/theme.js';
applyDocumentTheme(resolveTheme(readThemePreference()));
installApiClient(); installApiClient();
const app = createApp(App); const app = createApp(App);
+2 -2
View File
@@ -60,8 +60,8 @@ router.beforeEach(async (to) => {
return { name: 'login', query: { next: to.fullPath } }; return { name: 'login', query: { next: to.fullPath } };
} }
// Guests may never reach settings/setup, even by typing the URL. // Guests can customize appearance; server configuration remains inaccessible.
const GUEST_BLOCKED = new Set(['settings', 'setup']); const GUEST_BLOCKED = new Set(['setup']);
if (session.isGuest.value && GUEST_BLOCKED.has(to.name as string)) { if (session.isGuest.value && GUEST_BLOCKED.has(to.name as string)) {
return { name: 'home' }; return { name: 'home' };
} }
+35 -6
View File
@@ -2,6 +2,8 @@ import { defineStore } from 'pinia';
import axios from 'axios'; import axios from 'axios';
import { resolveScopedBot } from './scope.js'; import { resolveScopedBot } from './scope.js';
import { useSession } from '../composables/useSession.js'; import { useSession } from '../composables/useSession.js';
import { DEFAULT_ACCENT, normalizeAccent, readGuestAccent, saveGuestAccent } from '../styles/accent.js';
import { applyDocumentTheme, observeSystemTheme, readThemePreference, resolveTheme, type ThemePreference } from '../styles/theme.js';
export interface Song { export interface Song {
id: string; id: string;
@@ -126,7 +128,9 @@ export const usePlayerStore = defineStore('player', {
queues: {} as Record<string, Song[]>, queues: {} as Record<string, Song[]>,
/** Per-bot timing state keyed by botId */ /** Per-bot timing state keyed by botId */
timings: {} as Record<string, TimingState>, timings: {} as Record<string, TimingState>,
theme: 'dark' as 'dark' | 'light', themePreference: readThemePreference(),
theme: resolveTheme(readThemePreference()),
accentColor: DEFAULT_ACCENT,
// Which sources the server has enabled (GET /api/music/providers) and the // Which sources the server has enabled (GET /api/music/providers) and the
// configured default. Empty until fetched — sections stay hidden briefly. // configured default. Empty until fetched — sections stay hidden briefly.
@@ -336,14 +340,39 @@ export const usePlayerStore = defineStore('player', {
this.queues[botId] = queue; this.queues[botId] = queue;
}, },
toggleTheme() { setThemePreference(preference: ThemePreference) {
this.theme = this.theme === 'dark' ? 'light' : 'dark'; this.themePreference = preference;
localStorage.setItem('theme', this.theme); try { localStorage.setItem('theme', preference); } catch { /* Keep the selection for this session if storage is unavailable. */ }
this.theme = resolveTheme(preference);
applyDocumentTheme(this.theme);
}, },
loadTheme() { loadTheme() {
const saved = localStorage.getItem('theme') as 'dark' | 'light' | null; this.themePreference = readThemePreference();
if (saved) this.theme = saved; this.theme = resolveTheme(this.themePreference);
applyDocumentTheme(this.theme);
return observeSystemTheme((dark) => {
if (this.themePreference !== 'system') return;
this.theme = resolveTheme('system', dark);
applyDocumentTheme(this.theme);
});
},
setAccentColor(value: string) {
const color = normalizeAccent(value);
if (!color) return;
this.accentColor = color;
},
saveGuestAccentColor() {
saveGuestAccent(this.accentColor);
},
loadAccentColor(value?: string | null) {
const session = useSession();
this.accentColor = !session.currentUser.value || session.isGuest.value
? readGuestAccent()
: normalizeAccent(value ?? '') ?? DEFAULT_ACCENT;
}, },
async startBotInstance(id: string) { async startBotInstance(id: string) {
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it, vi, afterEach } from 'vitest';
import { accentTokens, DEFAULT_ACCENT, normalizeAccent, readGuestAccent, saveGuestAccent } from './accent.js';
afterEach(() => vi.unstubAllGlobals());
describe('accent preferences', () => {
it('normalizes hex values and rejects invalid saved input', () => {
expect(normalizeAccent(' #AbC ')).toBe('#aabbcc');
expect(normalizeAccent('#8B5CF6')).toBe('#8b5cf6');
expect(normalizeAccent('url(example)')).toBeNull();
expect(accentTokens('invalid')['--color-primary']).toBe(DEFAULT_ACCENT);
});
it('keeps button text readable for light and dark custom colors', () => {
expect(accentTokens('#ffffff')['--color-on-primary']).toBe('#000000');
expect(accentTokens('#000000')['--color-on-primary']).toBe('#ffffff');
expect(accentTokens('#8b5cf6')['--color-primary-12']).toBe('rgba(139, 92, 246, 0.12)');
});
it('restores guest colors from a cookie and scopes persistence to the site', () => {
const doc = { cookie: 'other=value; tsmb_accent=#8b5cf6' };
vi.stubGlobal('document', doc);
vi.stubGlobal('location', { protocol: 'https:' });
expect(readGuestAccent()).toBe('#8b5cf6');
saveGuestAccent('#0891b2');
expect(doc.cookie).toBe('tsmb_accent=#0891b2; Path=/; Max-Age=31536000; SameSite=Lax; Secure');
doc.cookie = 'tsmb_accent=invalid';
expect(readGuestAccent()).toBe(DEFAULT_ACCENT);
});
});
+51
View File
@@ -0,0 +1,51 @@
export const DEFAULT_ACCENT = '#335eea';
export const ACCENT_COOKIE = 'tsmb_accent';
export function readGuestAccent(): string {
const value = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith(`${ACCENT_COOKIE}=`));
return normalizeAccent(value?.slice(ACCENT_COOKIE.length + 1) ?? '') ?? DEFAULT_ACCENT;
}
export function saveGuestAccent(color: string): void {
const secure = location.protocol === 'https:' ? '; Secure' : '';
document.cookie = `${ACCENT_COOKIE}=${color}; Path=/; Max-Age=31536000; SameSite=Lax${secure}`;
}
export const ACCENT_PRESETS = [
{ name: '经典蓝', color: DEFAULT_ACCENT },
{ name: '紫罗兰', color: '#8b5cf6' },
{ name: '玫瑰粉', color: '#e8447a' },
{ name: '珊瑚橙', color: '#ea580c' },
{ name: '翡翠绿', color: '#16a34a' },
{ name: '湖水青', color: '#0891b2' },
] as const;
export function normalizeAccent(value: string): string | null {
const hex = value.trim().toLowerCase();
if (/^#[0-9a-f]{6}$/.test(hex)) return hex;
if (/^#[0-9a-f]{3}$/.test(hex)) return '#' + [...hex.slice(1)].map((c) => c + c).join('');
return null;
}
export function accentTokens(value: string): Record<string, string> {
const color = normalizeAccent(value) ?? DEFAULT_ACCENT;
const rgb = [1, 3, 5].map((offset) => parseInt(color.slice(offset, offset + 2), 16));
const linear = rgb.map((channel) => {
const srgb = channel / 255;
return srgb <= 0.04045 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4;
});
const luminance = linear[0] * 0.2126 + linear[1] * 0.7152 + linear[2] * 0.0722;
const onAccent = luminance > 0.179 ? '#000000' : '#ffffff';
const tint = (amount: number) => '#' + rgb.map((channel) =>
Math.round(channel + (255 - channel) * amount).toString(16).padStart(2, '0'),
).join('');
return {
'--color-primary': color,
'--color-on-primary': onAccent,
'--color-primary-bg': tint(0.9),
'--color-primary-10': `rgba(${rgb.join(', ')}, 0.10)`,
'--color-primary-12': `rgba(${rgb.join(', ')}, 0.12)`,
'--color-primary-15': `rgba(${rgb.join(', ')}, 0.15)`,
'--gradient-fm': `linear-gradient(135deg, ${color}, ${color === DEFAULT_ACCENT ? '#6366f1' : tint(0.2)})`,
};
}
+34
View File
@@ -0,0 +1,34 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { observeSystemTheme, readThemePreference, resolveTheme } from './theme.js';
afterEach(() => vi.unstubAllGlobals());
describe('theme preferences', () => {
it('defaults to system and preserves existing explicit choices', () => {
for (const [saved, expected] of [[null, 'system'], ['invalid', 'system'], ['system', 'system'], ['dark', 'dark'], ['light', 'light']]) {
vi.stubGlobal('localStorage', { getItem: () => saved });
expect(readThemePreference()).toBe(expected);
}
vi.stubGlobal('localStorage', { getItem: () => { throw new Error('blocked'); } });
expect(readThemePreference()).toBe('system');
});
it('follows the browser preference while keeping manual overrides', () => {
expect(resolveTheme('system', true)).toBe('dark');
expect(resolveTheme('system', false)).toBe('light');
expect(resolveTheme('light', true)).toBe('light');
expect(resolveTheme('dark', false)).toBe('dark');
});
it('receives live system changes and removes its listener on cleanup', () => {
const media = new EventTarget();
const matchMedia = vi.fn(() => media);
vi.stubGlobal('window', { matchMedia });
const onChange = vi.fn();
const stop = observeSystemTheme(onChange);
expect(matchMedia).toHaveBeenCalledWith('(prefers-color-scheme: dark)');
media.dispatchEvent(Object.assign(new Event('change'), { matches: true }));
media.dispatchEvent(Object.assign(new Event('change'), { matches: false }));
expect(onChange.mock.calls).toEqual([[true], [false]]);
stop();
media.dispatchEvent(Object.assign(new Event('change'), { matches: true }));
expect(onChange).toHaveBeenCalledTimes(2);
});
});
+28
View File
@@ -0,0 +1,28 @@
export type Theme = 'dark' | 'light';
export type ThemePreference = Theme | 'system';
export function readThemePreference(): ThemePreference {
try {
const saved = localStorage.getItem('theme');
return saved === 'dark' || saved === 'light' ? saved : 'system';
} catch {
return 'system';
}
}
export function resolveTheme(preference: ThemePreference, systemDark = window.matchMedia('(prefers-color-scheme: dark)').matches): Theme {
return preference === 'system' ? (systemDark ? 'dark' : 'light') : preference;
}
export function applyDocumentTheme(theme: Theme) {
document.documentElement.dataset.theme = theme;
document.documentElement.style.colorScheme = theme;
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', theme === 'dark' ? '#222222' : '#ffffff');
}
export function observeSystemTheme(onChange: (dark: boolean) => void) {
const media = window.matchMedia('(prefers-color-scheme: dark)');
const listener = (event: MediaQueryListEvent) => onChange(event.matches);
media.addEventListener('change', listener);
return () => media.removeEventListener('change', listener);
}
+1
View File
@@ -59,6 +59,7 @@
// Accent // Accent
--color-primary: #335eea; --color-primary: #335eea;
--color-on-primary: #ffffff;
--color-primary-bg: #eaeffd; --color-primary-bg: #eaeffd;
--color-primary-15: rgba(51, 94, 234, 0.15); --color-primary-15: rgba(51, 94, 234, 0.15);
--color-primary-10: rgba(51, 94, 234, 0.10); --color-primary-10: rgba(51, 94, 234, 0.10);
+1 -1
View File
@@ -322,7 +322,7 @@ watch(() => `${route.params.id}|${route.query.platform ?? ''}`, loadArtist);
.play-all-btn { .play-all-btn {
background: var(--color-primary); background: var(--color-primary);
color: white; color: var(--color-on-primary);
&:not(:disabled):hover { transform: scale(1.04); } &:not(:disabled):hover { transform: scale(1.04); }
&:not(:disabled):active { transform: scale(0.96); } &:not(:disabled):active { transform: scale(0.96); }
} }
+1 -1
View File
@@ -68,7 +68,7 @@ async function submit() {
} }
.auth-card button { .auth-card button {
height: 38px; border-radius: var(--radius-sm); border: 0; height: 38px; border-radius: var(--radius-sm); border: 0;
background: var(--color-primary); color: #fff; font-weight: 500; cursor: pointer; background: var(--color-primary); color: var(--color-on-primary); font-weight: 500; cursor: pointer;
} }
.auth-card button:disabled { opacity: 0.6; cursor: progress; } .auth-card button:disabled { opacity: 0.6; cursor: progress; }
.auth-error { color: #e26a6a; font-size: 13px; margin: 0; } .auth-error { color: #e26a6a; font-size: 13px; margin: 0; }
+1 -1
View File
@@ -455,7 +455,7 @@ onMounted(() => {
width: 56px; width: 56px;
height: 56px; height: 56px;
border-radius: var(--radius-md); border-radius: var(--radius-md);
background: linear-gradient(135deg, var(--color-primary), #6366f1); background: var(--gradient-fm);
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
+1 -1
View File
@@ -96,7 +96,7 @@ async function enterAsGuest() {
} }
.auth-card button { .auth-card button {
height: 38px; border-radius: var(--radius-sm); border: 0; height: 38px; border-radius: var(--radius-sm); border: 0;
background: var(--color-primary); color: #fff; font-weight: 500; cursor: pointer; background: var(--color-primary); color: var(--color-on-primary); font-weight: 500; cursor: pointer;
} }
.auth-card button:disabled { opacity: 0.6; cursor: progress; } .auth-card button:disabled { opacity: 0.6; cursor: progress; }
.auth-error { color: #e26a6a; font-size: 13px; margin: 0; } .auth-error { color: #e26a6a; font-size: 13px; margin: 0; }
+1 -1
View File
@@ -227,7 +227,7 @@ async function toggleFavorite() {
gap: 6px; gap: 6px;
padding: 10px 28px; padding: 10px 28px;
background: var(--color-primary); background: var(--color-primary);
color: white; color: var(--color-on-primary);
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
font-size: 14px; font-size: 14px;
font-weight: 600; font-weight: 600;
+2 -2
View File
@@ -209,7 +209,7 @@ onMounted(async () => {
font-weight: 600; font-weight: 600;
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
background: var(--color-primary); background: var(--color-primary);
color: #fff; color: var(--color-on-primary);
border: 1px solid var(--color-primary); border: 1px solid var(--color-primary);
cursor: pointer; cursor: pointer;
transition: filter var(--transition-fast); transition: filter var(--transition-fast);
@@ -282,7 +282,7 @@ onMounted(async () => {
transition: all var(--transition-fast); transition: all var(--transition-fast);
&:hover:not(:disabled) { background: var(--bg-secondary); border-color: var(--color-primary); } &:hover:not(:disabled) { background: var(--bg-secondary); border-color: var(--color-primary); }
&:disabled { opacity: 0.5; cursor: not-allowed; } &:disabled { opacity: 0.5; cursor: not-allowed; }
&.primary { background: var(--color-primary); border-color: var(--color-primary); color: #fff; } &.primary { background: var(--color-primary); border-color: var(--color-primary); color: var(--color-on-primary); }
&.danger { color: #ef4444; } &.danger { color: #ef4444; }
} }
+4 -4
View File
@@ -734,7 +734,7 @@ onMounted(async () => {
padding: 8px 14px; padding: 8px 14px;
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
background: var(--color-primary); background: var(--color-primary);
color: #fff; color: var(--color-on-primary);
font-size: 13px; font-size: 13px;
font-weight: var(--fw-semi); font-weight: var(--fw-semi);
cursor: pointer; cursor: pointer;
@@ -1017,7 +1017,7 @@ onMounted(async () => {
&.active { &.active {
color: var(--color-primary); color: var(--color-primary);
background: rgba(51, 94, 234, 0.12); background: var(--color-primary-12);
} }
} }
@@ -1047,7 +1047,7 @@ onMounted(async () => {
&.active { &.active {
background: var(--color-primary); background: var(--color-primary);
color: #fff; color: var(--color-on-primary);
.tab-count { opacity: 0.85; } .tab-count { opacity: 0.85; }
} }
} }
@@ -1088,7 +1088,7 @@ onMounted(async () => {
&:hover:not(:disabled) { &:hover:not(:disabled) {
color: var(--color-primary); color: var(--color-primary);
background: rgba(51, 94, 234, 0.12); background: var(--color-primary-12);
} }
&:disabled { &:disabled {
+414 -62
View File
@@ -4,25 +4,93 @@
<Icon icon="mdi:arrow-left" /> <Icon icon="mdi:arrow-left" />
返回 返回
</button> </button>
<h1 class="page-title">设置</h1> <header class="settings-header">
<div class="settings-eyebrow">偏好与管理</div>
<h1 class="page-title">设置</h1>
<p class="settings-intro">从个人偏好到机器人管理,在这里找到你需要的设置。</p>
</header>
<div class="settings-layout">
<aside class="settings-sidebar">
<div class="settings-nav-label">设置分类</div>
<nav class="settings-nav" aria-label="设置分类">
<button
v-for="category in visibleCategories"
:key="category.id"
type="button"
class="settings-nav-item"
:class="{ active: activeCategory === category.id }"
:aria-current="activeCategory === category.id ? 'page' : undefined"
aria-controls="settings-content"
@click="selectCategory(category.id)"
>
<Icon :icon="category.icon" class="settings-nav-icon" aria-hidden="true" />
<span class="settings-nav-copy">
<span class="settings-nav-title">{{ category.title }}</span>
<span class="settings-nav-description">{{ category.summary }}</span>
</span>
<Icon icon="mdi:chevron-right" class="settings-nav-arrow" aria-hidden="true" />
</button>
</nav>
</aside>
<div id="settings-content" class="settings-content" aria-labelledby="category-title">
<header ref="categoryHeader" class="category-header" tabindex="-1">
<span class="category-icon"><Icon :icon="currentCategory.icon" aria-hidden="true" /></span>
<div>
<h2 id="category-title">{{ currentCategory.title }}</h2>
<p>{{ currentCategory.description }}</p>
</div>
</header>
<!-- Theme Toggle --> <!-- Theme Toggle -->
<section class="settings-section"> <section class="settings-section" v-show="activeCategory === 'appearance'">
<h2 class="section-title">外观</h2> <h2 class="section-title">外观</h2>
<div class="setting-row"> <div class="setting-row">
<div class="setting-label"> <div class="setting-label">
<Icon icon="mdi:theme-light-dark" class="setting-icon" /> <Icon icon="mdi:theme-light-dark" class="setting-icon" />
主题模式 主题模式
</div> </div>
<button class="theme-toggle" @click="store.toggleTheme()"> <div class="theme-options" role="group" aria-label="主题模式">
<Icon :icon="store.theme === 'dark' ? 'mdi:weather-night' : 'mdi:weather-sunny'" /> <button class="theme-toggle" :aria-pressed="store.themePreference === 'system'" @click="store.setThemePreference('system')"><Icon icon="mdi:monitor" />跟随系统</button>
{{ store.theme === 'dark' ? '深色' : '浅色' }} <button class="theme-toggle" :aria-pressed="store.themePreference === 'dark'" @click="store.setThemePreference('dark')"><Icon icon="mdi:weather-night" />深色</button>
</button> <button class="theme-toggle" :aria-pressed="store.themePreference === 'light'" @click="store.setThemePreference('light')"><Icon icon="mdi:weather-sunny" />浅色</button>
</div>
</div>
<div class="accent-setting">
<h3 class="accent-title"><Icon icon="mdi:palette-outline" aria-hidden="true" />主题色</h3>
<p class="accent-hint">选择按钮、选中状态和进度条的强调色,支持预设颜色或自定义色值。</p>
<div class="accent-presets" role="group" aria-label="预设主题色">
<button
v-for="preset in ACCENT_PRESETS"
:key="preset.color"
type="button"
class="accent-preset"
:class="{ selected: store.accentColor === preset.color }"
:aria-pressed="store.accentColor === preset.color"
:aria-label="preset.name"
@click="chooseAccent(preset.color)"
>
<span class="accent-swatch" :style="{ background: preset.color, color: accentTokens(preset.color)['--color-on-primary'] }">
<Icon v-if="store.accentColor === preset.color" icon="mdi:check" aria-hidden="true" />
</span>
<span>{{ preset.name }}</span>
</button>
</div>
<div class="accent-custom">
<AccentColorPicker :model-value="store.accentColor" @update:model-value="chooseAccent" />
<button type="button" class="accent-reset" @click="chooseAccent(DEFAULT_ACCENT)">恢复默认</button>
</div>
<div class="accent-save-row">
<button type="button" class="btn-primary" :disabled="accentSaving || !accentDirty" @click="saveAccent">{{ accentSaving ? '保存中…' : '保存' }}</button>
<span>{{ accentDirty ? '有未保存的修改' : '已保存' }}</span>
</div>
<p v-if="accentSaveError" class="accent-feedback invalid" aria-live="polite">{{ accentSaveError }}</p>
</div> </div>
</section> </section>
<!-- Account: own password change --> <!-- Account: own password change -->
<section class="settings-section"> <section v-if="!session.isGuest.value" class="settings-section" v-show="activeCategory === 'account'">
<h2 class="section-title">账户</h2> <h2 class="section-title">账户</h2>
<div class="account-info-card"> <div class="account-info-card">
<div class="account-row"> <div class="account-row">
@@ -52,7 +120,7 @@
</section> </section>
<!-- Bot Management (create/edit/delete/start-stop) requires bot.manage --> <!-- Bot Management (create/edit/delete/start-stop) requires bot.manage -->
<section v-if="can('bot.manage')" class="settings-section"> <section v-if="can('bot.manage')" class="settings-section" v-show="activeCategory === 'bots'">
<h2 class="section-title">机器人管理</h2> <h2 class="section-title">机器人管理</h2>
<div class="bot-list"> <div class="bot-list">
<div v-for="bot in store.bots" :key="bot.id" class="bot-item"> <div v-for="bot in store.bots" :key="bot.id" class="bot-item">
@@ -128,41 +196,59 @@
<!-- Create Bot --> <!-- Create Bot -->
<div class="create-bot"> <div class="create-bot">
<h3 class="subsection-title">创建新实例</h3> <h3 class="subsection-title">创建新实例</h3>
<div class="form-group"> <div class="create-instance-layout">
<label>名称</label> <aside class="create-instance-avatar">
<input v-model="newBotName" class="input" placeholder="我的音乐机器人" /> <div class="create-avatar-title">自定义头像 <span>可选</span></div>
</div> <AvatarUpload v-model="newBotAvatar" />
<div class="form-row"> </aside>
<div class="form-group" style="flex:2"> <div class="create-instance-fields">
<label>服务器地址</label> <div class="create-field-section">
<input v-model="newBotServer" class="input" placeholder="localhost 或 ts.example.com" /> <h4>基本信息</h4>
</div> <div class="create-field-grid">
<div class="form-group" style="flex:1"> <div class="form-group">
<label>端口</label> <label for="new-bot-name">名称</label>
<input v-model.number="newBotPort" type="number" class="input" placeholder="9987" /> <input id="new-bot-name" v-model="newBotName" class="input" placeholder="我的音乐机器人" />
</div>
<div class="form-group">
<label for="new-bot-nickname">昵称</label>
<input id="new-bot-nickname" v-model="newBotNickname" class="input" placeholder="MusicBot" />
</div>
</div>
</div>
<div class="create-field-section">
<h4>服务器连接</h4>
<div class="create-field-grid create-server-grid">
<div class="form-group">
<label for="new-bot-server">服务器地址</label>
<input id="new-bot-server" v-model="newBotServer" class="input" placeholder="localhost 或 ts.example.com" />
</div>
<div class="form-group">
<label for="new-bot-port">端口</label>
<input id="new-bot-port" v-model.number="newBotPort" type="number" class="input" placeholder="9987" />
</div>
<div class="form-group create-field-wide">
<label for="new-bot-password">服务器密码(可选)</label>
<input id="new-bot-password" v-model="newBotServerPassword" class="input" type="password" placeholder="服务器有密码时填写" />
</div>
</div>
</div>
<div class="create-field-section">
<h4>默认频道</h4>
<div class="create-field-grid">
<div class="form-group">
<label for="new-bot-channel">频道名称(可选)</label>
<input id="new-bot-channel" v-model="newBotChannel" :disabled="!!newBotChannelId" class="input" :class="{ disabled: !!newBotChannelId }" placeholder="音乐频道" />
</div>
<div class="form-group">
<label for="new-bot-channel-id">频道 ID(可选)</label>
<input id="new-bot-channel-id" v-model="newBotChannelId" :disabled="!!newBotChannel" class="input" :class="{ disabled: !!newBotChannel }" placeholder="如 12" />
</div>
</div>
<p class="create-field-hint">频道名称与 ID 任选其一填写。</p>
</div>
<div class="create-instance-actions"><button class="btn-primary" @click="createBot">创建</button></div>
</div> </div>
</div> </div>
<div class="form-group">
<label>昵称</label>
<input v-model="newBotNickname" class="input" placeholder="MusicBot" />
</div>
<div class="form-group">
<label>默认频道名称(可选)</label>
<input v-model="newBotChannel" :disabled="!!newBotChannelId" class="input" :class="{ disabled: !!newBotChannelId }" placeholder="音乐频道" />
</div>
<div class="form-group">
<label>默认频道ID(可选)</label>
<input v-model="newBotChannelId" :disabled="!!newBotChannel" class="input" :class="{ disabled: !!newBotChannel }" placeholder="如 12" />
</div>
<div class="form-group">
<label>服务器密码(可选)</label>
<input v-model="newBotServerPassword" class="input" type="password" placeholder="服务器有密码时填写" />
</div>
<div class="form-group">
<label>自定义头像(可选)</label>
<AvatarUpload v-model="newBotAvatar" />
</div>
<button class="btn-primary" @click="createBot">创建</button>
</div> </div>
</section> </section>
@@ -171,7 +257,7 @@
visible even while the source is disabled: the enable toggle below is visible even while the source is disabled: the enable toggle below is
the only UI that flips its enabledProviders membership, so hiding the the only UI that flips its enabledProviders membership, so hiding the
card would leave no way to turn Jellyfin on. --> card would leave no way to turn Jellyfin on. -->
<section v-if="can('platform.auth')" class="settings-section"> <section v-if="can('platform.auth')" class="settings-section" v-show="activeCategory === 'music'">
<h2 class="section-title">Jellyfin 音乐库(可选)</h2> <h2 class="section-title">Jellyfin 音乐库(可选)</h2>
<div class="account-card"> <div class="account-card">
@@ -273,7 +359,7 @@
<!-- Music Account - QR Code Login (platform auth) requires platform.auth. <!-- Music Account - QR Code Login (platform auth) requires platform.auth.
Cards for sources disabled via enabledProviders are hidden. --> Cards for sources disabled via enabledProviders are hidden. -->
<section v-if="can('platform.auth') && (providerOn('netease') || providerOn('qq') || providerOn('bilibili') || providerOn('kugou'))" class="settings-section"> <section v-if="can('platform.auth') && (providerOn('netease') || providerOn('qq') || providerOn('bilibili') || providerOn('kugou'))" class="settings-section" v-show="activeCategory === 'music'">
<h2 class="section-title">音乐账号</h2> <h2 class="section-title">音乐账号</h2>
<!-- NetEase --> <!-- NetEase -->
@@ -559,7 +645,7 @@
<!-- Default music source (issue #126): the source used by chat commands <!-- Default music source (issue #126): the source used by chat commands
(!play/!add …) and the WebUI when no platform flag is given. Saving is a (!play/!add …) and the WebUI when no platform flag is given. Saving is a
global bot setting, so gate on bot.manage like the other behavior rows. --> global bot setting, so gate on bot.manage like the other behavior rows. -->
<section v-if="can('bot.manage')" class="settings-section"> <section v-if="can('bot.manage')" class="settings-section" v-show="activeCategory === 'playback'">
<h2 class="section-title">默认音源</h2> <h2 class="section-title">默认音源</h2>
<p class="profile-section-hint"> <p class="profile-section-hint">
设置不带音源参数时(如聊天里的 <code>!play 歌名</code> 或网页搜索)默认使用的音源。 设置不带音源参数时(如聊天里的 <code>!play 歌名</code> 或网页搜索)默认使用的音源。
@@ -587,7 +673,7 @@
</section> </section>
<!-- Spotify (Connect) playback via librespot — requires platform.auth --> <!-- Spotify (Connect) playback via librespot — requires platform.auth -->
<section v-if="can('platform.auth')" class="settings-section"> <section v-if="can('platform.auth')" class="settings-section" v-show="activeCategory === 'music'">
<h2 class="section-title">Spotify 播放(实验性)</h2> <h2 class="section-title">Spotify 播放(实验性)</h2>
<p class="spotify-disclaimer">{{ SPOTIFY_DISCLAIMER }}</p> <p class="spotify-disclaimer">{{ SPOTIFY_DISCLAIMER }}</p>
@@ -687,7 +773,7 @@
</section> </section>
<!-- Audio Quality requires quality --> <!-- Audio Quality requires quality -->
<section v-if="can('quality')" class="settings-section"> <section v-if="can('quality')" class="settings-section" v-show="activeCategory === 'playback'">
<h2 class="section-title">音质设置</h2> <h2 class="section-title">音质设置</h2>
<div v-if="providerOn('jellyfin')" class="setting-row"> <div v-if="providerOn('jellyfin')" class="setting-row">
<div class="setting-label"> <div class="setting-label">
@@ -728,7 +814,7 @@
</section> </section>
<!-- Command Prefix --> <!-- Command Prefix -->
<section class="settings-section"> <section v-if="!session.isGuest.value" class="settings-section" v-show="activeCategory === 'commands'">
<h2 class="section-title">命令设置</h2> <h2 class="section-title">命令设置</h2>
<div class="setting-row"> <div class="setting-row">
<div class="setting-label"> <div class="setting-label">
@@ -743,7 +829,7 @@
</section> </section>
<!-- Idle Timeout --> <!-- Idle Timeout -->
<section v-if="can('bot.manage')" class="settings-section"> <section v-if="can('bot.manage')" class="settings-section" v-show="activeCategory === 'playback'">
<h2 class="section-title">行为设置</h2> <h2 class="section-title">行为设置</h2>
<div class="setting-row"> <div class="setting-row">
<div class="setting-label"> <div class="setting-label">
@@ -884,9 +970,9 @@
</section> </section>
<!-- Guest Mode (admin only) --> <!-- Guest Mode (admin only) -->
<section v-if="session.isAdmin.value" class="settings-section"> <section v-if="session.isAdmin.value" class="settings-section" v-show="activeCategory === 'access'">
<h2 class="section-title">游客模式</h2> <h2 class="section-title">游客模式</h2>
<p class="profile-section-hint">开启后,访客无需登录即可进入并点歌(默认关闭)。游客永远无法查看或修改设置。下面逐项决定游客可用的能力。</p> <p class="profile-section-hint">开启后,访客无需登录即可进入并点歌(默认关闭)。游客仅可调整个人外观,无法查看或修改管理设置。下面逐项决定游客可用的能力。</p>
<label class="profile-toggle behavior-toggle"> <label class="profile-toggle behavior-toggle">
<div class="profile-toggle-text"> <div class="profile-toggle-text">
@@ -933,7 +1019,7 @@
</section> </section>
<!-- Command Permissions (admin only) --> <!-- Command Permissions (admin only) -->
<section v-if="session.isAdmin.value" class="settings-section"> <section v-if="session.isAdmin.value" class="settings-section" v-show="activeCategory === 'commands'">
<h2 class="section-title">命令权限</h2> <h2 class="section-title">命令权限</h2>
<p class="profile-section-hint"> <p class="profile-section-hint">
限制谁能在 TeamSpeak 聊天里运行管理类命令(stop / clear / remove / move / vol / mode)。 限制谁能在 TeamSpeak 聊天里运行管理类命令(stop / clear / remove / move / vol / mode)。
@@ -950,7 +1036,7 @@
</section> </section>
<!-- Bot Profile (TeamSpeak Behavior) --> <!-- Bot Profile (TeamSpeak Behavior) -->
<section v-if="can('bot.manage')" class="settings-section"> <section v-if="can('bot.manage')" class="settings-section" v-show="activeCategory === 'bots'">
<h2 class="section-title">机器人 Profile(TeamSpeak 行为)</h2> <h2 class="section-title">机器人 Profile(TeamSpeak 行为)</h2>
<p class="profile-section-hint">控制 bot 在 TeamSpeak 上自动同步歌曲信息的方式。⚠️ 标记的项会触发频道里所有人的提示音。</p> <p class="profile-section-hint">控制 bot 在 TeamSpeak 上自动同步歌曲信息的方式。⚠️ 标记的项会触发频道里所有人的提示音。</p>
<div v-if="store.bots.length === 0" class="empty-hint">还没有机器人,先在上面创建一个。</div> <div v-if="store.bots.length === 0" class="empty-hint">还没有机器人,先在上面创建一个。</div>
@@ -1003,7 +1089,7 @@
</section> </section>
<!-- User Management --> <!-- User Management -->
<section v-if="session.isAdmin.value" class="settings-section"> <section v-if="session.isAdmin.value" class="settings-section" v-show="activeCategory === 'access'">
<h2 class="section-title">用户管理</h2> <h2 class="section-title">用户管理</h2>
<div class="user-list"> <div class="user-list">
<div v-for="u in userList" :key="u.id" class="user-row-wrap"> <div v-for="u in userList" :key="u.id" class="user-row-wrap">
@@ -1136,7 +1222,7 @@
</section> </section>
<!-- API Keys --> <!-- API Keys -->
<section class="settings-section"> <section v-if="!session.isGuest.value" class="settings-section" v-show="activeCategory === 'account'">
<h2 class="section-title">API 密钥</h2> <h2 class="section-title">API 密钥</h2>
<p class="apikey-hint"> <p class="apikey-hint">
通过 API Key 调用本机的 REST API(请求头 <code>Authorization: Bearer</code> 或 <code>X-API-Key</code>)。 通过 API Key 调用本机的 REST API(请求头 <code>Authorization: Bearer</code> 或 <code>X-API-Key</code>)。
@@ -1190,7 +1276,7 @@
</section> </section>
<!-- Audit Log --> <!-- Audit Log -->
<section v-if="session.isAdmin.value" class="settings-section"> <section v-if="session.isAdmin.value" class="settings-section" v-show="activeCategory === 'audit'">
<h2 class="section-title"> <h2 class="section-title">
操作审计 操作审计
<button class="audit-refresh-btn" @click="loadAudit" :disabled="auditLoading" title="刷新"> <button class="audit-refresh-btn" @click="loadAudit" :disabled="auditLoading" title="刷新">
@@ -1207,19 +1293,23 @@
</div> </div>
</div> </div>
</section> </section>
</div>
</div>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'; import { ref, reactive, computed, watch, nextTick, onMounted, onUnmounted } from 'vue';
import { Icon } from '@iconify/vue'; import { Icon } from '@iconify/vue';
import axios from 'axios'; import axios from 'axios';
import AvatarUpload from '../components/AvatarUpload.vue'; import AvatarUpload from '../components/AvatarUpload.vue';
import CustomAvatarRow from '../components/CustomAvatarRow.vue'; import CustomAvatarRow from '../components/CustomAvatarRow.vue';
import AccentColorPicker from '../components/AccentColorPicker.vue';
import PersonalNeteaseAccount from '../components/PersonalNeteaseAccount.vue'; import PersonalNeteaseAccount from '../components/PersonalNeteaseAccount.vue';
import QRCode from 'qrcode'; import QRCode from 'qrcode';
import { usePlayerStore } from '../stores/player.js'; import { usePlayerStore } from '../stores/player.js';
import { useSession } from '../composables/useSession.js'; import { useSession } from '../composables/useSession.js';
import { ACCENT_PRESETS, DEFAULT_ACCENT, accentTokens, readGuestAccent } from '../styles/accent.js';
import { import {
buildSpotifyPayload, buildSpotifyPayload,
parseSpotifyRedirect, parseSpotifyRedirect,
@@ -1230,6 +1320,10 @@ import {
} from '../composables/useSpotifySettings.js'; } from '../composables/useSpotifySettings.js';
const store = usePlayerStore(); const store = usePlayerStore();
function chooseAccent(color: string) {
store.setAccentColor(color);
accentSaveError.value = '';
}
function botStatusClass(bot: any) { function botStatusClass(bot: any) {
if (!bot.connected) return 'offline'; if (!bot.connected) return 'offline';
@@ -2089,6 +2183,62 @@ async function updateProfile(botId: string, key: keyof ProfileConfig, value: boo
// --- User Management --- // --- User Management ---
const session = useSession(); const session = useSession();
const { can } = session; const { can } = session;
const accentSaving = ref(false);
const accentSaveError = ref('');
const guestSavedAccent = ref(readGuestAccent());
const accentDirty = computed(() => store.accentColor !==
(session.isGuest.value ? guestSavedAccent.value : session.currentUser.value?.accentColor ?? DEFAULT_ACCENT));
async function saveAccent() {
if (accentSaving.value) return;
const color = store.accentColor;
chooseAccent(color);
accentSaving.value = true;
accentSaveError.value = '';
try {
if (session.isGuest.value) {
store.saveGuestAccentColor();
guestSavedAccent.value = color;
} else {
await session.saveAccentColor(color);
}
} catch (error) {
accentSaveError.value = (error as Error).message;
} finally {
accentSaving.value = false;
}
}
// Navigation mirrors section permissions; hidden sections keep their form state.
const settingsCategories = [
{ id: 'bots', title: '机器人', summary: '实例与 TeamSpeak 配置', icon: 'mdi:robot-outline', description: '创建和管理机器人实例,配置服务器连接与 TeamSpeak 展示行为。' },
{ id: 'music', title: '音乐平台', summary: '平台登录与音乐库连接', icon: 'mdi:music-box-multiple-outline', description: '登录音乐平台,连接 Jellyfin 音乐库,或配置 Spotify 播放。' },
{ id: 'playback', title: '播放与音质', summary: '音源、音质与播放行为', icon: 'mdi:tune-variant', description: '设置默认音乐来源、播放音质,以及闲置退出和语音压低等行为。' },
{ id: 'commands', title: '聊天命令', summary: '命令前缀与使用权限', icon: 'mdi:console-line', description: '设置 TeamSpeak 聊天命令的触发前缀,以及命令使用权限。' },
{ id: 'access', title: '用户与权限', summary: '成员管理与游客访问', icon: 'mdi:shield-account-outline', description: '管理成员账户和权限,设置游客可以访问和操作的功能。' },
{ id: 'account', title: '个人账户', summary: '信息、密码与 API 密钥', icon: 'mdi:account-circle-outline', description: '查看账户信息、修改密码,以及管理个人音乐账号和 API 密钥。' },
{ id: 'appearance', title: '外观', summary: '主题模式与自定义强调色', icon: 'mdi:palette-outline', description: '选择适合你的主题模式和强调色,让日常使用更舒适。' },
{ id: 'audit', title: '操作审计', summary: '操作记录与变更追踪', icon: 'mdi:clipboard-text-clock-outline', description: '查看账户与管理操作记录,了解谁在什么时间进行了变更。' },
] as const;
type SettingsCategoryId = typeof settingsCategories[number]['id'];
const categoryHeader = ref<HTMLElement | null>(null);
const visibleCategories = computed(() => settingsCategories.filter((category) => {
if (session.isGuest.value) return category.id === 'appearance';
if (category.id === 'bots') return can('bot.manage');
if (category.id === 'music') return can('platform.auth');
if (category.id === 'playback') return can('bot.manage') || can('quality');
if (category.id === 'access' || category.id === 'audit') return session.isAdmin.value;
return true;
}));
const activeCategory = ref<SettingsCategoryId>(visibleCategories.value[0]!.id);
const currentCategory = computed(() => visibleCategories.value.find((category) => category.id === activeCategory.value) ?? visibleCategories.value[0]!);
watch(visibleCategories, (categories) => {
if (!categories.some((category) => category.id === activeCategory.value)) activeCategory.value = categories[0]!.id;
});
async function selectCategory(id: SettingsCategoryId) {
activeCategory.value = id;
await nextTick();
categoryHeader.value?.focus({ preventScroll: true });
}
// --- Own password change (available to all authenticated users) --- // --- Own password change (available to all authenticated users) ---
const ownPw = reactive({ old: '', new: '', confirm: '' }); const ownPw = reactive({ old: '', new: '', confirm: '' });
@@ -2487,6 +2637,7 @@ function auditActionClass(action: string): string {
} }
onMounted(() => { onMounted(() => {
if (session.isGuest.value) return;
store.fetchBots(); // Refresh bot status on page visit store.fetchBots(); // Refresh bot status on page visit
checkAuthStatus(); checkAuthStatus();
loadQuality(); loadQuality();
@@ -2509,6 +2660,157 @@ onUnmounted(() => {
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.accent-setting { margin-top: 24px; padding-top: 24px; border-top: 1px solid var(--border-color); }
.accent-title { display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 600; }
.accent-title svg { font-size: 18px; color: var(--text-secondary); }
.accent-hint { margin: 8px 0 16px; font-size: 12px; line-height: 1.6; color: var(--text-secondary); }
.accent-presets { display: flex; gap: 10px; flex-wrap: wrap; }
.accent-preset {
display: flex; flex-direction: column; align-items: center; gap: 8px;
padding: 10px; min-width: 68px; border: 1px solid transparent;
border-radius: var(--radius-md); background: transparent;
color: var(--text-secondary); font-size: 12px; cursor: pointer;
&:hover { background: var(--hover-bg); }
&.selected { border-color: var(--color-primary); background: var(--color-primary-10); color: var(--text-primary); }
&:focus-visible { outline: 2px solid var(--color-primary); outline-offset: 2px; }
}
.accent-swatch { display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; font-size: 20px; border: 1px solid var(--border-color); }
.accent-custom { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; margin-top: 20px; }
.accent-reset { font-size: 12px; color: var(--text-secondary); padding: 8px 0; cursor: pointer; &:hover { color: var(--text-primary); } }
.accent-feedback { margin: 12px 0 0; font-size: 12px; color: var(--text-tertiary); &.invalid { color: #e26a6a; } }
.accent-save-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-top: 20px; font-size: 12px; color: var(--text-secondary); }
.accent-save-row button:disabled { opacity: 0.5; cursor: default; }
.settings-page {
overflow-anchor: none;
max-width: 1240px;
margin: 0 auto;
}
.settings-header { margin-bottom: 28px; }
.settings-eyebrow {
margin-bottom: 8px;
color: var(--text-tertiary);
font-size: 12px;
font-weight: 600;
letter-spacing: 1px;
}
.settings-intro {
margin: 8px 0 0;
color: var(--text-secondary);
font-size: 14px;
line-height: 1.6;
}
.settings-layout {
display: grid;
grid-template-columns: 260px minmax(0, 1fr);
gap: 32px;
align-items: start;
}
.settings-sidebar {
position: sticky;
top: calc(var(--navbar-height) + 24px);
max-height: calc(100dvh - var(--navbar-height) - var(--player-height) - 48px);
overflow-y: auto;
scrollbar-width: none;
&::-webkit-scrollbar { display: none; }
padding: 12px;
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
background: var(--bg-card);
}
.settings-nav-label {
padding: 8px 12px 12px;
font-size: 11px;
font-weight: 600;
color: var(--text-tertiary);
letter-spacing: 1px;
}
.settings-nav { display: flex; flex-direction: column; gap: 4px; }
.settings-nav-item {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
padding: 10px 12px;
border: 1px solid transparent;
border-radius: var(--radius-md);
background: transparent;
color: var(--text-secondary);
text-align: left;
cursor: pointer;
transition: background var(--transition-fast), color var(--transition-fast);
&:hover { background: var(--hover-bg); color: var(--text-primary); }
&:focus-visible { outline: 2px solid var(--color-primary); outline-offset: 2px; }
&.active {
background: var(--color-primary-10);
border-color: var(--color-primary-15);
color: var(--color-primary);
.settings-nav-description { color: var(--text-secondary); }
.settings-nav-arrow { opacity: 1; }
}
}
.settings-nav-icon { font-size: 22px; flex-shrink: 0; }
.settings-nav-copy { display: flex; flex: 1; flex-direction: column; min-width: 0; gap: 5px; }
.settings-nav-title { font-size: 14px; font-weight: 600; }
.settings-nav-description { font-size: 11px; line-height: 1.5; color: var(--text-tertiary); }
.settings-nav-arrow { font-size: 18px; opacity: 0; flex-shrink: 0; }
.settings-content { min-width: 0; }
.category-header {
display: flex;
align-items: center;
gap: 14px;
padding: 4px 0 24px;
margin-bottom: 24px;
border-bottom: 1px solid var(--border-color);
scroll-margin-top: calc(var(--navbar-height) + 24px);
outline: none;
h2 { font-size: 22px; font-weight: 700; margin: 0; }
p { margin: 6px 0 0; font-size: 13px; color: var(--text-secondary); line-height: 1.6; }
}
.category-icon {
display: grid;
place-items: center;
flex-shrink: 0;
width: 48px;
height: 48px;
font-size: 25px;
border-radius: 12px;
background: var(--color-primary-10);
color: var(--color-primary);
}
@media (max-width: 1100px) and (min-width: 769px) {
.settings-layout { grid-template-columns: 230px minmax(0, 1fr); gap: 24px; }
.settings-nav-item { gap: 8px; padding: 10px 8px; }
}
@media (max-width: 768px) {
.settings-header { margin-bottom: 20px; }
.settings-layout { grid-template-columns: minmax(0, 1fr); gap: 24px; }
.settings-sidebar { position: static; max-height: none; padding: 8px; overflow: hidden; }
.settings-nav-label { padding: 4px 8px 10px; }
.settings-nav {
flex-direction: row;
overflow-x: auto;
padding: 2px 2px 6px;
scrollbar-width: none;
&::-webkit-scrollbar { display: none; }
}
.settings-nav-item { flex: 0 0 auto; width: auto; gap: 8px; padding: 10px 12px; }
.settings-nav-title { white-space: nowrap; }
.settings-nav-description, .settings-nav-arrow { display: none; }
.settings-nav-icon { font-size: 19px; }
.category-header {
gap: 12px;
padding-bottom: 20px;
margin-bottom: 20px;
scroll-margin-top: calc(var(--navbar-height) + 136px);
}
.category-header h2 { font-size: 20px; }
}
.back-btn { .back-btn {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -2523,13 +2825,14 @@ onUnmounted(() => {
.page-title { .page-title {
font-size: 28px; font-size: 28px;
font-weight: 800; font-weight: 800;
margin-bottom: 32px; margin-bottom: 0;
} }
.settings-section { .settings-section {
margin-bottom: 36px; margin-bottom: 20px;
padding: 24px; padding: 24px;
background: var(--bg-card); background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
} }
@@ -2564,6 +2867,7 @@ onUnmounted(() => {
opacity: 0.6; opacity: 0.6;
} }
.theme-options { display: flex; flex-wrap: wrap; gap: 6px; }
.theme-toggle { .theme-toggle {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -2574,7 +2878,8 @@ onUnmounted(() => {
font-size: 13px; font-size: 13px;
font-weight: 600; font-weight: 600;
transition: all var(--transition-fast); transition: all var(--transition-fast);
&:hover { background: var(--color-primary); color: white; } &:hover { background: var(--color-primary); color: var(--color-on-primary); }
&[aria-pressed='true'] { background: var(--color-primary-15); color: var(--color-primary); box-shadow: inset 0 0 0 1px var(--color-primary); }
} }
// Bot management // Bot management
@@ -2919,7 +3224,7 @@ onUnmounted(() => {
.btn-primary { .btn-primary {
padding: 10px 20px; padding: 10px 20px;
background: var(--color-primary); background: var(--color-primary);
color: white; color: var(--color-on-primary);
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
font-size: 13px; font-size: 13px;
font-weight: 600; font-weight: 600;
@@ -2936,7 +3241,7 @@ onUnmounted(() => {
font-size: 12px; font-size: 12px;
font-weight: 600; font-weight: 600;
transition: all var(--transition-fast); transition: all var(--transition-fast);
&:hover { background: var(--color-primary); color: white; } &:hover { background: var(--color-primary); color: var(--color-on-primary); }
} }
.btn-edit { .btn-edit {
@@ -2970,6 +3275,53 @@ onUnmounted(() => {
border-top: 1px solid var(--border-color); border-top: 1px solid var(--border-color);
} }
.create-instance-layout {
display: grid;
grid-template-columns: 168px minmax(0, 1fr);
gap: 28px;
align-items: start;
}
.create-instance-avatar {
padding: 18px 12px;
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
background: var(--bg-card);
text-align: center;
.create-avatar-title { margin-bottom: 18px; font-size: 13px; font-weight: 600; }
.create-avatar-title span { margin-left: 4px; font-size: 11px; font-weight: 400; color: var(--text-tertiary); }
:deep(.avatar-upload) { align-items: center; gap: 12px; }
:deep(.preview) { width: 120px; height: 120px; border: 1px solid var(--border-color); }
:deep(.preview.empty svg) { font-size: 64px; }
:deep(.hint) { font-size: 11px; line-height: 1.6; }
}
.create-instance-fields { min-width: 0; }
.create-field-section {
margin-bottom: 22px;
h4 { margin: 0 0 12px; font-size: 13px; font-weight: 600; }
.form-group { min-width: 0; margin: 0; }
.input { width: 100%; min-width: 0; box-sizing: border-box; }
}
.create-field-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px 16px; }
.create-server-grid { grid-template-columns: minmax(0, 1fr) 100px; }
.create-field-wide { grid-column: 1 / -1; }
.create-field-hint { margin: 8px 0 0; font-size: 11px; color: var(--text-tertiary); }
.create-instance-actions { display: flex; justify-content: flex-end; padding-top: 16px; border-top: 1px solid var(--border-color); }
@media (max-width: 1100px) and (min-width: 769px) {
.create-instance-layout { grid-template-columns: 144px minmax(0, 1fr); gap: 20px; }
.create-field-grid { grid-template-columns: minmax(0, 1fr); }
.create-server-grid { grid-template-columns: minmax(0, 1fr) 90px; }
}
@media (max-width: 600px) {
.create-instance-layout { grid-template-columns: minmax(0, 1fr); gap: 22px; }
.create-instance-avatar { justify-self: start; width: 168px; box-sizing: border-box; }
.create-field-grid { grid-template-columns: minmax(0, 1fr); }
.create-server-grid { grid-template-columns: minmax(0, 1fr) 86px; gap: 12px; }
}
.form-group { .form-group {
margin-bottom: 12px; margin-bottom: 12px;
label { label {
@@ -3279,7 +3631,7 @@ onUnmounted(() => {
.user-name { font-weight: 500; color: var(--text-primary); display: flex; align-items: center; gap: 8px; } .user-name { font-weight: 500; color: var(--text-primary); display: flex; align-items: center; gap: 8px; }
.user-self-badge { .user-self-badge {
font-size: 11px; padding: 2px 6px; border-radius: 4px; font-size: 11px; padding: 2px 6px; border-radius: 4px;
background: var(--color-primary); color: #fff; background: var(--color-primary); color: var(--color-on-primary);
} }
.user-created { font-size: 12px; color: var(--text-secondary); } .user-created { font-size: 12px; color: var(--text-secondary); }
.user-actions { display: flex; gap: 8px; } .user-actions { display: flex; gap: 8px; }
+3 -3
View File
@@ -239,13 +239,13 @@ async function saveJellyfinAndNext() {
.step.active .step-dot { .step.active .step-dot {
background: var(--color-primary); background: var(--color-primary);
color: white; color: var(--color-on-primary);
opacity: 1; opacity: 1;
} }
.step.done .step-dot { .step.done .step-dot {
background: var(--color-primary); background: var(--color-primary);
color: white; color: var(--color-on-primary);
opacity: 0.7; opacity: 0.7;
} }
@@ -302,7 +302,7 @@ async function saveJellyfinAndNext() {
.btn-primary { .btn-primary {
padding: 10px 32px; padding: 10px 32px;
background: var(--color-primary); background: var(--color-primary);
color: white; color: var(--color-on-primary);
border-radius: var(--radius-md); border-radius: var(--radius-md);
font-size: 14px; font-size: 14px;
font-weight: 600; font-weight: 600;