mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-01 02:12:50 +08:00
Compare commits
52
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ec3dcc405 | ||
|
|
bd03cb1c59 | ||
|
|
5c05eae530 | ||
|
|
c72cd4f233 | ||
|
|
dc2659628e | ||
|
|
ad5568187d | ||
|
|
cb01cd3049 | ||
|
|
db3b6b2f66 | ||
|
|
d34e249f8a | ||
|
|
6546bbd830 | ||
|
|
a33fdc1aab | ||
|
|
b25cdba161 | ||
|
|
90a4d80958 | ||
|
|
a47917afb1 | ||
|
|
17b092f2e4 | ||
|
|
0360088710 | ||
|
|
ea05787cb7 | ||
|
|
84e04ee2d2 | ||
|
|
406ecda7d7 | ||
|
|
0808cde447 | ||
|
|
dd8e8c5950 | ||
|
|
2792a86a6c | ||
|
|
2b657ae338 | ||
|
|
35fa3a95df | ||
|
|
4f026aa65f | ||
|
|
568d49f837 | ||
|
|
f2a72e3162 | ||
|
|
9928035282 | ||
|
|
79e9cd797c | ||
|
|
51debb915c | ||
|
|
066f12d91f | ||
|
|
69b311283a | ||
|
|
263c1ba6da | ||
|
|
b7779ab108 | ||
|
|
97ee05f1ef | ||
|
|
91b2533176 | ||
|
|
178935a63d | ||
|
|
c3d06cb09a | ||
|
|
72e0d3a439 | ||
|
|
d2c44ed256 | ||
|
|
d8a8574323 | ||
|
|
2daae59014 | ||
|
|
4c25cfe5e5 | ||
|
|
aceccc93e1 | ||
|
|
d3eb6f2107 | ||
|
|
e9995c1e30 | ||
|
|
4ac3309e34 | ||
|
|
c2771ab9a7 | ||
|
|
1ef80be883 | ||
|
|
61c24cc219 | ||
|
|
a613d6cac0 | ||
|
|
ba645e5ccb |
No files matched your search
@@ -103,12 +103,12 @@ npm start
|
||||
|
||||
### 方式三:Docker 一键部署
|
||||
|
||||
所有依赖已内置(Node.js、FFmpeg、Opus 编码器),无需安装任何额外软件。
|
||||
需要 Docker 和 Docker Compose v2。默认从 GitHub Container Registry(GHCR)拉取预构建镜像,镜像已包含 Node.js、FFmpeg 和 Opus 编码器。
|
||||
|
||||
```bash
|
||||
git clone https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
|
||||
cd teamspeak-music-bot/scripts/docker
|
||||
docker-compose up -d
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
打开浏览器访问 **http://localhost:3000**
|
||||
@@ -116,15 +116,14 @@ docker-compose up -d
|
||||
<details>
|
||||
<summary>Docker 详细说明</summary>
|
||||
|
||||
- 首次构建需要几分钟(编译原生模块)
|
||||
- 默认使用 `host` 网络模式,机器人可直接连接局域网 TS3 服务器
|
||||
- 数据持久化在 Docker 命名卷 `tsmusicbot-data` 中(数据库、Cookie、日志)
|
||||
- 内置健康检查(`/api/health`),支持 Docker 自动重启
|
||||
|
||||
```bash
|
||||
docker logs -f tsmusicbot # 查看日志
|
||||
docker-compose down # 停止
|
||||
docker-compose up -d --build # 代码更新后重新构建
|
||||
docker compose down # 停止
|
||||
docker compose pull && docker compose up -d # 更新预构建镜像
|
||||
```
|
||||
|
||||
如果 TS3 服务器在其他机器上,编辑 `docker-compose.yml`:
|
||||
@@ -136,6 +135,36 @@ ports:
|
||||
|
||||
</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 下有两个脚本,按需二选一:
|
||||
@@ -302,11 +331,8 @@ npm start
|
||||
```bash
|
||||
cd scripts/docker
|
||||
|
||||
# 拉取最新代码
|
||||
git pull
|
||||
|
||||
# 重新构建并启动(数据自动保留)
|
||||
docker-compose up -d --build
|
||||
# 拉取预构建镜像并重新启动
|
||||
docker compose pull && docker compose up -d
|
||||
```
|
||||
|
||||
> 数据(数据库、Cookie、日志)保存在 Docker 命名卷 `tsmusicbot-data` 中,更新不会丢失。
|
||||
@@ -347,6 +373,20 @@ sudo systemctl start tsmusicbot
|
||||
4. (可选)在 **设置 → Jellyfin 音乐库** 连接自建 Jellyfin 服务器并打开「启用 Jellyfin 音源」(安装向导第 3 步保存连接时会自动启用;详见 [可选:Jellyfin 音源](#可选jellyfin-音源))
|
||||
5. 在 **设置 → 用户管理**(仅管理员可见)按需添加成员。成员默认可控制播放但无法管理其他用户;管理员还可为每个成员单独配置**能力**(播放控制 / 队列 / 机器人管理 / 平台登录 / 音质)和**可操作的机器人白名单**,未授权的机器人对该成员不可见、不可控
|
||||
|
||||
### QQ 音乐自动续期
|
||||
|
||||
QQ 音源启用时,`QQ_MUSIC_MANAGED_SESSION` 默认为 `1`。在 **设置 → 音乐账号 → QQ 音乐** 用手机 QQ 扫码授权一次后,机器人每 24 小时自动续期,遇到有效期更短的凭据会在到期前提前续期。凭据和上次成功续期时间保存在数据目录的 `cookies/qq-session.json`,重启后继续按原时间安排续期。
|
||||
|
||||
已有 `cookies/qq.json` 可继续播放,扫码授权后才会获得续期所需的凭据。手动导入 Cookie 会替换当前登录并取消该账号的自动续期。设置页会显示上次成功续期时间、下次续期时间、重试状态或重新扫码提示。具备平台登录权限的用户也可以调用 `POST /api/auth/qq/refresh` 手动尝试续期。
|
||||
|
||||
设置 `QQ_MUSIC_MANAGED_SESSION=0` 并重启可关闭自动续期。机器人继续使用当前的 QQ 播放 Cookie,并从 `cookies/qq.json` 兼容读取旧部署的 Cookie。
|
||||
|
||||
### 每用户音乐账号
|
||||
|
||||
管理员可在设置中开启「每个成员使用自己的音乐账号」,默认关闭。成员可扫码绑定自己的网易云,也可接受管理员分配的网易云、QQ 音乐、酷狗或 B 站账号。网页搜索、歌单和推荐默认优先使用自己的绑定,其次使用分配账号,最后使用机器人共享账号。成员也可在「我的音乐账号」中主动选择共享账号。房间播歌使用机器人共享账号。
|
||||
|
||||
从共享账号导入时,账号池保存当前 Cookie 的副本。共享账号续期或更换后,管理员可在账号池中更新该条目的 Cookie。
|
||||
|
||||
### WebUI 页面说明
|
||||
|
||||
| 页面 | 功能 |
|
||||
@@ -583,7 +623,7 @@ teamspeak-music-bot/
|
||||
| **后端框架** | Express 4, WebSocket (ws) |
|
||||
| **数据库** | better-sqlite3 (SQLite) |
|
||||
| **音频处理** | FFmpeg (ffmpeg-static 内置), @discordjs/opus |
|
||||
| **TS 协议** | @honeybbq/teamspeak-client(完整客户端协议)+ 自研 TS6 协议适配层 |
|
||||
| **TS 协议** | @honeybbq/teamspeak(TS3 / TS6 完整客户端协议,支持 OpenProtocol v1) |
|
||||
| **Jellyfin** | Jellyfin REST API(可选音源,直连,无额外 npm 依赖) |
|
||||
| **网易云 API** | NeteaseCloudMusicApi |
|
||||
| **QQ 音乐 API** | @sansenjian/qq-music-api(锁定 `~2.4.0`,需 Node ≥ 20.17) |
|
||||
@@ -915,7 +955,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` 升级)。
|
||||
|
||||
**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:忘记管理员密码怎么办?**
|
||||
A:直接操作 SQLite 数据库。最简单的办法是清空 `users` 表然后重新进入 first-run 流程:`sqlite3 data/tsmusicbot.db "DELETE FROM users; DELETE FROM sessions;"`,重启后浏览器会自动跳转 `/first-run` 让你重新创建管理员。详细方法见 [从 WebUI 无鉴权版本升级](#从-webui-无鉴权版本升级重要)。
|
||||
@@ -953,7 +993,24 @@ A:本项目内置 `/login` 限流(每 IP 每分钟 5 次),但生产部
|
||||
|
||||
> 完整历史请查看 [git log](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/commits/main) 或 [Releases](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/releases)。这里只列出重要变更和面向用户的破坏性改动。
|
||||
|
||||
### 最新版本 — v1.15.2:长视频续播与语音发送故障处理
|
||||
### 最新版本 — v1.16.0:播放可靠性、音乐账号与 OpenProtocol
|
||||
|
||||
- **播放恢复**:临时取流失败会按上限重试,支持的音源可尝试更低音质。`playUrlRetries` 默认为 2,可设为 0–5,设为 0 时关闭重试。切歌、停止或断线会取消旧请求。网易云返回上游限制时会提示具体类型,并停止同一来源的连续重试。网易云播放请求的 User-Agent 与登录客户端配置一致。 [#185](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/185) · [#190](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/190)
|
||||
- **B 站**:点播链接保留分 P 参数,修复部分 CDN 的 403。 [#191](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/191)
|
||||
- **音乐登录**:支持多行 `Set-Cookie` 导入及 QQ 扫码会话自动续期。启用网页个人音乐账号后,搜索、歌单和推荐可使用个人登录或管理员分配的账号;房间语音播放使用共享账号。 [#184](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/184) · [#188](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/188) · [#186](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/186)
|
||||
- **网页播放历史**:有权限的用户可按机器人单条删除、批量删除或清空历史。 [#182](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/182)
|
||||
- **TeamSpeak**:新增 OpenProtocol v1 命令发现和结构化回复,更新 TS3/TS6 客户端 SDK,补齐音频淡入淡出的回归测试。 [#194](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/194) · [#178](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/178)
|
||||
- **隐私与部署**:音乐 API 请求失败时,日志保留诊断码并省略请求和响应数据;Docker 文档新增官方镜像离线导入和按版本标签本地构建的步骤。 [#197](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/197) · [#196](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/196)
|
||||
|
||||
### v1.15.4:播放控制淡入淡出
|
||||
|
||||
- 暂停、恢复、切歌和停止时使用音量渐变,减少操作时的爆音。 [#177](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/177)
|
||||
|
||||
### v1.15.3:设置和外观偏好
|
||||
|
||||
- 重整设置页,并同步账号的界面外观偏好。 [#176](https://github.com/ZHANGTIANYAO1/teamspeak-music-bot/pull/176)
|
||||
|
||||
### v1.15.2:长视频续播与语音发送故障处理
|
||||
|
||||
- 修复播放停滞的误判:一帧音频成功发送后,即使缓冲恰好被读空,也会重置断流计数。真实断流仍保留超时检测。
|
||||
- B站 CDN 按实际域名识别,补齐 `szbdyd.com` 等回退节点的请求头和断点定位,避免续播时从头下载、解码长视频。
|
||||
@@ -1246,7 +1303,7 @@ A:本项目内置 `/login` 限流(每 IP 每分钟 5 次),但生产部
|
||||
| [NeteaseCloudMusicApi](https://github.com/Binaryify/NeteaseCloudMusicApi) | 网易云音乐 API 项目 |
|
||||
| [QQMusicApi](https://github.com/jsososo/QQMusicApi) | QQ 音乐 API 项目 |
|
||||
| [@sansenjian/qq-music-api](https://github.com/sansenjian/qq-music-api) | QQ 音乐 API 活跃维护版本 |
|
||||
| [@honeybbq/teamspeak-client](https://www.npmjs.com/package/@honeybbq/teamspeak-client) | TS3 完整客户端协议实现 |
|
||||
| [@honeybbq/teamspeak](https://www.npmjs.com/package/@honeybbq/teamspeak) | TS3 / TS6 完整客户端协议实现 |
|
||||
| [bilibili-API-collect](https://github.com/SocialSisterYi/bilibili-API-collect) | 哔哩哔哩 API 文档 |
|
||||
| [MakcRe/KuGouMusicApi](https://github.com/MakcRe/KuGouMusicApi) | 酷狗音乐 API 参考(请求签名 / KRC 歌词解码 / 设备注册移植来源,MIT 许可) |
|
||||
|
||||
|
||||
+3
-1
@@ -225,7 +225,9 @@ interface BotStatus {
|
||||
| GET | `/queue` | `{ queue: QueuedSong[], status: BotStatus }` |
|
||||
| GET | `/elapsed` | `{ elapsed: 42.5 }` |
|
||||
| DELETE | `/queue/:index` | `{ message }`(移除指定下标,能力 `player.queue`) |
|
||||
| GET | `/history?limit=50` | `{ history: [{ id, name, artist, album, coverUrl, platform, playedAt, requestedBy }] }` |
|
||||
| GET | `/history?limit=50` | `{ history: [{ rowId, id, name, artist, album, coverUrl, platform, playedAt, requestedBy }] }` |
|
||||
| DELETE | `/history/:rowId` | `{ deleted }`(删除单条记录,能力 `player.queue`) |
|
||||
| DELETE | `/history` | `{ deleted }`(请求体 `{ ids: number[] }` 批量删除 1–500 条或 `{ all: true }` 清空,能力 `player.queue`) |
|
||||
| GET | `/profile` | ProfileConfig |
|
||||
| PUT | `/profile` | ProfileConfig(能力 `bot.manage`) |
|
||||
|
||||
|
||||
Generated
+26
-15
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "tsmusicbot",
|
||||
"version": "0.1.0",
|
||||
"version": "1.16.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "tsmusicbot",
|
||||
"version": "0.1.0",
|
||||
"version": "1.16.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak-client": "^0.2.1",
|
||||
"@honeybbq/teamspeak": "^1.0.0-beta.31",
|
||||
"@koa/router": "^15.4.0",
|
||||
"@sansenjian/qq-music-api": "~2.4.0",
|
||||
"axios": "^1.14.0",
|
||||
@@ -42,6 +42,9 @@
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^6.0.2",
|
||||
"vitest": "^4.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.12.0 || >=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@derhuerst/http-basic": {
|
||||
@@ -575,16 +578,24 @@
|
||||
"integrity": "sha512-Waj1cwPXJDucOib4a3bAISsKJVb15MKi9IvmTI/7ssVEm6sywXGjVJDhl6/umt1pK1ZS7PacXU3A1PmFKHEZ2w==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/@honeybbq/teamspeak-client": {
|
||||
"version": "0.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak-client/-/teamspeak-client-0.2.2.tgz",
|
||||
"integrity": "sha512-JQ4yHEUwAxK2kHmIxelEf3grzMM8lVeuf7RzxK1g24U6XH8ZJO28S477FUtSTRe68PwUBkAlsa1Z/7BhLKh+AA==",
|
||||
"node_modules/@honeybbq/teamspeak": {
|
||||
"version": "1.0.0-beta.31",
|
||||
"resolved": "https://registry.npmjs.org/@honeybbq/teamspeak/-/teamspeak-1.0.0-beta.31.tgz",
|
||||
"integrity": "sha512-rOTnUVJdSmBruIA0UGLaUbat6iRCB64Ztuj7mCtyPif7vWnXzUA1FypjNWGorFLOrACgzEYCw+nfy2VQW8GudA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19"
|
||||
"node": ">=22.12"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ssh2": "^1.17.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ssh2": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/sourcemap-codec": {
|
||||
@@ -637,12 +648,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/curves": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.0.1.tgz",
|
||||
"integrity": "sha512-vs1Az2OOTBiP4q0pwjW5aF0xp9n4MxVrmkFBxc6EKZc6ddYx5gaZiAsZoq0uRRXWbi3AT/sBqn05eRPtn1JCPw==",
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz",
|
||||
"integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "2.0.1"
|
||||
"@noble/hashes": "2.4.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 20.19.0"
|
||||
@@ -652,9 +663,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/hashes": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.0.1.tgz",
|
||||
"integrity": "sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==",
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",
|
||||
"integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 20.19.0"
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "tsmusicbot",
|
||||
"version": "0.1.0",
|
||||
"version": "1.16.0",
|
||||
"description": "TeamSpeak music bot with NetEase Cloud Music and QQ Music support",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
@@ -20,7 +20,7 @@
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@honeybbq/teamspeak-client": "^0.2.1",
|
||||
"@honeybbq/teamspeak": "^1.0.0-beta.31",
|
||||
"@koa/router": "^15.4.0",
|
||||
"@sansenjian/qq-music-api": "~2.4.0",
|
||||
"axios": "^1.14.0",
|
||||
|
||||
@@ -50,6 +50,7 @@ describe("buildFfmpegArgs", () => {
|
||||
"https://szbdyd.com/audio.m4s",
|
||||
"https://stream.mcdn.szbdyd.com/audio.m4s",
|
||||
"https://xy219x131x72x38xy.mcdn.bilivideo.cn.szbdyd.com/audio.m4s",
|
||||
"https://b-bacb4fc51cs41d5p0dxdau053w.edge.mountaintoys.cn/audio.m4s",
|
||||
"HTTPS://UPOS-SZ-MIRRORCOS.BILIVIDEO.COM:443/audio.m4s",
|
||||
"https://upos-sz-mirrorcos.bilivideo.com./audio.m4s",
|
||||
])("uses Bilibili headers and input-side seeking for the actual CDN host in %s", (url) => {
|
||||
@@ -70,6 +71,8 @@ describe("buildFfmpegArgs", () => {
|
||||
"https://bilibili.com.evil.example/audio.m4s",
|
||||
"https://evilbilibili.com/audio.m4s",
|
||||
"https://szbdyd.com.evil.example/audio.m4s",
|
||||
"https://mountaintoys.cn.evil.example/audio.m4s",
|
||||
"https://evilmountaintoys.cn/audio.m4s",
|
||||
"https://evil.example/audio.m4s?redirect=https://upos-sz-mirrorcos.bilivideo.com/x",
|
||||
"https://bilibili.com@evil.example/audio.m4s",
|
||||
])("does not trust Bilibili text outside an allowed hostname in %s", (url) => {
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ export function buildFfmpegArgs(url: string, seekSeconds: number): string[] {
|
||||
}
|
||||
const isHttp = httpHostname !== null;
|
||||
const isBilibili = httpHostname !== null &&
|
||||
["bilivideo.com", "bilivideo.cn", "bilibili.com", "szbdyd.com"].some(
|
||||
["bilivideo.com", "bilivideo.cn", "bilibili.com", "szbdyd.com", "mountaintoys.cn"].some(
|
||||
domain => httpHostname === domain || httpHostname.endsWith(`.${domain}`),
|
||||
);
|
||||
|
||||
|
||||
@@ -29,6 +29,10 @@ function makeBot() {
|
||||
player.getVolume = () => 50;
|
||||
player.pause = AudioPlayer.prototype.pause;
|
||||
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.stop = vi.fn(() => { player.sessionId++; player.state = "idle"; });
|
||||
const provider = { getSongUrl: vi.fn(async (): Promise<{ url: string } | null> => ({ url: "fresh" })) };
|
||||
|
||||
@@ -396,6 +396,20 @@ const resolveAndPlay = BotInstance.prototype.resolveAndPlay as (
|
||||
this: unknown,
|
||||
song: any,
|
||||
) => Promise<boolean>;
|
||||
|
||||
it("re-resolves an active web FM account before fetching more songs", async () => {
|
||||
const old = { platform: "netease", getCookie: () => "old", getPersonalFm: vi.fn(async () => []) };
|
||||
const shared = { platform: "netease", getCookie: () => "shared", getPersonalFm: vi.fn(async () => []) };
|
||||
const context = {
|
||||
isFmMode: true,
|
||||
fmProvider: old,
|
||||
resolveFmProvider: () => shared,
|
||||
logger: { error: vi.fn() },
|
||||
};
|
||||
await (BotInstance.prototype as unknown as { refillFm(): Promise<void> }).refillFm.call(context);
|
||||
expect(old.getPersonalFm).not.toHaveBeenCalled();
|
||||
expect(shared.getPersonalFm).toHaveBeenCalledOnce();
|
||||
});
|
||||
const setupPlayerEvents = (BotInstance.prototype as any).setupPlayerEvents as (
|
||||
this: unknown,
|
||||
) => void;
|
||||
@@ -461,6 +475,7 @@ function makeResolveCtx(opts: {
|
||||
config: {},
|
||||
id: "bot1",
|
||||
voteSkipUsers: new Set<string>(),
|
||||
queue: { current: vi.fn(() => null) },
|
||||
autoPaused: false,
|
||||
currentSourceIsSpotify: opts.currentSourceIsSpotify ?? false,
|
||||
effectiveDuration: undefined,
|
||||
@@ -487,6 +502,22 @@ function spotifySong() {
|
||||
};
|
||||
}
|
||||
|
||||
it("does not start a track whose URL resolved after the queue was cleared", async () => {
|
||||
const player = makePlayer();
|
||||
const song = { ...spotifySong(), platform: "netease" };
|
||||
const ctx = makeResolveCtx({ controller: makeController(), player, url: "" });
|
||||
ctx.queue.current.mockReturnValue(song);
|
||||
ctx.getProviderFor.mockReturnValue({
|
||||
getSongUrl: async () => {
|
||||
ctx.queue.current.mockReturnValue(null);
|
||||
return { url: "https://example.com/track" };
|
||||
},
|
||||
});
|
||||
|
||||
expect(await resolveAndPlay.call(ctx, song)).toBe(false);
|
||||
expect(player.play).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe("BotInstance.resolveAndPlay — Spotify routing (C4)", () => {
|
||||
it("routes a spotify song to controller.playTrack + player.playPcmStream, not player.play", async () => {
|
||||
const controller = makeController();
|
||||
@@ -1544,6 +1575,36 @@ describe("BotInstance live-queue persistence (#119)", () => {
|
||||
});
|
||||
|
||||
describe("BotInstance Bilibili multi-P resolution", () => {
|
||||
it("passes the page from a TeamSpeak video link to the Bilibili provider", async () => {
|
||||
const song = {
|
||||
id: "BV1yxHQeYEuE?p=2",
|
||||
name: "Video - P2",
|
||||
artist: "Uploader",
|
||||
album: "",
|
||||
duration: 180,
|
||||
coverUrl: "",
|
||||
platform: "bilibili" as const,
|
||||
};
|
||||
const provider = { platform: "bilibili", getSongDetail: vi.fn().mockResolvedValue(song) };
|
||||
const ctx = {
|
||||
config: { commandPrefix: "!" },
|
||||
assertProviderEnabled: vi.fn(),
|
||||
getProviderFor: vi.fn().mockReturnValue(provider),
|
||||
};
|
||||
const args = "[URL]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2[/URL]";
|
||||
|
||||
const result = await (BotInstance.prototype as any).resolvePlayQuery.call(ctx, {
|
||||
name: "play",
|
||||
args,
|
||||
rawArgs: [args],
|
||||
flags: new Set(),
|
||||
});
|
||||
|
||||
expect(ctx.getProviderFor).toHaveBeenCalledWith("bilibili");
|
||||
expect(provider.getSongDetail).toHaveBeenCalledWith("BV1yxHQeYEuE?p=2");
|
||||
expect(result.song).toEqual(song);
|
||||
});
|
||||
|
||||
it("resolves multi-P search result to P1 with accurate duration and name", async () => {
|
||||
const multiPSongDetail = {
|
||||
id: "BV1multiP?p=1",
|
||||
@@ -1780,6 +1841,10 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
player.getPlaybackSessionId = AudioPlayer.prototype.getPlaybackSessionId;
|
||||
player.pause = AudioPlayer.prototype.pause;
|
||||
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"; });
|
||||
const provider = { getSongUrl: vi.fn(async () => ({ url: "fresh" })) };
|
||||
const advances: string[] = [];
|
||||
@@ -1948,3 +2013,150 @@ describe("BotInstance trackEnd — stale playback sessions", () => {
|
||||
expect(ctx.advances).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BotInstance — OpenProtocol & command routing", () => {
|
||||
it("routes private DM command replies to invokerId and channel replies to the channel", async () => {
|
||||
const ctx = makeGateCtx({ adminGroups: [] });
|
||||
ctx.executeCommand = vi.fn(async (parsed: { name: string; args: string }) =>
|
||||
`ok:${parsed.name}:${parsed.args}`,
|
||||
);
|
||||
|
||||
const dm: TS3TextMessage = {
|
||||
invokerName: "FlSpeakUser",
|
||||
invokerId: "12",
|
||||
invokerUid: "uid-fl",
|
||||
message: "!play 晴天",
|
||||
targetMode: 1,
|
||||
invokerGroups: [],
|
||||
};
|
||||
await handleTextMessage.call(ctx, dm);
|
||||
|
||||
expect(ctx.executeCommand).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:play:晴天", 1, 12);
|
||||
|
||||
ctx.tsClient.sendTextMessage.mockClear();
|
||||
await handleTextMessage.call(ctx, makeMsg("!now"));
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith("ok:now:");
|
||||
});
|
||||
|
||||
it("drops a private command reply when the connection changed during execution", async () => {
|
||||
const ctx = makeGateCtx({});
|
||||
ctx.lifecycleGeneration = 1;
|
||||
const executed = deferred();
|
||||
const reply = deferred<string>();
|
||||
ctx.executeCommand = vi.fn(() => {
|
||||
executed.resolve();
|
||||
return reply.promise;
|
||||
});
|
||||
|
||||
const pending = handleTextMessage.call(ctx, { ...makeMsg("!now"), targetMode: 1 });
|
||||
await executed.promise;
|
||||
ctx.lifecycleGeneration++;
|
||||
reply.resolve("Prior connection's queue");
|
||||
await pending;
|
||||
|
||||
expect(ctx.tsClient.sendTextMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("drops a command from a previous connection after the group check", async () => {
|
||||
const ctx = makeGateCtx({ adminGroups: [6] });
|
||||
ctx.lifecycleGeneration = 1;
|
||||
const groups = deferred<string[]>();
|
||||
ctx.tsClient.getClientServerGroups.mockReturnValue(groups.promise);
|
||||
|
||||
const pending = handleTextMessage.call(ctx, { ...makeMsg("!stop"), targetMode: 1 });
|
||||
expect(ctx.tsClient.getClientServerGroups).toHaveBeenCalled();
|
||||
ctx.lifecycleGeneration++;
|
||||
groups.resolve(["6"]);
|
||||
await pending;
|
||||
|
||||
expect(ctx.executeCommand).not.toHaveBeenCalled();
|
||||
expect(ctx.tsClient.sendTextMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("routes permission denied and execution errors privately when triggered via DM", async () => {
|
||||
const ctx = makeGateCtx({ adminGroups: [6], lookupGroups: [] });
|
||||
const dmStop: TS3TextMessage = {
|
||||
invokerName: "Guest",
|
||||
invokerId: "22",
|
||||
invokerUid: "uid-guest",
|
||||
message: "!stop",
|
||||
targetMode: 1,
|
||||
invokerGroups: [],
|
||||
};
|
||||
await handleTextMessage.call(ctx, dmStop);
|
||||
expect(ctx.tsClient.sendTextMessage).toHaveBeenCalledWith(COMMAND_DENIED_MESSAGE, 1, 22);
|
||||
|
||||
ctx.tsClient.sendTextMessage.mockClear();
|
||||
const okCtx = makeGateCtx({ adminGroups: [] });
|
||||
okCtx.executeCommand = vi.fn(async () => {
|
||||
throw new Error("boom");
|
||||
});
|
||||
await handleTextMessage.call(okCtx, { ...dmStop, message: "!play x" });
|
||||
expect(okCtx.tsClient.sendTextMessage).toHaveBeenCalledWith("Error: boom", 1, 22);
|
||||
});
|
||||
|
||||
it("wires connected, clientMoved, pluginCommand, and disconnected to openProtocol", () => {
|
||||
const tsClient = new EventEmitter() as EventEmitter & {
|
||||
getClientId(): number;
|
||||
};
|
||||
tsClient.getClientId = () => 99;
|
||||
const openProtocol = {
|
||||
scheduleAnnounce: vi.fn(),
|
||||
handlePluginCommand: vi.fn(async () => {}),
|
||||
reset: vi.fn(),
|
||||
};
|
||||
const ctx = {
|
||||
tsClient,
|
||||
openProtocol,
|
||||
connected: true,
|
||||
lifecycleGeneration: 0,
|
||||
autoPaused: false,
|
||||
idleTimer: null,
|
||||
idlePollTimer: null,
|
||||
jellyfinPollTimer: null,
|
||||
snapshotTimer: null,
|
||||
currentSourceIsSpotify: false,
|
||||
disconnectEmitted: false,
|
||||
_cancelIdleTimer: vi.fn(),
|
||||
_startIdlePoller: vi.fn(),
|
||||
_startJellyfinReportPoller: vi.fn(),
|
||||
unregisterManagedVoiceClient: vi.fn(),
|
||||
voiceDucking: { reset: vi.fn(), removeSpeaker: vi.fn(), handleVoiceActivity: vi.fn() },
|
||||
spotifyController: { stop: vi.fn() },
|
||||
player: { stop: vi.fn() },
|
||||
jellyfinReporter: undefined,
|
||||
queue: { clear: vi.fn() },
|
||||
sweepLocalAudio: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
refreshOccupancy: vi.fn(async () => {}),
|
||||
profileManager: { onChannelMoved: vi.fn(async () => {}) },
|
||||
logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
|
||||
} as Record<string, any>;
|
||||
|
||||
(BotInstance.prototype as any).setupTsEvents.call(ctx);
|
||||
|
||||
tsClient.emit("connected");
|
||||
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(1);
|
||||
|
||||
tsClient.emit("clientMoved", { id: 5, targetChannelID: 10n });
|
||||
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(1);
|
||||
|
||||
tsClient.emit("clientMoved", { id: 99, targetChannelID: 10n });
|
||||
expect(openProtocol.scheduleAnnounce).toHaveBeenCalledTimes(2);
|
||||
|
||||
const pluginCmd = {
|
||||
name: "tsclient:commands",
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 5,
|
||||
invokerName: "User",
|
||||
invokerUid: "uid-user",
|
||||
};
|
||||
tsClient.emit("pluginCommand", pluginCmd);
|
||||
expect(openProtocol.handlePluginCommand).toHaveBeenCalledWith(pluginCmd);
|
||||
|
||||
tsClient.emit("disconnected");
|
||||
expect(openProtocol.reset).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
+195
-49
@@ -2,13 +2,18 @@ import { EventEmitter } from "node:events";
|
||||
import {
|
||||
TS3Client,
|
||||
type TS3ClientOptions,
|
||||
type TS3PluginCommand,
|
||||
type TS3TextMessage,
|
||||
type TS3VoiceActivity,
|
||||
type TS3VoiceSendFailure,
|
||||
} from "../ts-protocol/client.js";
|
||||
import { OpenProtocolManager } from "../ts-protocol/open-protocol.js";
|
||||
import { AudioPlayer } from "../audio/player.js";
|
||||
import { resolveUrlWithRetry } from "./url-retry.js";
|
||||
import { RISK_CONTROL_CODE, RiskControlError, toPlayFailure } from "../music/provider.js";
|
||||
import { PlayQueue, PlayMode, type QueuedSong } from "../audio/queue.js";
|
||||
import type { MusicProvider, Platform, Song } from "../music/provider.js";
|
||||
import type { MusicProvider, Platform, PlayFailure, Song, SongUrlResult } from "../music/provider.js";
|
||||
import { musicRequestError } from "../music/request-error.js";
|
||||
import {
|
||||
parseCommand,
|
||||
canRunCommand,
|
||||
@@ -154,11 +159,27 @@ export interface BotStatus {
|
||||
effectiveDuration?: number;
|
||||
}
|
||||
|
||||
async function sendTextReply(
|
||||
tsClient: Pick<TS3Client, "sendTextMessage">,
|
||||
msg: TS3TextMessage,
|
||||
text: string,
|
||||
): Promise<void> {
|
||||
if (msg.targetMode === 1) {
|
||||
const targetClientId = Number(msg.invokerId);
|
||||
if (Number.isInteger(targetClientId) && targetClientId > 0) {
|
||||
await tsClient.sendTextMessage(text, 1, targetClientId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
await tsClient.sendTextMessage(text);
|
||||
}
|
||||
|
||||
export class BotInstance extends EventEmitter {
|
||||
readonly id: string;
|
||||
name: string;
|
||||
|
||||
private tsClient: TS3Client;
|
||||
private openProtocol: OpenProtocolManager;
|
||||
private player: AudioPlayer;
|
||||
private voiceDucking: VoiceDuckingController;
|
||||
private managedVoiceClients: ManagedVoiceClientRegistry;
|
||||
@@ -198,9 +219,11 @@ export class BotInstance extends EventEmitter {
|
||||
private profileManager: BotProfileManager;
|
||||
private isFmMode = false;
|
||||
private fmProvider: MusicProvider | null = null;
|
||||
private resolveFmProvider?: () => MusicProvider;
|
||||
private fmRequesterName: string | undefined;
|
||||
/** Results of the most recent !search, for "#N" selection (issue #90). */
|
||||
private lastSearchResults: Song[] = [];
|
||||
private playbackRequest?: symbol;
|
||||
/** 当前曲实际播放时长(试听片段秒数或完整 duration);resolveAndPlay 赋值。 */
|
||||
private effectiveDuration: number | undefined;
|
||||
/** Resume attempts for the current song's stream (#161); see resumeInterruptedStream. */
|
||||
@@ -230,6 +253,14 @@ export class BotInstance extends EventEmitter {
|
||||
this.avatarStore = options.avatarStore;
|
||||
|
||||
this.tsClient = new TS3Client(options.tsOptions, this.logger);
|
||||
this.openProtocol = new OpenProtocolManager({
|
||||
transport: this.tsClient,
|
||||
getConfig: () => ({
|
||||
locale: this.config.locale,
|
||||
commandPrefix: this.config.commandPrefix,
|
||||
}),
|
||||
logger: this.logger,
|
||||
});
|
||||
this.player = new AudioPlayer(this.logger);
|
||||
this.voiceDucking = new VoiceDuckingController(
|
||||
this.player,
|
||||
@@ -446,6 +477,12 @@ export class BotInstance extends EventEmitter {
|
||||
});
|
||||
});
|
||||
|
||||
this.tsClient.on("pluginCommand", (cmd: TS3PluginCommand) => {
|
||||
this.openProtocol?.handlePluginCommand(cmd).catch((err) => {
|
||||
this.logger.debug({ err }, "OpenProtocol plugin command handler failed");
|
||||
});
|
||||
});
|
||||
|
||||
this.tsClient.on("disconnected", () => {
|
||||
// Always reset local state — covers the case where connect() never
|
||||
// completed (hanging handshake → 60s library idle timeout) and
|
||||
@@ -453,6 +490,7 @@ export class BotInstance extends EventEmitter {
|
||||
// short-circuited on !this.connected, leaving player stuck as "playing".
|
||||
this.lifecycleGeneration++;
|
||||
this.connected = false;
|
||||
this.openProtocol?.reset();
|
||||
this._cancelIdleTimer();
|
||||
this.unregisterManagedVoiceClient(MANAGED_VOICE_CLIENT_RELEASE_GRACE_MS);
|
||||
this.voiceDucking.reset(true);
|
||||
@@ -487,6 +525,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.autoPaused = false;
|
||||
this._startIdlePoller();
|
||||
this._startJellyfinReportPoller();
|
||||
this.openProtocol?.scheduleAnnounce();
|
||||
});
|
||||
|
||||
this.tsClient.on("voiceActivity", (activity: TS3VoiceActivity) => {
|
||||
@@ -525,6 +564,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.profileManager.onChannelMoved(event.targetChannelID).catch((err) => {
|
||||
this.logger.warn({ err }, "Channel description move update failed");
|
||||
});
|
||||
this.openProtocol?.scheduleAnnounce();
|
||||
} else {
|
||||
this.voiceDucking.removeSpeaker(event.id);
|
||||
}
|
||||
@@ -667,6 +707,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.disconnectEmitted = true;
|
||||
this.emit("disconnected");
|
||||
}
|
||||
this.openProtocol?.reset();
|
||||
this.tsClient.disconnect();
|
||||
// Stop outbound PCM and initiate the TeamSpeak disconnect before removing
|
||||
// our id from the shared registry, minimizing the window in which another
|
||||
@@ -794,13 +835,19 @@ export class BotInstance extends EventEmitter {
|
||||
);
|
||||
if (!parsed) return;
|
||||
|
||||
if (!(await this.isCommandAllowed(parsed.name, msg))) {
|
||||
// A numeric invoker ID only belongs to this TeamSpeak connection.
|
||||
const generation = this.lifecycleGeneration;
|
||||
const isCurrent = () => this.lifecycleGeneration === generation;
|
||||
const allowed = await this.isCommandAllowed(parsed.name, msg);
|
||||
if (!isCurrent()) return;
|
||||
|
||||
if (!allowed) {
|
||||
this.logger.info(
|
||||
{ command: parsed.name, invoker: msg.invokerName },
|
||||
"Command denied: invoker not in adminGroups"
|
||||
);
|
||||
try {
|
||||
await this.tsClient.sendTextMessage(COMMAND_DENIED_MESSAGE);
|
||||
await sendTextReply(this.tsClient, msg, COMMAND_DENIED_MESSAGE);
|
||||
} catch (sendErr) {
|
||||
this.logger.error({ err: sendErr }, "Failed to send permission-denied message to chat");
|
||||
}
|
||||
@@ -818,15 +865,15 @@ export class BotInstance extends EventEmitter {
|
||||
// A single long reply (e.g. full lyrics) would exceed TeamSpeak's
|
||||
// per-message byte cap, so split it and send the chunks in order.
|
||||
for (const chunk of splitTextIntoChunks(response)) {
|
||||
await this.tsClient.sendTextMessage(chunk);
|
||||
if (!isCurrent()) return;
|
||||
await sendTextReply(this.tsClient, msg, chunk);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isCurrent()) return;
|
||||
this.logger.error({ err, command: parsed.name }, "Command execution error");
|
||||
try {
|
||||
await this.tsClient.sendTextMessage(
|
||||
`Error: ${(err as Error).message}`
|
||||
);
|
||||
await sendTextReply(this.tsClient, msg, `Error: ${(err as Error).message}`);
|
||||
} catch (sendErr) {
|
||||
this.logger.error({ err: sendErr }, "Failed to send error message to chat");
|
||||
}
|
||||
@@ -980,6 +1027,7 @@ export class BotInstance extends EventEmitter {
|
||||
private disableFmMode(): void {
|
||||
this.isFmMode = false;
|
||||
this.fmProvider = null;
|
||||
this.resolveFmProvider = undefined;
|
||||
this.fmRequesterName = undefined;
|
||||
}
|
||||
|
||||
@@ -1021,55 +1069,118 @@ export class BotInstance extends EventEmitter {
|
||||
return requestedBy ? { ...song, requestedBy } : { ...song };
|
||||
}
|
||||
|
||||
/** Resolve URL for a song and start playing it. Skips to next if URL fails. */
|
||||
async resolveAndPlay(song: QueuedSong): Promise<boolean> {
|
||||
/** Resolve the URL and start playback if this request still owns the queue. */
|
||||
async resolveAndPlay(song: QueuedSong, onFailure?: (failure: PlayFailure) => void): Promise<boolean> {
|
||||
const request = Symbol();
|
||||
this.playbackRequest = request;
|
||||
const generation = this.lifecycleGeneration;
|
||||
const current = this.queue.current();
|
||||
const isCancelled = () => !this.connected || this.lifecycleGeneration !== generation ||
|
||||
this.playbackRequest !== request || this.queue.current() !== current;
|
||||
const fail = (message: string) => onFailure?.({
|
||||
platform: song.platform,
|
||||
songId: song.id,
|
||||
code: "unknown",
|
||||
message,
|
||||
});
|
||||
if (!this.connected) {
|
||||
this.logger.warn({ songId: song.id, name: song.name }, "resolveAndPlay called on disconnected bot — skipping");
|
||||
fail("机器人未连接");
|
||||
return false;
|
||||
}
|
||||
if (song.platform === "local" && !this.isLocalAudioEnabled()) {
|
||||
this.logger.warn({ songId: song.id, name: song.name }, "Local audio playback disabled — refusing track");
|
||||
fail("该机器人已关闭本地音频播放");
|
||||
return false;
|
||||
}
|
||||
// Clear any accumulated skip votes — every fresh track starts with a
|
||||
// clean slate, regardless of which code path loaded it (cmdPlay,
|
||||
// cmdPlaylist, cmdAlbum, cmdFm, trackEnd auto-advance, etc.).
|
||||
this.voteSkipUsers.clear();
|
||||
const provider = this.getProviderFor(song.platform);
|
||||
try {
|
||||
const provider = this.getProviderFor(song.platform);
|
||||
if (song.platform === "bilibili" && (!song.id.includes("?p=") || song.duration === 0)) {
|
||||
const detail = await provider.getSongDetail(song.id);
|
||||
if (detail) {
|
||||
song.duration = detail.duration;
|
||||
song.name = detail.name;
|
||||
song.id = detail.id;
|
||||
// Detail is metadata only (duration / canonical id). A failure here used
|
||||
// to abort the whole resolve before the retry budget even started, so a
|
||||
// transient 4xx turned into an instant 「无法播放」.
|
||||
try {
|
||||
const detail = await provider.getSongDetail(song.id);
|
||||
if (isCancelled()) return false;
|
||||
if (detail) {
|
||||
song.duration = detail.duration;
|
||||
song.name = detail.name;
|
||||
song.id = detail.id;
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn({ err, songId: song.id }, "Song detail lookup failed — continuing with queued metadata");
|
||||
}
|
||||
}
|
||||
const result = await provider.getSongUrl(song.id);
|
||||
if (!result?.url) {
|
||||
this.logger.warn({ songId: song.id, name: song.name }, "No URL available, skipping");
|
||||
return false;
|
||||
}
|
||||
// Re-check connection state AFTER the network round-trip — the URL
|
||||
// resolve can take multiple seconds and the user may have called stop
|
||||
// during that window. Without this, we'd spawn ffmpeg on a
|
||||
// disconnected bot and land back in the same "connected=false but
|
||||
// playing=true" inconsistency that Bug C was about.
|
||||
if (!this.connected) {
|
||||
this.logger.warn(
|
||||
{ songId: song.id, name: song.name },
|
||||
"bot disconnected during URL resolve — aborting playback",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Retries happen here (not in the provider) so every queue path — web
|
||||
// click, chat !play, auto-advance, FM — shares the same budget. The
|
||||
// policy lives in url-retry.ts so it is unit tested without a bot; a
|
||||
// config without the field means 0 retries, i.e. the previous behaviour.
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: this.config?.playUrlRetries,
|
||||
resolve: (quality) => provider.getSongUrl(song.id, quality),
|
||||
// NetEase's quality ladder is not continuous: a track can play at 192k
|
||||
// while both 320k and 128k return null, so every lower level is tried.
|
||||
// Providers without a quality knob return [] and keep one attempt.
|
||||
fallbacks: provider.getFallbackQualities?.() ?? [],
|
||||
// Stop / disconnect must abort the budget: retrying into a dead
|
||||
// connection only delays the queue.
|
||||
isCancelled,
|
||||
onAttemptFailed: ({ attempt, total, quality, error }) => {
|
||||
const fields = { songId: song.id, name: song.name, attempt, total, quality };
|
||||
if (error instanceof RiskControlError) {
|
||||
// -460 is NetEase refusing the IP, not this track. Say so, otherwise
|
||||
// the log reads like the song is unavailable and people go hunting
|
||||
// for a copyright problem that does not exist.
|
||||
this.logger.warn(
|
||||
{ ...fields, code: RISK_CONTROL_CODE, reason: error.message },
|
||||
"URL resolve hit NetEase risk control (-460) — backing off",
|
||||
);
|
||||
} else if (error) {
|
||||
this.logger.warn({ ...fields, err: error }, "URL resolve threw — retrying");
|
||||
} else if (attempt < total) {
|
||||
this.logger.debug(fields, "URL resolve returned no URL — retrying");
|
||||
}
|
||||
},
|
||||
// Once per track, and with the reason named. The old log line was
|
||||
// `No URL available` with no cause, which is what sent three separate
|
||||
// investigations after a copyright problem that was never there.
|
||||
onExhausted: ({ quality, error }) => {
|
||||
const failure = error
|
||||
? toPlayFailure(provider.platform, song.id, error)
|
||||
: {
|
||||
platform: provider.platform,
|
||||
songId: song.id,
|
||||
code: "unknown" as const,
|
||||
message: `没有拿到播放地址(${quality ?? "默认音质"})`,
|
||||
};
|
||||
onFailure?.(failure);
|
||||
this.logger.warn(
|
||||
{
|
||||
songId: song.id,
|
||||
name: song.name,
|
||||
platform: provider.platform,
|
||||
code: failure.code,
|
||||
quality: quality ?? "default",
|
||||
upstream: failure.upstream,
|
||||
reason: failure.message,
|
||||
},
|
||||
"No URL available, skipping",
|
||||
);
|
||||
},
|
||||
});
|
||||
if (!result?.url || isCancelled()) return false;
|
||||
// Stage 2: a `spotify:` sentinel URI means the go-librespot sidecar
|
||||
// serves the audio, NOT ffmpeg. Start the per-bot sidecar on demand; if
|
||||
// it can't run (disabled / non-Linux / binary missing) keep the Stage-1
|
||||
// fallback message + skip so the queue keeps moving.
|
||||
if (isSpotifyUri(result.url)) {
|
||||
const ready = await this.spotifyController.ensureStarted();
|
||||
if (isCancelled()) return false;
|
||||
if (!ready) {
|
||||
this.logger.info({ songId: song.id, name: song.name }, "Spotify backend unavailable — skipping");
|
||||
fail(SPOTIFY_UNAVAILABLE_MESSAGE);
|
||||
await this.tsClient.sendTextMessage(SPOTIFY_UNAVAILABLE_MESSAGE);
|
||||
return false;
|
||||
}
|
||||
@@ -1079,8 +1190,10 @@ export class BotInstance extends EventEmitter {
|
||||
// sidecar failed the play (dead/errored backend): never attach the
|
||||
// player to a dead stream — send the same fallback and skip.
|
||||
const played = await this.spotifyController.playTrack(result.url);
|
||||
if (isCancelled()) return false;
|
||||
if (!played) {
|
||||
this.logger.info({ songId: song.id, name: song.name }, "Spotify playTrack failed — skipping");
|
||||
fail(SPOTIFY_UNAVAILABLE_MESSAGE);
|
||||
await this.tsClient.sendTextMessage(SPOTIFY_UNAVAILABLE_MESSAGE);
|
||||
return false;
|
||||
}
|
||||
@@ -1180,7 +1293,9 @@ export class BotInstance extends EventEmitter {
|
||||
this.emit("stateChange");
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (isCancelled()) return false;
|
||||
this.logger.error({ err, songId: song.id }, "Failed to resolve URL");
|
||||
onFailure?.(toPlayFailure(song.platform, song.id, err));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1364,8 +1479,9 @@ export class BotInstance extends EventEmitter {
|
||||
const { song, error } = await this.resolvePlayQuery(cmd);
|
||||
if (error) return error;
|
||||
const song0 = song!;
|
||||
const ok = await this.playSingleSong(song0, requesterName);
|
||||
if (!ok) return `Cannot play: ${song0.name}`;
|
||||
let why: string | undefined;
|
||||
const ok = await this.playSingleSong(song0, requesterName, failure => { why = failure.message; });
|
||||
if (!ok) return why ? `Cannot play: ${song0.name} — ${why}` : `Cannot play: ${song0.name}`;
|
||||
return `Now playing: ${song0.name} - ${song0.artist}`;
|
||||
}
|
||||
|
||||
@@ -1381,7 +1497,7 @@ export class BotInstance extends EventEmitter {
|
||||
* Shared by chat !play and the web /play-song route so the toggle decision
|
||||
* lives in exactly one place (#119). Returns true if a track started playing.
|
||||
*/
|
||||
async playSingleSong(song: QueuedSong, requesterName?: string): Promise<boolean> {
|
||||
async playSingleSong(song: QueuedSong, requesterName?: string, onFailure?: (failure: PlayFailure) => void): Promise<boolean> {
|
||||
const s = this.withRequester(song, requesterName);
|
||||
if (this.config.playKeepsQueue && !this.queue.isEmpty()) {
|
||||
const insertedAt =
|
||||
@@ -1394,7 +1510,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.queue.playAt(insertedAt);
|
||||
this.player.resetFailures();
|
||||
// No sweep here: the queue is kept, so no local uploads were released.
|
||||
return this.resolveAndPlay(this.queue.current()!);
|
||||
return this.resolveAndPlay(this.queue.current()!, onFailure);
|
||||
}
|
||||
// Legacy replace behavior (default).
|
||||
const previous = this.queue.current();
|
||||
@@ -1408,7 +1524,7 @@ export class BotInstance extends EventEmitter {
|
||||
|
||||
// Reset failure counter on user-initiated play
|
||||
this.player.resetFailures();
|
||||
const ok = await this.resolveAndPlay(this.queue.current()!);
|
||||
const ok = await this.resolveAndPlay(this.queue.current()!, onFailure);
|
||||
// Sweep AFTER the new song is queued+resolved: the replaced songs are no
|
||||
// longer referenced (and get deleted), but the song — if it is the same
|
||||
// local upload that was already playing — stays referenced and is preserved.
|
||||
@@ -1807,7 +1923,11 @@ export class BotInstance extends EventEmitter {
|
||||
return this.startFm(this.getProvider(cmd.flags), requesterName);
|
||||
}
|
||||
|
||||
async startFm(provider: MusicProvider = this.neteaseProvider, requesterName?: string): Promise<string> {
|
||||
async startFm(
|
||||
provider: MusicProvider = this.neteaseProvider,
|
||||
requesterName?: string,
|
||||
resolveProvider?: () => MusicProvider,
|
||||
): Promise<string> {
|
||||
// Match the !fm chat-command guard: refuse before mutating the queue when
|
||||
// offline, so the web /fm route can't wipe the queue + flip into FM mode
|
||||
// while nothing can actually play.
|
||||
@@ -1829,6 +1949,7 @@ export class BotInstance extends EventEmitter {
|
||||
this.queue.setMode(PlayMode.Random);
|
||||
this.isFmMode = true;
|
||||
this.fmProvider = provider;
|
||||
this.resolveFmProvider = resolveProvider;
|
||||
this.fmRequesterName = requesterName?.trim() || undefined;
|
||||
this.player.resetFailures();
|
||||
|
||||
@@ -1874,17 +1995,23 @@ export class BotInstance extends EventEmitter {
|
||||
}
|
||||
|
||||
private async refillFm(): Promise<void> {
|
||||
const provider = this.fmProvider;
|
||||
if (!this.isFmMode || !provider?.getPersonalFm) return;
|
||||
if (!this.isFmMode || !this.fmProvider) return;
|
||||
const resolveProvider = this.resolveFmProvider;
|
||||
try {
|
||||
const current = this.fmProvider;
|
||||
const resolved = resolveProvider?.() ?? current;
|
||||
// Keep a provider's FM cursor while its login remains unchanged.
|
||||
const provider = resolved !== current && resolved.getCookie() !== current.getCookie() ? resolved : current;
|
||||
this.fmProvider = provider;
|
||||
if (!provider.getPersonalFm) return;
|
||||
const songs = await provider.getPersonalFm();
|
||||
if (songs.length === 0) return;
|
||||
if (!this.isFmMode || this.fmProvider !== provider || this.resolveFmProvider !== resolveProvider || songs.length === 0) return;
|
||||
for (const song of songs) {
|
||||
this.queue.add(this.withRequester({ ...song, platform: provider.platform }, this.fmRequesterName));
|
||||
}
|
||||
this.logger.debug({ count: songs.length, platform: provider.platform }, "FM queue refilled");
|
||||
} catch (err) {
|
||||
this.logger.error({ err }, "Failed to refill FM queue");
|
||||
this.logger.error({ err: musicRequestError(err) }, "Failed to refill FM queue");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2037,6 +2164,7 @@ export class BotInstance extends EventEmitter {
|
||||
if (st.isFmMode && st.fmPlatform) {
|
||||
this.isFmMode = true;
|
||||
this.fmProvider = this.getProviderFor(st.fmPlatform as Platform);
|
||||
this.resolveFmProvider = undefined;
|
||||
}
|
||||
const current = this.queue.current();
|
||||
if (current) {
|
||||
@@ -2100,24 +2228,39 @@ export class BotInstance extends EventEmitter {
|
||||
*
|
||||
* Returns true if a song actually started playing, false otherwise.
|
||||
*/
|
||||
async playNext(maxRetries = 3): Promise<boolean> {
|
||||
async playNext(maxRetries = 3, onFailure?: (failure: PlayFailure) => void): Promise<boolean> {
|
||||
if (this.isAdvancing || !this.connected) return false;
|
||||
this.isAdvancing = true;
|
||||
let started = false;
|
||||
let riskControlled = false;
|
||||
const captureFailure = (failure: PlayFailure) => {
|
||||
riskControlled = failure.code === "risk_control";
|
||||
onFailure?.(failure);
|
||||
};
|
||||
const generation = this.lifecycleGeneration;
|
||||
const unchanged = (song: QueuedSong, request: symbol | undefined) =>
|
||||
this.connected && this.lifecycleGeneration === generation &&
|
||||
this.queue.current() === song && this.playbackRequest === request;
|
||||
try {
|
||||
if (this.player.getState() !== "idle") this.player.stop(true);
|
||||
this.voteSkipUsers.clear();
|
||||
const next = this.queue.next();
|
||||
if (next) {
|
||||
started = await this.resolveAndPlay(next);
|
||||
const playback = this.resolveAndPlay(next, captureFailure);
|
||||
const request = this.playbackRequest;
|
||||
started = await playback;
|
||||
if (!started && !unchanged(next, request)) return false;
|
||||
if (!started) {
|
||||
for (let i = 0; i < maxRetries && this.connected; i++) {
|
||||
for (let i = 0; i < maxRetries && this.connected && !riskControlled; i++) {
|
||||
const retry = this.queue.next();
|
||||
if (!retry) break;
|
||||
if (await this.resolveAndPlay(retry)) {
|
||||
const retryPlayback = this.resolveAndPlay(retry, captureFailure);
|
||||
const retryRequest = this.playbackRequest;
|
||||
if (await retryPlayback) {
|
||||
started = true;
|
||||
break;
|
||||
}
|
||||
if (!unchanged(retry, retryRequest)) return false;
|
||||
}
|
||||
}
|
||||
if (!started) {
|
||||
@@ -2133,7 +2276,10 @@ export class BotInstance extends EventEmitter {
|
||||
await this.refillFm();
|
||||
const refillNext = this.queue.next();
|
||||
if (refillNext) {
|
||||
started = await this.resolveAndPlay(refillNext);
|
||||
const refillPlayback = this.resolveAndPlay(refillNext, captureFailure);
|
||||
const refillRequest = this.playbackRequest;
|
||||
started = await refillPlayback;
|
||||
if (!started && !unchanged(refillNext, refillRequest)) return false;
|
||||
}
|
||||
if (!started) {
|
||||
this.player.stop();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { Client, generateIdentity } from "@honeybbq/teamspeak-client";
|
||||
import { BotProfileManager } from "./profile.js";
|
||||
import { TS6HttpQuery } from "../ts-protocol/http-query.js";
|
||||
import type { TS3Client } from "../ts-protocol/client.js";
|
||||
@@ -419,20 +418,15 @@ describe("BotProfileManager checked TS6 profile lifecycle", () => {
|
||||
|
||||
it("checks self clientupdate permission responses and retries only after reconnect", async () => {
|
||||
const { pm, ts, request, logger } = makeHttpProfile({ nicknameEnabled: true, awayStatusEnabled: true });
|
||||
const client: any = new Client(generateIdentity(0), "127.0.0.1:9987", "Bot");
|
||||
const commands: string[] = [];
|
||||
client.handler.sendPacket = vi.fn((_type, data: Buffer) => {
|
||||
const command = data.toString();
|
||||
ts.execCommand.mockImplementation(async (command: string) => {
|
||||
commands.push(command);
|
||||
const returnCode = command.match(/return_code=(\d+)/)?.[1];
|
||||
client.handler.onPacket({ typeFlagged: 2, data: Buffer.from(`error id=2568 msg=insufficient\\sclient\\spermissions${returnCode ? ` return_code=${returnCode}` : ""}`) });
|
||||
throw new Error("insufficient client permissions (error id=2568)");
|
||||
});
|
||||
ts.sendCommandNoWait.mockImplementation((command: string) => client.sendCommandNoWait(command));
|
||||
ts.execCommand.mockImplementation((command: string) => client.execCommand(command));
|
||||
await pm.onSongChange(null);
|
||||
await pm.onSongChange(null);
|
||||
expect(commands).toHaveLength(1);
|
||||
expect(commands[0]).toMatch(/^clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放 return_code=\d+$/);
|
||||
expect(commands[0]).toBe("clientupdate client_nickname=Bot client_away=1 client_away_message=等待播放");
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(logger.info.mock.calls.some((call: any[]) => call[1] === "Client properties updated (nickname + away)")).toBe(false);
|
||||
pm.onConnect();
|
||||
|
||||
@@ -101,6 +101,34 @@ describe("parseSongRef (#90 exact-song selection)", () => {
|
||||
expect(parseSongRef("https://www.bilibili.com/video/BV1yxHQeYEuE")).toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" });
|
||||
expect(parseSongRef("https://b23.tv/BV1yxHQeYEuE")).toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE?p=2",
|
||||
"https://b23.tv/BV1yxHQeYEuE?p=2",
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE/?from=share&p=2&vd_source=test#reply",
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE/?from=share?p=3&p=2",
|
||||
"https://www.bilibili.com/video/BV1yxHQeYEuE/?p=%32",
|
||||
"[URL]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2[/URL]",
|
||||
"[url]https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2#reply[/url]",
|
||||
"[URL=https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2]点击播放[/URL]",
|
||||
"参考 https://example.com/?p=9 视频 https://www.bilibili.com/video/BV1yxHQeYEuE/?p=2 请播放",
|
||||
])("preserves the Bilibili page query in %s", (input) => {
|
||||
expect(parseSongRef(input)).toEqual({ id: "BV1yxHQeYEuE?p=2", platform: "bilibili" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
"?p=2extra",
|
||||
"?p=-2",
|
||||
"?page=2",
|
||||
"?sp=2",
|
||||
"?from=share?p=2",
|
||||
"?from=share%3Fp%3D2",
|
||||
"?from=share#reply&p=2",
|
||||
"#reply?p=2",
|
||||
])("ignores an invalid or unrelated Bilibili page query %s", (query) => {
|
||||
expect(parseSongRef(`https://www.bilibili.com/video/BV1yxHQeYEuE${query}`))
|
||||
.toEqual({ id: "BV1yxHQeYEuE", platform: "bilibili" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseSelectionIndex (#90 pick from last search)", () => {
|
||||
|
||||
+5
-1
@@ -69,7 +69,11 @@ export function parseSongRef(raw: string): SongRef | null {
|
||||
// a "BV..." token never collides with them).
|
||||
const bv = /BV[0-9A-Za-z]{8,12}/.exec(q);
|
||||
if (bv && (/^BV[0-9A-Za-z]{8,12}$/.test(q) || /bilibili\.com|b23\.tv/i.test(q))) {
|
||||
return { id: bv[0], platform: "bilibili" };
|
||||
// Extract the query attached to this BV id, including in [URL=...] tags.
|
||||
const suffix = q.slice(bv.index + bv[0].length);
|
||||
const query = /^\/?\?([^#\s[\]]*)/.exec(suffix)?.[1];
|
||||
const page = new URLSearchParams(query).get("p");
|
||||
return { id: page && /^\d+$/.test(page) ? `${bv[0]}?p=${page}` : bv[0], platform: "bilibili" };
|
||||
}
|
||||
|
||||
// NetEase song URL. Only treat `id=N` as a SONG id when the URL is not a
|
||||
|
||||
@@ -0,0 +1,540 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { RiskControlError, SongUrlUnavailable, toPlayFailure } from "../music/provider.js";
|
||||
import type { SongUrlResult } from "../music/provider.js";
|
||||
import {
|
||||
MAX_URL_RETRIES,
|
||||
DEFAULT_URL_RETRY_BACKOFF_MS,
|
||||
QUALITY_SWITCH_BACKOFF_MS,
|
||||
RISK_CONTROL_BACKOFF_MS,
|
||||
normalizeRetryCount,
|
||||
resolveUrlWithRetry,
|
||||
} from "./url-retry.js";
|
||||
|
||||
const ok = (url = "https://cdn.example/track.mp3"): SongUrlResult => ({ url });
|
||||
|
||||
/** Sleep stand-in that records the delays instead of waiting. */
|
||||
function recordingSleep() {
|
||||
const delays: number[] = [];
|
||||
return { delays, sleep: async (ms: number) => void delays.push(ms) };
|
||||
}
|
||||
|
||||
describe("normalizeRetryCount", () => {
|
||||
it("accepts 0..MAX and truncates fractions", () => {
|
||||
expect(normalizeRetryCount(0)).toBe(0);
|
||||
expect(normalizeRetryCount(2)).toBe(2);
|
||||
expect(normalizeRetryCount(2.9)).toBe(2);
|
||||
});
|
||||
|
||||
it("clamps out-of-range numbers", () => {
|
||||
expect(normalizeRetryCount(-3)).toBe(0);
|
||||
expect(normalizeRetryCount(99)).toBe(MAX_URL_RETRIES);
|
||||
});
|
||||
|
||||
// Garbage means "old behaviour" (fail fast), not "retry forever".
|
||||
it("treats non-numeric values as zero", () => {
|
||||
expect(normalizeRetryCount(undefined)).toBe(0);
|
||||
expect(normalizeRetryCount(null)).toBe(0);
|
||||
expect(normalizeRetryCount("3")).toBe(0);
|
||||
expect(normalizeRetryCount(Number.NaN)).toBe(0);
|
||||
expect(normalizeRetryCount(Number.POSITIVE_INFINITY)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveUrlWithRetry", () => {
|
||||
it("makes exactly one attempt when retries is 0", async () => {
|
||||
const resolve = vi.fn(async () => null);
|
||||
const { sleep } = recordingSleep();
|
||||
const result = await resolveUrlWithRetry({ retries: 0, resolve, sleep });
|
||||
expect(result).toBeNull();
|
||||
expect(resolve).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// The reported bug: first click fails, third works. A retry inside one
|
||||
// request turns that into a normal play.
|
||||
it("succeeds on a later attempt and stops retrying", async () => {
|
||||
const resolve = vi
|
||||
.fn<() => Promise<SongUrlResult | null>>()
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce(ok());
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep });
|
||||
|
||||
expect(result).toEqual(ok());
|
||||
expect(resolve).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("gives up after 1 + retries attempts", async () => {
|
||||
const resolve = vi.fn(async () => null);
|
||||
const { sleep, delays } = recordingSleep();
|
||||
|
||||
const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep });
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(resolve).toHaveBeenCalledTimes(3);
|
||||
// Linear backoff: one wait before attempt 2, two units before attempt 3.
|
||||
expect(delays).toEqual([DEFAULT_URL_RETRY_BACKOFF_MS, DEFAULT_URL_RETRY_BACKOFF_MS * 2]);
|
||||
});
|
||||
|
||||
// A timeout from the local API sidecar looks identical to the user, so a
|
||||
// throw is retried exactly like an empty result.
|
||||
it("retries after a thrown error", async () => {
|
||||
const resolve = vi
|
||||
.fn<() => Promise<SongUrlResult | null>>()
|
||||
.mockRejectedValueOnce(new Error("ECONNRESET"))
|
||||
.mockResolvedValueOnce(ok("https://cdn.example/retry.mp3"));
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
const result = await resolveUrlWithRetry({ retries: 1, resolve, sleep });
|
||||
|
||||
expect(result?.url).toBe("https://cdn.example/retry.mp3");
|
||||
expect(resolve).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("returns null when every attempt throws", async () => {
|
||||
const resolve = vi.fn(async () => {
|
||||
throw new Error("boom");
|
||||
});
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
expect(await resolveUrlWithRetry({ retries: 2, resolve, sleep })).toBeNull();
|
||||
expect(resolve).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("does not start when already cancelled", async () => {
|
||||
const resolve = vi.fn(async () => ok());
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 3,
|
||||
resolve,
|
||||
isCancelled: () => true,
|
||||
sleep: async () => {},
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
expect(resolve).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Stopping mid-budget must not keep hammering the API for a track nobody
|
||||
// wants any more.
|
||||
it("aborts after cancellation during the backoff", async () => {
|
||||
const resolve = vi.fn(async () => null);
|
||||
let cancelled = false;
|
||||
const sleep = async () => {
|
||||
cancelled = true; // user hit stop while we waited
|
||||
};
|
||||
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 3,
|
||||
resolve,
|
||||
isCancelled: () => cancelled,
|
||||
sleep,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(resolve).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reports every failed attempt once, with the error when there was one", async () => {
|
||||
const failures: Array<{ attempt: number; total: number; error?: unknown }> = [];
|
||||
const boom = new Error("boom");
|
||||
const resolve = vi
|
||||
.fn<() => Promise<SongUrlResult | null>>()
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockRejectedValueOnce(boom)
|
||||
.mockResolvedValueOnce(null);
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
await resolveUrlWithRetry({
|
||||
retries: 2,
|
||||
resolve,
|
||||
sleep,
|
||||
onAttemptFailed: (info) => failures.push(info),
|
||||
});
|
||||
|
||||
expect(failures).toHaveLength(3);
|
||||
expect(failures[0]).toEqual({ attempt: 1, total: 3, error: undefined });
|
||||
expect(failures[1]).toEqual({ attempt: 2, total: 3, error: boom });
|
||||
expect(failures[2]).toEqual({ attempt: 3, total: 3, error: undefined });
|
||||
});
|
||||
|
||||
it("does not report a failure for the attempt that succeeded", async () => {
|
||||
const onAttemptFailed = vi.fn();
|
||||
const resolve = vi
|
||||
.fn<() => Promise<SongUrlResult | null>>()
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce(ok());
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
await resolveUrlWithRetry({ retries: 1, resolve, sleep, onAttemptFailed });
|
||||
|
||||
expect(onAttemptFailed).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("honours a custom backoff", async () => {
|
||||
const { sleep, delays } = recordingSleep();
|
||||
await resolveUrlWithRetry({
|
||||
retries: 2,
|
||||
backoffMs: 10,
|
||||
resolve: async () => null,
|
||||
sleep,
|
||||
});
|
||||
expect(delays).toEqual([10, 20]);
|
||||
});
|
||||
|
||||
// An empty-string URL is as useless as null: the player would fail later.
|
||||
it("treats a result without a url as a failure", async () => {
|
||||
const resolve = vi
|
||||
.fn<() => Promise<SongUrlResult | null>>()
|
||||
.mockResolvedValueOnce({ url: "" })
|
||||
.mockResolvedValueOnce(ok());
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
const result = await resolveUrlWithRetry({ retries: 1, resolve, sleep });
|
||||
expect(result?.url).toBe(ok().url);
|
||||
expect(resolve).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Quality fallback
|
||||
//
|
||||
// Regression for «点四五次才能播»: NetEase's ladder is discontinuous, so a
|
||||
// track that plays at 192k can return null at BOTH 320k (the default) and 128k.
|
||||
// Retrying the same level can never fix that — the level has to change.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("resolveUrlWithRetry — quality fallback", () => {
|
||||
it("sweeps the fallback levels after the primary budget is spent", async () => {
|
||||
const seen: Array<string | undefined> = [];
|
||||
const resolve = vi.fn(async (quality?: string) => {
|
||||
seen.push(quality);
|
||||
// Only "higher" ever works; the configured level never does.
|
||||
return quality === "higher" ? ok("https://cdn.example/192.mp3") : null;
|
||||
});
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 1,
|
||||
resolve,
|
||||
fallbacks: ["higher", "standard"],
|
||||
sleep,
|
||||
});
|
||||
|
||||
expect(result?.url).toBe("https://cdn.example/192.mp3");
|
||||
// primary, primary retry, then higher — and stops there.
|
||||
expect(seen).toEqual([undefined, undefined, "higher"]);
|
||||
});
|
||||
|
||||
it("tries every fallback in order when none of them work", async () => {
|
||||
const seen: Array<string | undefined> = [];
|
||||
const resolve = vi.fn(async (quality?: string) => {
|
||||
seen.push(quality);
|
||||
return null;
|
||||
});
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 1,
|
||||
resolve,
|
||||
fallbacks: ["higher", "standard"],
|
||||
sleep,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(seen).toEqual([undefined, undefined, "higher", "standard"]);
|
||||
});
|
||||
|
||||
it("does not touch fallbacks when the configured level succeeds", async () => {
|
||||
const resolve = vi.fn(async () => ok());
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
await resolveUrlWithRetry({ retries: 3, resolve, fallbacks: ["higher"], sleep });
|
||||
|
||||
expect(resolve).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// A level switch is a different request, so it must not wait out a full
|
||||
// same-quality backoff — otherwise a broken 320k track stalls for seconds.
|
||||
it("uses the short switch delay between levels", async () => {
|
||||
const { sleep, delays } = recordingSleep();
|
||||
await resolveUrlWithRetry({
|
||||
retries: 1,
|
||||
resolve: async () => null,
|
||||
fallbacks: ["higher", "standard"],
|
||||
sleep,
|
||||
});
|
||||
expect(delays).toEqual([
|
||||
DEFAULT_URL_RETRY_BACKOFF_MS, // primary → primary retry
|
||||
QUALITY_SWITCH_BACKOFF_MS, // retry → higher
|
||||
QUALITY_SWITCH_BACKOFF_MS, // higher → standard
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports which quality each failed attempt used", async () => {
|
||||
const failures: Array<{ quality?: string }> = [];
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
await resolveUrlWithRetry({
|
||||
retries: 0,
|
||||
resolve: async () => null,
|
||||
fallbacks: ["higher", "standard"],
|
||||
sleep,
|
||||
onAttemptFailed: (info) => failures.push(info),
|
||||
});
|
||||
|
||||
expect(failures.map((f) => f.quality)).toEqual([undefined, "higher", "standard"]);
|
||||
});
|
||||
|
||||
it("still works when no fallbacks are supplied", async () => {
|
||||
const resolve = vi.fn(async () => null);
|
||||
const { sleep } = recordingSleep();
|
||||
const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep });
|
||||
expect(result).toBeNull();
|
||||
expect(resolve).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("aborts mid-sweep when the caller is cancelled", async () => {
|
||||
const resolve = vi.fn(async () => null);
|
||||
let cancelled = false;
|
||||
const sleep = async () => {
|
||||
cancelled = true;
|
||||
};
|
||||
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 0,
|
||||
resolve,
|
||||
fallbacks: ["higher", "standard"],
|
||||
isCancelled: () => cancelled,
|
||||
sleep,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(resolve).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// NetEase risk control (-460)
|
||||
//
|
||||
// Measured against a live host: `GET /song/url/v1?id=…&level=exhigh` without
|
||||
// the account cookie answers 400 `{"code":-460,"message":"检测到您的网络环境存在
|
||||
// 风险,请稍后再试"}` every single time, while the same call WITH the cookie
|
||||
// answers 200. Intermittently it also rejects the cookie call — that is the
|
||||
// "click play five times until it works" report.
|
||||
//
|
||||
// Because -460 is a 400, the normal 250ms re-poke lands inside the same risk
|
||||
// window and the whole budget is wasted. These tests pin the longer wait.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("resolveUrlWithRetry — risk control backoff", () => {
|
||||
it("retries once after RISK_CONTROL_BACKOFF_MS, then stops", async () => {
|
||||
const { sleep, delays } = recordingSleep();
|
||||
const resolve = vi.fn(async () => {
|
||||
throw new RiskControlError("网络环境风险 (-460)");
|
||||
});
|
||||
const result = await resolveUrlWithRetry({ retries: 2, resolve, sleep });
|
||||
|
||||
expect(result).toBeNull();
|
||||
// One request plus exactly one retry. The old shape waited 2.5s and then
|
||||
// 7.5s, spending three requests to reach the same "still blocked".
|
||||
expect(resolve).toHaveBeenCalledTimes(2);
|
||||
expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS]);
|
||||
// Still far longer than a plain transient retry would have waited.
|
||||
expect(delays[0]).toBeGreaterThan(DEFAULT_URL_RETRY_BACKOFF_MS);
|
||||
});
|
||||
|
||||
it("caps the budget at two requests regardless of retries, and skips the ladder", async () => {
|
||||
let attempts = 0;
|
||||
const { sleep, delays } = recordingSleep();
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 5,
|
||||
resolve: async () => {
|
||||
attempts += 1;
|
||||
throw new RiskControlError("网络环境风险 (-460)");
|
||||
},
|
||||
fallbacks: ["higher", "standard"],
|
||||
sleep,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
// -460 ignores which level we ask for, so neither the extra configured
|
||||
// retries nor the two ladder steps are worth sending: each one only adds
|
||||
// silence before the same failure surfaces.
|
||||
expect(attempts).toBe(2);
|
||||
expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS]);
|
||||
});
|
||||
|
||||
it("still walks the ladder when the risk control clears on a retry", async () => {
|
||||
// First attempt blocked by the IP, second one just has no URL — the cause
|
||||
// changed, so a lower level is worth trying again.
|
||||
let attempts = 0;
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 1,
|
||||
resolve: async (quality) => {
|
||||
attempts += 1;
|
||||
if (attempts === 1) throw new RiskControlError("网络环境风险 (-460)");
|
||||
if (quality === "standard") return ok("https://cdn.example/128k.mp3");
|
||||
return null;
|
||||
},
|
||||
fallbacks: ["higher", "standard"],
|
||||
sleep: async () => {},
|
||||
});
|
||||
|
||||
expect(result?.url).toBe("https://cdn.example/128k.mp3");
|
||||
// 2 same-quality attempts, then both ladder steps — the second attempt was a
|
||||
// plain miss, not -460, so the cap no longer applies and the ladder keeps
|
||||
// its normal cost.
|
||||
expect(attempts).toBe(4);
|
||||
});
|
||||
|
||||
it("recovers on the single retry and stops spending", async () => {
|
||||
let attempts = 0;
|
||||
const { sleep, delays } = recordingSleep();
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 3,
|
||||
resolve: async () => {
|
||||
attempts += 1;
|
||||
if (attempts < 2) throw new RiskControlError("网络环境风险 (-460)");
|
||||
return ok("https://cdn.example/after-window.mp3");
|
||||
},
|
||||
sleep,
|
||||
});
|
||||
|
||||
expect(result?.url).toBe("https://cdn.example/after-window.mp3");
|
||||
expect(attempts).toBe(2);
|
||||
expect(delays).toEqual([RISK_CONTROL_BACKOFF_MS]);
|
||||
});
|
||||
|
||||
it("still uses the short delay for a plain error", async () => {
|
||||
const { sleep, delays } = recordingSleep();
|
||||
await resolveUrlWithRetry({
|
||||
retries: 1,
|
||||
resolve: async () => {
|
||||
throw new Error("boom");
|
||||
},
|
||||
sleep,
|
||||
});
|
||||
expect(delays).toEqual([DEFAULT_URL_RETRY_BACKOFF_MS]);
|
||||
});
|
||||
|
||||
it("cancels during a risk-control wait", async () => {
|
||||
let cancelled = false;
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 3,
|
||||
resolve: async () => {
|
||||
throw new RiskControlError("网络环境风险 (-460)");
|
||||
},
|
||||
isCancelled: () => cancelled,
|
||||
sleep: async () => {
|
||||
cancelled = true;
|
||||
},
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reporting why the budget ran out
|
||||
//
|
||||
// The caller needs a cause, not just `null`: the web layer used to print
|
||||
// 「无法播放(区域/版权限制)」 for every outcome, including a lapsed membership and
|
||||
// a quality the account cannot stream. `onExhausted` is how the cause survives
|
||||
// the retry loop.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("resolveUrlWithRetry — reporting the cause", () => {
|
||||
function unavailable(code: any, message = "某原因") {
|
||||
return new SongUrlUnavailable({ platform: "netease", songId: "1", code, message });
|
||||
}
|
||||
|
||||
it("hands back the last error once the budget is spent", async () => {
|
||||
const seen: Array<{ quality?: string; error: unknown }> = [];
|
||||
const err = unavailable("vip_required");
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 2,
|
||||
resolve: async () => {
|
||||
throw err;
|
||||
},
|
||||
sleep,
|
||||
onExhausted: (info) => seen.push(info),
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(seen).toHaveLength(1);
|
||||
expect(seen[0].error).toBe(err);
|
||||
expect(toPlayFailure("netease", "1", seen[0].error).code).toBe("vip_required");
|
||||
});
|
||||
|
||||
it("reports the level it gave up on, not the first one", async () => {
|
||||
const seen: Array<{ quality?: string; error: unknown }> = [];
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
await resolveUrlWithRetry({
|
||||
retries: 0,
|
||||
resolve: async (quality) => {
|
||||
if (quality === "standard") throw unavailable("quality_denied");
|
||||
return null;
|
||||
},
|
||||
fallbacks: ["higher", "standard"],
|
||||
sleep,
|
||||
onExhausted: (info) => seen.push(info),
|
||||
});
|
||||
|
||||
expect(seen[0].quality).toBe("standard");
|
||||
});
|
||||
|
||||
it("stays silent when a level finally works", async () => {
|
||||
const seen: unknown[] = [];
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
const result = await resolveUrlWithRetry({
|
||||
retries: 1,
|
||||
resolve: async (quality) => {
|
||||
if (quality === "higher") return ok();
|
||||
throw unavailable("quality_denied");
|
||||
},
|
||||
fallbacks: ["higher"],
|
||||
sleep,
|
||||
onExhausted: (info) => seen.push(info),
|
||||
});
|
||||
|
||||
expect(result?.url).toBeTruthy();
|
||||
expect(seen).toHaveLength(0);
|
||||
});
|
||||
|
||||
// Pressing stop is not a failure. Reporting one would flash an error toast at
|
||||
// a user who just changed their mind.
|
||||
it("stays silent when the caller cancels", async () => {
|
||||
const seen: unknown[] = [];
|
||||
let cancelled = false;
|
||||
|
||||
await resolveUrlWithRetry({
|
||||
retries: 3,
|
||||
resolve: async () => {
|
||||
throw unavailable("risk_control");
|
||||
},
|
||||
isCancelled: () => cancelled,
|
||||
sleep: async () => {
|
||||
cancelled = true;
|
||||
},
|
||||
onExhausted: (info) => seen.push(info),
|
||||
});
|
||||
|
||||
expect(seen).toHaveLength(0);
|
||||
});
|
||||
|
||||
// Providers that have not adopted SongUrlUnavailable still return null.
|
||||
it("still reports for a provider that returns null without throwing", async () => {
|
||||
const seen: Array<{ quality?: string; error: unknown }> = [];
|
||||
const { sleep } = recordingSleep();
|
||||
|
||||
await resolveUrlWithRetry({
|
||||
retries: 0,
|
||||
resolve: async () => null,
|
||||
sleep,
|
||||
onExhausted: (info) => seen.push(info),
|
||||
});
|
||||
|
||||
expect(seen).toHaveLength(1);
|
||||
expect(seen[0].error).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import { RiskControlError } from "../music/provider.js";
|
||||
import type { SongUrlResult } from "../music/provider.js";
|
||||
|
||||
/**
|
||||
* Silent re-resolve of a playable URL.
|
||||
*
|
||||
* Two different failure modes look identical to the user but need different
|
||||
* treatment, so this handles both inside one request:
|
||||
*
|
||||
* 1. **Transient** — NetEase intermittently answers `url: null` for a song that
|
||||
* resolves fine a moment later. Repeating the SAME request fixes it.
|
||||
* 2. **Quality gap** — some tracks have no URL at the configured level while a
|
||||
* different level works. Measured against a real library: a track can be
|
||||
* playable at "higher" (192k) while BOTH "exhigh" (320k) and "standard"
|
||||
* (128k) return null, so a single "drop to the cheapest" step is not enough
|
||||
* — every level below the current one has to be tried.
|
||||
*
|
||||
* Without either, the user saw 「无法播放(区域/版权限制)」 and had to click play
|
||||
* repeatedly until it happened to work.
|
||||
*
|
||||
* Kept as a standalone function (not a BotInstance method) so the behaviour is
|
||||
* testable without booting a bot, and so every caller — web click, chat !play,
|
||||
* auto-advance, FM — gets the same budget by construction.
|
||||
*/
|
||||
|
||||
/** Upper bound on retries per quality level, whatever the config says. */
|
||||
export const MAX_URL_RETRIES = 5;
|
||||
|
||||
/** Default delay before retrying the SAME quality; grows linearly (250, 500 …). */
|
||||
export const DEFAULT_URL_RETRY_BACKOFF_MS = 250;
|
||||
|
||||
/**
|
||||
* Delay before the first attempt at the next quality level. Much shorter than a
|
||||
* same-quality retry: switching level is a different request, not a re-poke of
|
||||
* the same one, so it does not need to wait out the same jitter window.
|
||||
*/
|
||||
export const QUALITY_SWITCH_BACKOFF_MS = 120;
|
||||
|
||||
/**
|
||||
* Delay before the single retry that follows a -460 (NetEase IP risk control).
|
||||
*
|
||||
* This is the one failure mode where the delay is NOT cosmetic: the upstream
|
||||
* has decided the caller's address looks risky and will keep answering 400 for
|
||||
* a few seconds no matter what we ask. Re-poking after 250ms just burns the
|
||||
* budget inside the same window.
|
||||
*
|
||||
* Sized against what the window actually looks like: a live host answered
|
||||
* `-460, -460, -460, -460, 200` on six consecutive 128k requests with no
|
||||
* waiting at all, i.e. it is "let a few of these through, then stop caring"
|
||||
* rather than a hard timer. So 2.5s is a good bet for one retry, and waiting
|
||||
* longer is not: it buys nothing the user cannot do themselves.
|
||||
*/
|
||||
export const RISK_CONTROL_BACKOFF_MS = 2500;
|
||||
|
||||
/**
|
||||
* Hard ceiling on requests sent while the IP is risk controlled (1 + 1 retry).
|
||||
*
|
||||
* The previous shape grew the delay per attempt (2.5s, then 7.5s), which meant
|
||||
* up to 10s of a spinner doing nothing before the same error appeared. Measured
|
||||
* behaviour says a blocked address either clears within a couple of seconds or
|
||||
* stays blocked; the third and later attempts only add silence. Spending two
|
||||
* requests and then telling the user to wait ~5s is both faster and honest.
|
||||
*/
|
||||
export const MAX_RISK_CONTROL_REQUESTS = 2;
|
||||
|
||||
/**
|
||||
* Normalise a config value into a usable retry count.
|
||||
* Anything non-numeric (legacy config, `"3"`, `null`) means "no retries", which
|
||||
* keeps the pre-existing fail-fast behaviour for callers that pass garbage.
|
||||
*/
|
||||
export function normalizeRetryCount(value: unknown): number {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) return 0;
|
||||
return Math.min(MAX_URL_RETRIES, Math.max(0, Math.trunc(value)));
|
||||
}
|
||||
|
||||
export interface ResolveUrlWithRetryOptions {
|
||||
/** Extra attempts per quality level after the first. 0 = one attempt each. */
|
||||
retries: unknown;
|
||||
/** Resolve one URL. `undefined` means "the provider's configured quality". */
|
||||
resolve: (quality?: string) => Promise<SongUrlResult | null>;
|
||||
/**
|
||||
* Lower quality levels to sweep after the primary budget is spent, best→worst.
|
||||
* Typically `provider.getFallbackQualities?.()`.
|
||||
*/
|
||||
fallbacks?: string[];
|
||||
/** Checked before every attempt — stop / disconnect aborts the budget. */
|
||||
isCancelled?: () => boolean;
|
||||
backoffMs?: number;
|
||||
/** Called once per failed attempt (logging hook). */
|
||||
onAttemptFailed?: (info: {
|
||||
attempt: number;
|
||||
total: number;
|
||||
quality?: string;
|
||||
error?: unknown;
|
||||
}) => void;
|
||||
/**
|
||||
* Called once when the budget is spent — never on cancellation, because
|
||||
* "the user pressed stop" is not a failure worth reporting.
|
||||
*
|
||||
* Carries the last attempt's error so the caller can turn it into a message
|
||||
* that names the cause (missing membership, delisted, blocked quality) rather
|
||||
* than the old catch-all 「区域/版权限制」.
|
||||
*/
|
||||
onExhausted?: (info: { quality?: string; error: unknown }) => void;
|
||||
/** Injectable for tests. */
|
||||
sleep?: (ms: number) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first successful result, or null once every level is exhausted.
|
||||
*
|
||||
* Request count: `(1 + retries)` at the configured quality, then one per
|
||||
* fallback level. With the defaults (2 retries, exhigh, NetEase's two lower
|
||||
* levels) that is at most 5 requests and ~1.1s of waiting — or 2 requests and
|
||||
* 2.5s when the IP is risk controlled, which is the one case where waiting
|
||||
* more cannot help.
|
||||
*/
|
||||
export async function resolveUrlWithRetry(
|
||||
opts: ResolveUrlWithRetryOptions,
|
||||
): Promise<SongUrlResult | null> {
|
||||
const retries = normalizeRetryCount(opts.retries);
|
||||
const backoffMs = opts.backoffMs ?? DEFAULT_URL_RETRY_BACKOFF_MS;
|
||||
const sleep =
|
||||
opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
|
||||
|
||||
// Phase 1: the configured quality (1 + retries attempts).
|
||||
// Phase 2: every lower level, once each, so a discontinuous ladder is covered.
|
||||
const plan: Array<{ quality?: string; fallback: boolean }> = [];
|
||||
for (let i = 0; i <= retries; i++) plan.push({ quality: undefined, fallback: false });
|
||||
for (const quality of opts.fallbacks ?? []) plan.push({ quality, fallback: true });
|
||||
|
||||
let sameQualityAttempt = 0;
|
||||
// Set when the previous attempt failed with -460. Risk control ignores the
|
||||
// quality we ask for, so a level switch does not get to use its short delay.
|
||||
let riskControlled = false;
|
||||
// Requests actually sent. Only consulted while risk controlled, where the
|
||||
// budget is capped at MAX_RISK_CONTROL_REQUESTS instead of the configured
|
||||
// retry count.
|
||||
let requestsMade = 0;
|
||||
// The last failure, kept so the caller can explain the outcome. A `null`
|
||||
// result (no throw) counts too — it is the providers that have not adopted
|
||||
// SongUrlUnavailable yet.
|
||||
let lastError: unknown;
|
||||
let lastQuality: string | undefined;
|
||||
|
||||
for (let i = 0; i < plan.length; i++) {
|
||||
const step = plan[i];
|
||||
if (opts.isCancelled?.()) return null;
|
||||
|
||||
// -460 is an IP-level refusal, not a property of this track: the quality we
|
||||
// ask for is irrelevant to it, so stepping down the ladder cannot succeed
|
||||
// and each extra step only adds silence. Stop after one retry instead of
|
||||
// when the plan runs out — the caller reports "try again in a few seconds",
|
||||
// which is something the user can act on, unlike a longer spinner.
|
||||
if (riskControlled && (step.fallback || requestsMade >= MAX_RISK_CONTROL_REQUESTS)) break;
|
||||
|
||||
if (i > 0) {
|
||||
const wait = riskControlled
|
||||
? RISK_CONTROL_BACKOFF_MS
|
||||
: step.fallback
|
||||
? QUALITY_SWITCH_BACKOFF_MS
|
||||
: backoffMs * sameQualityAttempt;
|
||||
if (wait > 0) await sleep(wait);
|
||||
// The user may have stopped or switched tracks while we waited.
|
||||
if (opts.isCancelled?.()) return null;
|
||||
}
|
||||
|
||||
let error: unknown;
|
||||
requestsMade += 1;
|
||||
let result: SongUrlResult | null = null;
|
||||
try {
|
||||
result = await opts.resolve(step.quality);
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
if (opts.isCancelled?.()) return null;
|
||||
if (result?.url) return result;
|
||||
riskControlled = error instanceof RiskControlError;
|
||||
lastError = error;
|
||||
lastQuality = step.quality;
|
||||
opts.onAttemptFailed?.({ attempt: i + 1, total: plan.length, quality: step.quality, error });
|
||||
// Only same-quality attempts grow the backoff; a level switch resets it.
|
||||
sameQualityAttempt = step.fallback ? 0 : sameQualityAttempt + 1;
|
||||
}
|
||||
|
||||
opts.onExhausted?.({ quality: lastQuality, error: lastError });
|
||||
return null;
|
||||
}
|
||||
@@ -65,9 +65,17 @@ describe("BotInstance persistent voice send failure", () => {
|
||||
expect(frames).toBe(50);
|
||||
h.tsClient.emit("voiceSendFailed", { consecutiveFailures: 100, durationMs: 2000 });
|
||||
vi.advanceTimersByTime(3000);
|
||||
expect(frames).toBe(50);
|
||||
expect(h.player.getElapsed()).toBe(1);
|
||||
// Pausing emits a short de-click fade tail (pauseFrames) so the last
|
||||
// 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");
|
||||
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(); }
|
||||
});
|
||||
|
||||
|
||||
@@ -130,6 +130,13 @@ export interface BotConfig {
|
||||
* persisted/restored until an operator opts in.
|
||||
*/
|
||||
savedQueuesEnabled: boolean;
|
||||
/**
|
||||
* Per-user music accounts (admin-controlled, default false). When on, a web
|
||||
* user who linked their own platform account (Settings → 我的音乐账号) reads
|
||||
* search results, playlists and recommendations through their linked account
|
||||
* or an account assigned by an admin. Room playback uses the shared account.
|
||||
*/
|
||||
perUserMusicAccounts: boolean;
|
||||
/**
|
||||
* When true, a single-song immediate !play (chat) / play-song (web) inserts
|
||||
* after the current track and jumps to it instead of clearing the queue, so
|
||||
@@ -137,6 +144,19 @@ export interface BotConfig {
|
||||
* keeps today's clear-and-play behavior.
|
||||
*/
|
||||
playKeepsQueue: boolean;
|
||||
/**
|
||||
* Extra attempts to re-resolve a playable URL before a track is reported as
|
||||
* unplayable.
|
||||
*
|
||||
* NetEase intermittently answers `url: null` for a song that resolves fine a
|
||||
* second later (upstream risk-control / edge jitter), which users experienced
|
||||
* as "click once → 无法播放(区域/版权限制), click again → works". Retrying
|
||||
* silently inside one request turns that into a normal play.
|
||||
*
|
||||
* 0 disables retries (fail fast, pre-existing behaviour). Clamped to 0..5 so
|
||||
* a hand-edited config cannot turn every failed track into a long stall.
|
||||
*/
|
||||
playUrlRetries: number;
|
||||
// Public base URL used when generating share links (e.g. the bot专属链接).
|
||||
// Leave empty to use the browser's current origin. Example:
|
||||
// "https://music.example.com" or "http://1.2.3.4:3000"
|
||||
@@ -191,7 +211,11 @@ export function getDefaultConfig(): BotConfig {
|
||||
idleTimeoutMinutes: 0,
|
||||
localAudioEnabled: true,
|
||||
savedQueuesEnabled: false,
|
||||
perUserMusicAccounts: false,
|
||||
playKeepsQueue: false,
|
||||
// Two extra attempts: enough to ride out a transient NetEase hiccup without
|
||||
// making a genuinely unlicensed track feel stuck (~1s of backoff total).
|
||||
playUrlRetries: 2,
|
||||
publicUrl: "",
|
||||
trustProxy: false,
|
||||
guestMode: {
|
||||
@@ -394,6 +418,19 @@ export function loadConfig(path: string): BotConfig {
|
||||
// them (`"yes"`, `1`, `null` → false; only a literal `true` enables).
|
||||
const savedQueuesEnabled = partial.savedQueuesEnabled === true;
|
||||
const playKeepsQueue = partial.playKeepsQueue === true;
|
||||
// Same strict-coercion rule: a legacy config without the key, or a
|
||||
// hand-edited `"yes"`/`1`, must never turn account isolation on by accident.
|
||||
const perUserMusicAccounts = partial.perUserMusicAccounts === true;
|
||||
|
||||
// Play-URL retry budget. Anything non-numeric (legacy config, `"3"`,
|
||||
// `null`) falls back to the default instead of disabling the retry, because
|
||||
// "no retries" is the surprising outcome here — the feature exists to hide
|
||||
// upstream flakiness from users.
|
||||
const rawRetries = partial.playUrlRetries;
|
||||
const playUrlRetries =
|
||||
typeof rawRetries === "number" && Number.isFinite(rawRetries)
|
||||
? Math.min(5, Math.max(0, Math.trunc(rawRetries)))
|
||||
: defaults.playUrlRetries;
|
||||
|
||||
// Voice ducking is opt-in and the retained-volume percentage is consumed
|
||||
// directly by the audio path. Only a plain-object block with correctly
|
||||
@@ -456,7 +493,9 @@ export function loadConfig(path: string): BotConfig {
|
||||
audioQuality,
|
||||
enabledProviders,
|
||||
savedQueuesEnabled,
|
||||
perUserMusicAccounts,
|
||||
playKeepsQueue,
|
||||
playUrlRetries,
|
||||
voiceDucking,
|
||||
defaultPlatform: defaultPlatformPref,
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import Database from "better-sqlite3";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { CAPABILITIES, BOTS_ALL } from "./permissions.js";
|
||||
import { GUEST_USER_ID, GUEST_USERNAME } from "./users.js";
|
||||
import type { QueuedSong } from "../audio/queue.js";
|
||||
@@ -126,10 +127,62 @@ export interface FavoritePlaylist {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A music-platform login the ADMIN owns and may hand out to members
|
||||
* (`perUserMusicAccounts`, #164 follow-up).
|
||||
*
|
||||
* Two separate tables, on purpose:
|
||||
* - `music_accounts` = the pool. Only the admin writes it.
|
||||
* - `music_account_grants` = "member X may use account Y".
|
||||
*
|
||||
* Keeping grants out of `user_music_cookies` is what makes "self-linked beats
|
||||
* admin-granted" possible: a member scanning their own QR code must not
|
||||
* silently overwrite (or be overwritten by) an account the admin assigned, and
|
||||
* unlinking on the member side must never revoke what the admin granted.
|
||||
*
|
||||
* `cookie` is server-side only — the API layer masks it before answering.
|
||||
*/
|
||||
export interface MusicAccount {
|
||||
id: string;
|
||||
platform: string;
|
||||
/** Admin-facing name ("网易云-主号"). Members see this instead of a nickname. */
|
||||
label: string;
|
||||
cookie: string;
|
||||
/** Who provided the login; null = imported from the bot's shared login. */
|
||||
ownerId: string | null;
|
||||
/** 0 = any number of grantees, 1 = exclusive (one member at a time). */
|
||||
capacity: number;
|
||||
enabled: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** One row of `music_account_grants`, joined with display fields for the UI. */
|
||||
export interface MusicAccountGrant {
|
||||
userId: string;
|
||||
username: string;
|
||||
platform: string;
|
||||
accountId: string;
|
||||
accountLabel: string;
|
||||
grantedBy: string;
|
||||
grantedAt: string;
|
||||
}
|
||||
|
||||
/** An account resolved FOR a user: what provider-scope needs to build a view. */
|
||||
export interface GrantedMusicAccount {
|
||||
accountId: string;
|
||||
label: string;
|
||||
cookie: string;
|
||||
}
|
||||
|
||||
export interface BotDatabase {
|
||||
db: Database.Database;
|
||||
addPlayHistory(entry: PlayHistoryEntry): void;
|
||||
getPlayHistory(botId: string, limit: number): PlayHistoryRecord[];
|
||||
/** Deletes the given history rows (by primary key) for one bot. Returns affected rows. */
|
||||
deletePlayHistory(botId: string, ids: number[]): number;
|
||||
/** Deletes every history row of one bot. Returns affected rows. */
|
||||
clearPlayHistory(botId: string): number;
|
||||
saveBotInstance(instance: BotInstance): void;
|
||||
getBotInstances(): BotInstance[];
|
||||
deleteBotInstance(id: string): boolean;
|
||||
@@ -148,6 +201,54 @@ export interface BotDatabase {
|
||||
getUserMusicCookie(userId: string, platform: string): string | null;
|
||||
setUserMusicCookie(userId: string, platform: string, cookie: string): void;
|
||||
deleteUserMusicCookie(userId: string, platform: string): boolean;
|
||||
/** null when the member never chose; callers treat that as "prefer own". */
|
||||
getUserMusicPreference(userId: string, platform: string): { preferShared: boolean } | null;
|
||||
setUserMusicPreference(userId: string, platform: string, preferShared: boolean): void;
|
||||
// Admin-owned account pool + assignments (#164 follow-up).
|
||||
listMusicAccounts(platform?: string): MusicAccount[];
|
||||
getMusicAccount(id: string): MusicAccount | null;
|
||||
createMusicAccount(input: {
|
||||
platform: string;
|
||||
label: string;
|
||||
cookie: string;
|
||||
ownerId?: string | null;
|
||||
capacity?: number;
|
||||
enabled?: boolean;
|
||||
}): MusicAccount;
|
||||
/**
|
||||
* Partial update; false when the id does not exist or the capacity is too low.
|
||||
*
|
||||
* `platform` is intentionally NOT patchable: grants are keyed by
|
||||
* (userId, platform) while pointing at `accountId`, so moving an account to
|
||||
* another platform would silently orphan every existing assignment (the
|
||||
* grant would still say "netease" while the account says "qq"). Re-create the
|
||||
* account instead — that path preserves the invariant.
|
||||
*/
|
||||
updateMusicAccount(
|
||||
id: string,
|
||||
patch: Partial<Pick<MusicAccount, "label" | "cookie" | "capacity" | "enabled">>,
|
||||
): boolean;
|
||||
/** Removes the account AND every grant pointing at it (FK cascade). */
|
||||
deleteMusicAccount(id: string): boolean;
|
||||
countMusicAccountGrants(accountId: string): number;
|
||||
listMusicAccountGrants(accountId: string): MusicAccountGrant[];
|
||||
/** Every grant, grouped for the admin overview page. */
|
||||
listAllMusicAccountGrants(): MusicAccountGrant[];
|
||||
/**
|
||||
* Assign `accountId` to `userId`, enforcing enabled/capacity in ONE
|
||||
* transaction so two concurrent assignments cannot both pass the capacity
|
||||
* check and overshoot an exclusive account.
|
||||
*/
|
||||
assignMusicAccount(
|
||||
userId: string,
|
||||
accountId: string,
|
||||
grantedBy: string,
|
||||
):
|
||||
| { ok: true; replacedAccountId: string | null }
|
||||
| { ok: false; reason: "not_found" | "disabled" | "exclusive" | "full" };
|
||||
deleteMusicAccountGrant(userId: string, platform: string, accountId: string): boolean;
|
||||
/** The account an admin assigned to `userId`, or null. Disabled accounts are skipped. */
|
||||
getGrantedMusicAccount(userId: string, platform: string): GrantedMusicAccount | null;
|
||||
// Saved queues (Feature 1) — upsert by (ownerId, name), capped.
|
||||
saveQueue(ownerId: string, name: string, songs: StoredSong[]): SavedQueue;
|
||||
listSavedQueues(ownerId: string, includeShared: boolean): SavedQueueMeta[];
|
||||
@@ -358,6 +459,52 @@ function initTables(db: Database.Database): void {
|
||||
PRIMARY KEY (userId, platform),
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Which login a member wants to use for a platform (#164 follow-up).
|
||||
-- preferShared = 1 means "ignore my own / assigned account and play
|
||||
-- through the bot's shared login", which is how someone whose own account
|
||||
-- has no membership still gets to play paid tracks. Default 0 keeps the
|
||||
-- privacy-first behaviour (own account wins).
|
||||
CREATE TABLE IF NOT EXISTS user_music_prefs (
|
||||
userId TEXT NOT NULL,
|
||||
platform TEXT NOT NULL,
|
||||
preferShared INTEGER NOT NULL DEFAULT 0,
|
||||
updatedAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (userId, platform),
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Admin-owned music logins that can be handed out to members (#164
|
||||
-- follow-up). Separate from user_music_cookies so a member's own QR login
|
||||
-- and an admin's assignment never overwrite each other.
|
||||
CREATE TABLE IF NOT EXISTS music_accounts (
|
||||
id TEXT PRIMARY KEY,
|
||||
platform TEXT NOT NULL,
|
||||
label TEXT NOT NULL,
|
||||
cookie TEXT NOT NULL,
|
||||
ownerId TEXT,
|
||||
capacity INTEGER NOT NULL DEFAULT 0,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
createdAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updatedAt TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_music_accounts_platform ON music_accounts(platform);
|
||||
|
||||
-- "member X may use account Y". PK (userId, platform) = at most one
|
||||
-- assigned account per platform per member; assigning another replaces it.
|
||||
-- accountId cascade keeps a deleted account from leaving dangling grants.
|
||||
CREATE TABLE IF NOT EXISTS music_account_grants (
|
||||
userId TEXT NOT NULL,
|
||||
platform TEXT NOT NULL,
|
||||
accountId TEXT NOT NULL,
|
||||
grantedBy TEXT NOT NULL,
|
||||
grantedAt TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (userId, platform),
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (accountId) REFERENCES music_accounts(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_music_account_grants_accountId
|
||||
ON music_account_grants(accountId);
|
||||
`);
|
||||
}
|
||||
|
||||
@@ -416,6 +563,10 @@ export function createDatabase(dbPath: string): BotDatabase {
|
||||
SELECT * FROM play_history WHERE botId = ? ORDER BY id DESC LIMIT ?
|
||||
`);
|
||||
|
||||
// botId is part of every predicate so one bot can never delete another bot's rows.
|
||||
const deleteHistoryRow = db.prepare("DELETE FROM play_history WHERE botId = ? AND id = ?");
|
||||
const deleteHistoryAll = db.prepare("DELETE FROM play_history WHERE botId = ?");
|
||||
|
||||
const upsertInstance = db.prepare(`
|
||||
INSERT INTO bot_instances (id, name, serverAddress, serverPort, nickname, defaultChannel, channelId, channelPassword, autoStart, serverProtocol, ts6ApiKey, serverPassword, identity)
|
||||
VALUES (@id, @name, @serverAddress, @serverPort, @nickname, @defaultChannel, @channelId, @channelPassword, @autoStart, @serverProtocol, @ts6ApiKey, @serverPassword, @identity)
|
||||
@@ -494,6 +645,128 @@ export function createDatabase(dbPath: string): BotDatabase {
|
||||
`DELETE FROM user_music_cookies WHERE userId = ? AND platform = ?`,
|
||||
);
|
||||
|
||||
const selectUserMusicPref = db.prepare(
|
||||
`SELECT preferShared FROM user_music_prefs WHERE userId = ? AND platform = ?`,
|
||||
);
|
||||
const upsertUserMusicPref = db.prepare(`
|
||||
INSERT INTO user_music_prefs (userId, platform, preferShared) VALUES (?, ?, ?)
|
||||
ON CONFLICT(userId, platform) DO UPDATE SET preferShared = excluded.preferShared, updatedAt = datetime('now')
|
||||
`);
|
||||
|
||||
// ---- Admin-owned account pool (#164 follow-up) -------------------------
|
||||
const MUSIC_ACCOUNT_GRANT_SELECT = `
|
||||
SELECT g.userId, COALESCE(u.username, g.userId) AS username, g.platform,
|
||||
g.accountId, a.label AS accountLabel, g.grantedBy, g.grantedAt
|
||||
FROM music_account_grants g
|
||||
JOIN music_accounts a ON a.id = g.accountId
|
||||
LEFT JOIN users u ON u.id = g.userId`;
|
||||
|
||||
const selectMusicAccount = db.prepare(`SELECT * FROM music_accounts WHERE id = ?`);
|
||||
const selectMusicAccountsAll = db.prepare(
|
||||
`SELECT * FROM music_accounts ORDER BY platform ASC, createdAt ASC`,
|
||||
);
|
||||
const selectMusicAccountsByPlatform = db.prepare(
|
||||
`SELECT * FROM music_accounts WHERE platform = ? ORDER BY createdAt ASC`,
|
||||
);
|
||||
const insertMusicAccount = db.prepare(`
|
||||
INSERT INTO music_accounts (id, platform, label, cookie, ownerId, capacity, enabled)
|
||||
VALUES (@id, @platform, @label, @cookie, @ownerId, @capacity, @enabled)
|
||||
`);
|
||||
const updateMusicAccountStmt = db.prepare(`
|
||||
UPDATE music_accounts
|
||||
SET platform = @platform, label = @label, cookie = @cookie,
|
||||
capacity = @capacity, enabled = @enabled, updatedAt = datetime('now')
|
||||
WHERE id = @id
|
||||
AND (@capacity = 0 OR @capacity >= (
|
||||
SELECT COUNT(*) FROM music_account_grants WHERE accountId = @id
|
||||
))
|
||||
`);
|
||||
const deleteMusicAccountStmt = db.prepare(`DELETE FROM music_accounts WHERE id = ?`);
|
||||
const countGrantsByAccount = db.prepare(
|
||||
`SELECT COUNT(*) AS c FROM music_account_grants WHERE accountId = ?`,
|
||||
);
|
||||
const selectGrantsByAccount = db.prepare(
|
||||
`${MUSIC_ACCOUNT_GRANT_SELECT} WHERE g.accountId = ? ORDER BY username ASC`,
|
||||
);
|
||||
const selectGrantsAll = db.prepare(
|
||||
`${MUSIC_ACCOUNT_GRANT_SELECT} ORDER BY g.platform ASC, username ASC`,
|
||||
);
|
||||
const upsertGrantStmt = db.prepare(`
|
||||
INSERT INTO music_account_grants (userId, platform, accountId, grantedBy)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(userId, platform) DO UPDATE SET
|
||||
accountId = excluded.accountId,
|
||||
grantedBy = excluded.grantedBy,
|
||||
grantedAt = datetime('now')
|
||||
`);
|
||||
const deleteGrantStmt = db.prepare(
|
||||
`DELETE FROM music_account_grants WHERE userId = ? AND platform = ? AND accountId = ?`,
|
||||
);
|
||||
// A disabled account is invisible to the resolver, so switching it off is an
|
||||
// instant, reversible rollback for everyone holding it (shared login returns).
|
||||
const selectGrantedAccount = db.prepare(`
|
||||
SELECT a.id AS accountId, a.label, a.cookie
|
||||
FROM music_account_grants g
|
||||
JOIN music_accounts a ON a.id = g.accountId
|
||||
WHERE g.userId = ? AND g.platform = ? AND a.enabled = 1
|
||||
`);
|
||||
|
||||
const rowToMusicAccount = (r: Record<string, unknown>): MusicAccount => ({
|
||||
id: String(r.id),
|
||||
platform: String(r.platform),
|
||||
label: String(r.label),
|
||||
cookie: String(r.cookie),
|
||||
ownerId: r.ownerId === null || r.ownerId === undefined ? null : String(r.ownerId),
|
||||
capacity: Number(r.capacity ?? 0),
|
||||
enabled: Number(r.enabled ?? 1) === 1,
|
||||
createdAt: String(r.createdAt ?? ""),
|
||||
updatedAt: String(r.updatedAt ?? ""),
|
||||
});
|
||||
|
||||
const selectGrantForUser = db.prepare(
|
||||
`SELECT accountId FROM music_account_grants WHERE userId = ? AND platform = ?`,
|
||||
);
|
||||
|
||||
/** Row → object lookup shared by the read/update paths (no `this` reliance). */
|
||||
const getAccountById = (id: string): MusicAccount | null => {
|
||||
const row = selectMusicAccount.get(id) as Record<string, unknown> | undefined;
|
||||
return row ? rowToMusicAccount(row) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Capacity check + grant write in ONE transaction. Reading the holder count
|
||||
* outside the write would let two admins assigning simultaneously both pass
|
||||
* the check and overshoot an exclusive account.
|
||||
*/
|
||||
const assignMusicAccountTx = db.transaction(
|
||||
(
|
||||
userId: string,
|
||||
accountId: string,
|
||||
grantedBy: string,
|
||||
):
|
||||
| { ok: true; replacedAccountId: string | null }
|
||||
| { ok: false; reason: "not_found" | "disabled" | "exclusive" | "full" } => {
|
||||
const row = selectMusicAccount.get(accountId) as Record<string, unknown> | undefined;
|
||||
if (!row) return { ok: false, reason: "not_found" };
|
||||
const account = rowToMusicAccount(row);
|
||||
if (!account.enabled) return { ok: false, reason: "disabled" };
|
||||
|
||||
const existing = selectGrantForUser.get(userId, account.platform) as
|
||||
| { accountId: string }
|
||||
| undefined;
|
||||
// Re-assigning the SAME account is a no-op, not a capacity conflict.
|
||||
if (existing?.accountId === account.id) return { ok: true, replacedAccountId: null };
|
||||
const replacedAccountId = existing ? existing.accountId : null;
|
||||
|
||||
const { c } = countGrantsByAccount.get(account.id) as { c: number };
|
||||
if (account.capacity === 1 && c >= 1) return { ok: false, reason: "exclusive" };
|
||||
if (account.capacity > 1 && c >= account.capacity) return { ok: false, reason: "full" };
|
||||
|
||||
upsertGrantStmt.run(userId, account.platform, account.id, grantedBy);
|
||||
return { ok: true, replacedAccountId };
|
||||
},
|
||||
);
|
||||
|
||||
// A corrupt/hand-edited songs blob must never throw into a route or the
|
||||
// restore path — degrade to an empty list instead.
|
||||
const parseSongs = (raw: string): StoredSong[] => {
|
||||
@@ -566,6 +839,22 @@ export function createDatabase(dbPath: string): BotDatabase {
|
||||
return selectHistory.all(botId, limit) as PlayHistoryRecord[];
|
||||
},
|
||||
|
||||
deletePlayHistory(botId, ids) {
|
||||
let deleted = 0;
|
||||
// Single transaction: either the whole selection goes away or nothing does.
|
||||
const tx = db.transaction((list: number[]) => {
|
||||
for (const id of list) {
|
||||
deleted += deleteHistoryRow.run(botId, id).changes;
|
||||
}
|
||||
});
|
||||
tx(ids);
|
||||
return deleted;
|
||||
},
|
||||
|
||||
clearPlayHistory(botId) {
|
||||
return deleteHistoryAll.run(botId).changes;
|
||||
},
|
||||
|
||||
saveBotInstance(instance) {
|
||||
upsertInstance.run({
|
||||
...instance,
|
||||
@@ -688,6 +977,98 @@ export function createDatabase(dbPath: string): BotDatabase {
|
||||
return deleteUserMusicCookieStmt.run(userId, platform).changes > 0;
|
||||
},
|
||||
|
||||
getUserMusicPreference(userId, platform) {
|
||||
const row = selectUserMusicPref.get(userId, platform) as
|
||||
| { preferShared: number }
|
||||
| undefined;
|
||||
if (!row) return null;
|
||||
return { preferShared: Number(row.preferShared) === 1 };
|
||||
},
|
||||
|
||||
setUserMusicPreference(userId, platform, preferShared) {
|
||||
upsertUserMusicPref.run(userId, platform, preferShared ? 1 : 0);
|
||||
},
|
||||
|
||||
listMusicAccounts(platform) {
|
||||
const rows = platform
|
||||
? (selectMusicAccountsByPlatform.all(platform) as Record<string, unknown>[])
|
||||
: (selectMusicAccountsAll.all() as Record<string, unknown>[]);
|
||||
return rows.map(rowToMusicAccount);
|
||||
},
|
||||
|
||||
getMusicAccount(id) {
|
||||
return getAccountById(id);
|
||||
},
|
||||
|
||||
createMusicAccount(input) {
|
||||
const id = randomUUID();
|
||||
insertMusicAccount.run({
|
||||
id,
|
||||
platform: input.platform,
|
||||
label: input.label,
|
||||
cookie: input.cookie,
|
||||
ownerId: input.ownerId ?? null,
|
||||
// Clamped so a negative capacity can never slip through and make the
|
||||
// "exclusive" check behave like "unlimited".
|
||||
capacity: Math.max(0, Math.trunc(input.capacity ?? 0)),
|
||||
enabled: input.enabled === false ? 0 : 1,
|
||||
});
|
||||
// No `this` hop: the factory's returned object can be destructured without
|
||||
// losing the lookup.
|
||||
return getAccountById(id)!;
|
||||
},
|
||||
|
||||
updateMusicAccount(id, patch) {
|
||||
const current = getAccountById(id);
|
||||
if (!current) return false;
|
||||
return updateMusicAccountStmt.run({
|
||||
id,
|
||||
// Platform is immutable (see the interface doc): existing grants are
|
||||
// keyed by the OLD platform and would be orphaned by a move.
|
||||
platform: current.platform,
|
||||
label: patch.label ?? current.label,
|
||||
cookie: patch.cookie ?? current.cookie,
|
||||
capacity:
|
||||
patch.capacity === undefined
|
||||
? current.capacity
|
||||
: Math.max(0, Math.trunc(patch.capacity)),
|
||||
enabled: (patch.enabled ?? current.enabled) ? 1 : 0,
|
||||
}).changes > 0;
|
||||
},
|
||||
|
||||
deleteMusicAccount(id) {
|
||||
return deleteMusicAccountStmt.run(id).changes > 0;
|
||||
},
|
||||
|
||||
countMusicAccountGrants(accountId) {
|
||||
const row = countGrantsByAccount.get(accountId) as { c: number } | undefined;
|
||||
return row?.c ?? 0;
|
||||
},
|
||||
|
||||
listMusicAccountGrants(accountId) {
|
||||
return selectGrantsByAccount.all(accountId) as MusicAccountGrant[];
|
||||
},
|
||||
|
||||
listAllMusicAccountGrants() {
|
||||
return selectGrantsAll.all() as MusicAccountGrant[];
|
||||
},
|
||||
|
||||
assignMusicAccount(userId, accountId, grantedBy) {
|
||||
return assignMusicAccountTx(userId, accountId, grantedBy);
|
||||
},
|
||||
|
||||
deleteMusicAccountGrant(userId, platform, accountId) {
|
||||
return deleteGrantStmt.run(userId, platform, accountId).changes > 0;
|
||||
},
|
||||
|
||||
getGrantedMusicAccount(userId, platform) {
|
||||
const row = selectGrantedAccount.get(userId, platform) as
|
||||
| { accountId: string; label: string; cookie: string }
|
||||
| undefined;
|
||||
if (!row || !row.cookie.trim()) return null;
|
||||
return { accountId: row.accountId, label: row.label, cookie: row.cookie };
|
||||
},
|
||||
|
||||
saveQueue(ownerId, name, songs) {
|
||||
if (songs.length > MAX_QUEUE_SONGS) {
|
||||
throw new Error(`保存失败:歌曲数量超过上限 ${MAX_QUEUE_SONGS}`);
|
||||
|
||||
+17
-4
@@ -6,6 +6,8 @@ import { createLogger } from "./logger.js";
|
||||
import { createApiServerManager } from "./music/api-server.js";
|
||||
import { NeteaseProvider } from "./music/netease.js";
|
||||
import { QQMusicProvider } from "./music/qq.js";
|
||||
import { createQqLoginClient } from "./music/qq-login.js";
|
||||
import { createQqSessionStore, QQManagedSession } from "./music/qq-session.js";
|
||||
import { BiliBiliProvider } from "./music/bilibili.js";
|
||||
import { LocalMusicProvider } from "./music/local.js";
|
||||
import { KugouProvider } from "./music/kugou.js";
|
||||
@@ -66,7 +68,6 @@ async function main() {
|
||||
await apiServer.start();
|
||||
|
||||
const neteaseProvider = new NeteaseProvider(apiServer.getNeteaseBaseUrl());
|
||||
const qqProvider = new QQMusicProvider(apiServer.getQQMusicBaseUrl());
|
||||
const bilibiliProvider = new BiliBiliProvider();
|
||||
const localProvider = new LocalMusicProvider(LOCAL_AUDIO_DIR);
|
||||
const kugouProvider = new KugouProvider();
|
||||
@@ -79,12 +80,23 @@ async function main() {
|
||||
spotifyProvider.setCreds(config.spotify.clientId, config.spotify.clientSecret);
|
||||
}
|
||||
|
||||
const cookieStore = createCookieStore(COOKIE_DIR);
|
||||
const qqStore = createQqSessionStore(path.join(COOKIE_DIR, "qq-session.json"), path.join(COOKIE_DIR, "qq.json"));
|
||||
const cookieStore = createCookieStore(COOKIE_DIR, qqStore);
|
||||
const avatarStore = createAvatarStore(AVATAR_DIR);
|
||||
const neteaseCookie = cookieStore.load("netease");
|
||||
if (neteaseCookie) neteaseProvider.setCookie(neteaseCookie);
|
||||
const qqCookie = cookieStore.load("qq");
|
||||
if (qqCookie) qqProvider.setCookie(qqCookie);
|
||||
const qqSession = (process.env.QQ_MUSIC_MANAGED_SESSION ?? "1") === "1" && isProviderEnabled(config, "qq")
|
||||
? new QQManagedSession(createQqLoginClient(), qqStore, logger)
|
||||
: undefined;
|
||||
const qqProvider = new QQMusicProvider(apiServer.getQQMusicBaseUrl(), qqSession);
|
||||
if (!qqSession) {
|
||||
try {
|
||||
const cookie = cookieStore.load("qq");
|
||||
if (cookie) qqProvider.setCookie(cookie);
|
||||
} catch {
|
||||
logger.warn("Could not read QQ session");
|
||||
}
|
||||
}
|
||||
const bilibiliCookie = cookieStore.load("bilibili");
|
||||
if (bilibiliCookie) bilibiliProvider.setCookie(bilibiliCookie);
|
||||
const kugouCookie = cookieStore.load("kugou");
|
||||
@@ -175,6 +187,7 @@ async function main() {
|
||||
|
||||
const shutdown = () => {
|
||||
logger.info("Shutting down...");
|
||||
qqSession?.stop();
|
||||
botManager.shutdown();
|
||||
webServer.stop();
|
||||
apiServer.stop();
|
||||
|
||||
@@ -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("");
|
||||
});
|
||||
});
|
||||
+46
-8
@@ -1,39 +1,77 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import type { createQqSessionStore } from "./qq-session.js";
|
||||
|
||||
/** Platforms with a persisted credential blob. For jellyfin the "cookie" is a
|
||||
* JSON string carrying the access token / userId / deviceId (see jellyfin.ts). */
|
||||
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 {
|
||||
save(platform: CookiePlatform, cookie: string): void;
|
||||
load(platform: CookiePlatform): string;
|
||||
}
|
||||
|
||||
export function createCookieStore(cookieDir: string): CookieStore {
|
||||
export function createCookieStore(cookieDir: string, qqStore?: ReturnType<typeof createQqSessionStore>): CookieStore {
|
||||
if (!fs.existsSync(cookieDir)) {
|
||||
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 {
|
||||
save(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 }
|
||||
);
|
||||
if (platform === "qq" && qqStore) {
|
||||
qqStore.save({ cookie });
|
||||
return;
|
||||
}
|
||||
write(platform, storesCookieHeader(platform) ? normalizeCookie(cookie) : cookie);
|
||||
},
|
||||
|
||||
load(platform: CookiePlatform): string {
|
||||
if (platform === "qq" && qqStore) return qqStore.load()?.cookie ?? "";
|
||||
const filePath = path.join(cookieDir, `${platform}.json`);
|
||||
if (!fs.existsSync(filePath)) return "";
|
||||
let stored: string;
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(filePath, "utf-8"));
|
||||
return data.cookie ?? "";
|
||||
if (typeof data?.cookie !== "string") return "";
|
||||
stored = data.cookie;
|
||||
} catch {
|
||||
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;
|
||||
},
|
||||
};
|
||||
}
|
||||
+23
-1
@@ -1,3 +1,4 @@
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import axios, { type AxiosInstance } from "axios";
|
||||
import type {
|
||||
@@ -461,7 +462,28 @@ export class BiliBiliProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
setCookie(cookie: string): void {
|
||||
this.cookie = cookie;
|
||||
this.cookie = normalizeCookie(cookie);
|
||||
}
|
||||
|
||||
/**
|
||||
* A view of the same provider logged in as another account (#164 follow-up):
|
||||
* a web user's own B站 login instead of the bot's shared one. Mirrors
|
||||
* NeteaseProvider.withCookie so the web layer can treat every platform the
|
||||
* same way.
|
||||
*
|
||||
* The anonymous buvid3 identity and the WBI signing key are carried over —
|
||||
* both are account-independent caches, and re-fetching them per request would
|
||||
* add two extra round-trips to every search.
|
||||
*/
|
||||
withCookie(cookie: string): BiliBiliProvider {
|
||||
const view = new BiliBiliProvider();
|
||||
view.quality = this.quality;
|
||||
view.buvidCookie = this.buvidCookie;
|
||||
view.buvidInitialized = this.buvidInitialized;
|
||||
view.wbiMixinKey = this.wbiMixinKey;
|
||||
view.wbiKeyFetchedAt = this.wbiKeyFetchedAt;
|
||||
view.setCookie(cookie);
|
||||
return view;
|
||||
}
|
||||
|
||||
getCookie(): string {
|
||||
|
||||
@@ -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("");
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
+25
-1
@@ -15,6 +15,7 @@
|
||||
* residential IP is required. QR login and VIP audio could not be verified in
|
||||
* the build environment.
|
||||
*/
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import axios, { type AxiosInstance } from "axios";
|
||||
import crypto from "node:crypto";
|
||||
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) ------
|
||||
setCookie(cookie: string): void {
|
||||
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("=");
|
||||
if (eq < 0) continue;
|
||||
const k = part.slice(0, eq).trim();
|
||||
@@ -468,6 +471,27 @@ export class KugouProvider implements MusicProvider {
|
||||
return this.quality;
|
||||
}
|
||||
|
||||
/**
|
||||
* A view of the same provider logged in as another account (#164 follow-up):
|
||||
* a web user's own 酷狗 login instead of the bot's shared one.
|
||||
*
|
||||
* Kugou signs every request with the device identity (guid/mid) and binds the
|
||||
* session token to it, so the view MUST reuse this instance's device instead
|
||||
* of generating a fresh one — otherwise the installed cookie is rejected as
|
||||
* coming from an unknown device.
|
||||
*/
|
||||
withCookie(cookie: string): KugouProvider {
|
||||
const view = new KugouProvider();
|
||||
view.guid = this.guid;
|
||||
view.mid = this.mid;
|
||||
// Share the in-flight dfid registration: it is device-scoped, not account-
|
||||
// scoped, and sharing avoids a duplicate /register/dev per request.
|
||||
view.dfidPromise = this.dfidPromise;
|
||||
view.quality = this.quality;
|
||||
view.setCookie(cookie);
|
||||
return view;
|
||||
}
|
||||
|
||||
// --- Shared signed request pipeline (mirrors util/request.js) --------------
|
||||
private async request(opts: {
|
||||
method: "GET" | "POST";
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { once } from "node:events";
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import { RiskControlError, SongUrlUnavailable } from "./provider.js";
|
||||
import {
|
||||
parseLyrics,
|
||||
mapNeteaseAlbums,
|
||||
@@ -8,6 +13,64 @@ import {
|
||||
NeteaseProvider,
|
||||
} from "./netease.js";
|
||||
|
||||
describe("NeteaseProvider playback user agent", () => {
|
||||
it("matches the playback UA to each account's platform without changing cookies or other requests", async () => {
|
||||
const requests: URL[] = [];
|
||||
const server = createServer((req, res) => {
|
||||
requests.push(new URL(req.url!, "http://localhost"));
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ code: 200, data: [{ url: "https://example.com/song.mp3" }] }));
|
||||
});
|
||||
server.listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
try {
|
||||
const provider = new NeteaseProvider(
|
||||
`http://127.0.0.1:${(server.address() as AddressInfo).port}`,
|
||||
);
|
||||
const cases = [
|
||||
["", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared; os=pc", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared; os=android", "Android"],
|
||||
["MUSIC_U=shared; os=android; os=iphone", "iPhone"],
|
||||
["MUSIC_U=shared; os=iphone", "iPhone"],
|
||||
["MUSIC_U=shared; os=linux", "Linux"],
|
||||
["MUSIC_U=shared; os=unknown", "NeteaseMusicDesktop"],
|
||||
["MUSIC_U=shared; os=%69phone", "iPhone"],
|
||||
["MUSIC_U=shared; os=%invalid", "NeteaseMusicDesktop"],
|
||||
];
|
||||
for (const [cookie, uaFamily] of cases) {
|
||||
provider.setCookie(cookie);
|
||||
expect(await provider.getSongUrl("1", "standard")).toMatchObject({ url: "https://example.com/song.mp3" });
|
||||
const params = requests.at(-1)!.searchParams;
|
||||
expect(params.get("ua")).toContain(uaFamily);
|
||||
expect(params.get("level")).toBe("standard");
|
||||
const normalized = normalizeCookie(cookie);
|
||||
expect(params.get("cookie")).toBe(normalized || null);
|
||||
expect(provider.getCookie()).toBe(normalized);
|
||||
}
|
||||
|
||||
provider.setCookie("MUSIC_U=shared; os=pc");
|
||||
const personal = provider.withCookie("MUSIC_U=personal; os=android");
|
||||
await personal.getSongUrl("2");
|
||||
expect(requests.at(-1)!.searchParams.get("ua")).toContain("Android");
|
||||
expect(requests.at(-1)!.searchParams.get("cookie")).toBe("MUSIC_U=personal; os=android");
|
||||
await provider.getSongUrl("3");
|
||||
expect(requests.at(-1)!.searchParams.get("ua")).toContain("NeteaseMusicDesktop");
|
||||
expect(provider.getCookie()).toBe("MUSIC_U=shared; os=pc");
|
||||
|
||||
requests.length = 0;
|
||||
await provider.search("hello");
|
||||
await provider.getQrCode();
|
||||
expect(requests).toHaveLength(6);
|
||||
expect(requests.every((url) => !url.searchParams.has("ua"))).toBe(true);
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve, reject) => server.close((err) => err ? reject(err) : resolve()));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("NetEase adapter", () => {
|
||||
it("parses LRC format lyrics", () => {
|
||||
const lrc = `[00:00.00] 作词 : 周杰伦
|
||||
@@ -314,3 +377,173 @@ describe("NeteaseProvider.getArtistAllSongs (全部歌曲 paging)", () => {
|
||||
expect(page.hasMore).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("NetEase quality fallback ladder", () => {
|
||||
it("offers every lower level, best-first, for the default 320k setting", () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
// Default quality is exhigh (320k) → 192k then 128k.
|
||||
expect(p.getFallbackQualities()).toEqual(["higher", "standard"]);
|
||||
});
|
||||
|
||||
// The real-world case that produced «点四五次才能播»: a track playable at
|
||||
// 192k while BOTH 320k and 128k return null. Dropping only to the cheapest
|
||||
// level would still fail, so 192k has to be in the list.
|
||||
it("includes intermediate levels, not just the cheapest", () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
p.setQuality("lossless");
|
||||
expect(p.getFallbackQualities()).toEqual(["exhigh", "higher", "standard"]);
|
||||
});
|
||||
|
||||
it("has nothing to offer once already at the lowest level", () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
p.setQuality("standard");
|
||||
expect(p.getFallbackQualities()).toEqual([]);
|
||||
});
|
||||
|
||||
it("never proposes a level above the configured one", () => {
|
||||
const p = new NeteaseProvider("http://x");
|
||||
p.setQuality("higher");
|
||||
expect(p.getFallbackQualities()).toEqual(["standard"]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Risk control (-460)
|
||||
//
|
||||
// Live measurement on a cloud host, same song, same second:
|
||||
// GET /song/url/v1?id=1827600686&level=exhigh → 400 {"code":-460}
|
||||
// GET …&cookie=<account cookie> → 200, 320k url
|
||||
// axios reports both 400s and 200s alike as ERR_BAD_REQUEST when it fails, so
|
||||
// the body has to be inspected to know whether retrying is worthwhile.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("NetEase risk control (-460)", () => {
|
||||
/** Swap the axios instance for a stub — no module mocking needed. */
|
||||
function providerWithApi(get: (url: string, cfg: unknown) => Promise<unknown>) {
|
||||
const p = new NeteaseProvider("http://127.0.0.1:3001");
|
||||
(p as unknown as { api: { get: typeof get } }).api = { get };
|
||||
return p;
|
||||
}
|
||||
|
||||
function httpError(status: number, data: unknown) {
|
||||
const err = new Error(`Request failed with status code ${status}`) as Error & {
|
||||
response: unknown;
|
||||
};
|
||||
err.response = { status, data };
|
||||
return err;
|
||||
}
|
||||
|
||||
it("turns 400 + code -460 into a RiskControlError", async () => {
|
||||
const p = providerWithApi(async () => {
|
||||
throw httpError(400, {
|
||||
code: -460,
|
||||
message: "检测到您的网络环境存在风险,请稍后再试",
|
||||
});
|
||||
});
|
||||
await expect(p.getSongUrl("1827600686")).rejects.toBeInstanceOf(RiskControlError);
|
||||
});
|
||||
|
||||
it("returns a fixed risk-control error without exposing the upstream message", async () => {
|
||||
const p = providerWithApi(async () => {
|
||||
throw httpError(400, { code: -460, message: "upstream sample detail" });
|
||||
});
|
||||
await expect(p.getSongUrl("1827600686")).rejects.toThrow("网易云请求被风控拦截 (-460)");
|
||||
});
|
||||
|
||||
it("does not disguise a genuine bad request", async () => {
|
||||
const p = providerWithApi(async () => {
|
||||
throw httpError(400, { code: 400, msg: "参数错误" });
|
||||
});
|
||||
await expect(p.getSongUrl("1")).rejects.not.toBeInstanceOf(RiskControlError);
|
||||
});
|
||||
|
||||
it("does not disguise an unrelated 400 without a body code", async () => {
|
||||
const p = providerWithApi(async () => {
|
||||
throw httpError(400, "<html>Bad Request</html>");
|
||||
});
|
||||
await expect(p.getSongUrl("1")).rejects.not.toBeInstanceOf(RiskControlError);
|
||||
});
|
||||
|
||||
// A 200 with no url is not "the track does not exist" — it is one of five
|
||||
// different things, and this used to collapse all of them into a bare null.
|
||||
it("names the cause for a 200 that carries no url", async () => {
|
||||
const p = providerWithApi(async () => ({ data: { data: [{ url: null, code: 404 }] } }));
|
||||
await expect(p.getSongUrl("1")).rejects.toMatchObject({
|
||||
failure: { code: "no_copyright" },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns the url and the trial window on success", async () => {
|
||||
const p = providerWithApi(async () => ({
|
||||
data: { data: [{ url: "http://cdn.example/x.mp3", freeTrialInfo: { start: 0, end: 60 } }] },
|
||||
}));
|
||||
const r = await p.getSongUrl("1");
|
||||
expect(r?.url).toBe("http://cdn.example/x.mp3");
|
||||
expect(r?.trialDuration).toBe(60);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Naming the cause of a 200-with-no-URL
|
||||
//
|
||||
// `/song/url/v1` says "no URL here" for at least four unrelated reasons and the
|
||||
// fix differs for each: open a membership, pick another track, drop the quality,
|
||||
// or wait. Collapsing them into `null` is what produced the catch-all
|
||||
// 「无法播放(区域/版权限制)」 for a problem that was usually not about copyright.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("NetEase — why a track has no URL", () => {
|
||||
/** Resolve and return the thrown error; fails loudly if it does not throw. */
|
||||
async function miss(item: Record<string, unknown> | undefined): Promise<any> {
|
||||
const p = new NeteaseProvider("http://127.0.0.1:3001");
|
||||
(p as unknown as { api: { get: () => Promise<unknown> } }).api = {
|
||||
get: async () => ({ data: { data: item ? [item] : [] } }),
|
||||
};
|
||||
try {
|
||||
await p.getSongUrl("1");
|
||||
} catch (err) {
|
||||
return err;
|
||||
}
|
||||
throw new Error("expected getSongUrl to throw for a URL-less response");
|
||||
}
|
||||
|
||||
it("fee=1 未购买 → 需要会员", async () => {
|
||||
const err = await miss({ url: null, code: 200, fee: 1, payed: 0, level: "exhigh" });
|
||||
expect(err.failure.code).toBe("vip_required");
|
||||
expect(err.failure.message).toMatch(/需要会员/);
|
||||
});
|
||||
|
||||
it("fee=4 未购买 → 需要购买专辑(不是「会员」)", async () => {
|
||||
const err = await miss({ url: null, code: 200, fee: 4, payed: 0, level: "exhigh" });
|
||||
expect(err.failure.code).toBe("vip_required");
|
||||
expect(err.failure.message).toMatch(/专辑/);
|
||||
});
|
||||
|
||||
it("已付款的曲目不算会员问题", async () => {
|
||||
const err = await miss({ url: null, code: 200, fee: 1, payed: 1, level: "exhigh" });
|
||||
expect(err.failure.code).toBe("quality_denied");
|
||||
});
|
||||
|
||||
it("upstream code 404 → 无版权", async () => {
|
||||
const err = await miss({ url: null, code: 404, level: "exhigh" });
|
||||
expect(err.failure.code).toBe("no_copyright");
|
||||
expect(err.failure.message).toMatch(/无版权|下架/);
|
||||
});
|
||||
|
||||
// The measured case that broke the old single-message assumption: a free
|
||||
// track (fee=8) with no URL at exhigh that plays fine at higher.
|
||||
it("fee=8 且无 URL → 音质受限,而不是版权", async () => {
|
||||
const err = await miss({ url: null, code: 200, fee: 8, level: "exhigh" });
|
||||
expect(err.failure.code).toBe("quality_denied");
|
||||
expect(err.failure.message).toMatch(/音质/);
|
||||
});
|
||||
|
||||
it("空 data 数组 → 未知,但仍带得出上游字段", async () => {
|
||||
const err = await miss(undefined);
|
||||
expect(err.failure.code).toBe("unknown");
|
||||
expect(err.failure.upstream).toBeDefined();
|
||||
});
|
||||
|
||||
it("把 fee / payed / level 留在 upstream 里供日志使用", async () => {
|
||||
const err = await miss({ url: null, code: 200, fee: 8, payed: 0, level: "higher", br: 192000 });
|
||||
expect(err.failure.upstream).toMatchObject({ fee: 8, payed: 0, level: "higher", br: 192000 });
|
||||
});
|
||||
});
|
||||
+144
-5
@@ -1,4 +1,7 @@
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import axios, { type AxiosInstance } from "axios";
|
||||
import { RISK_CONTROL_CODE, RiskControlError, SongUrlUnavailable } from "./provider.js";
|
||||
import type { PlayFailure } from "./provider.js";
|
||||
import type {
|
||||
MusicProvider,
|
||||
Song,
|
||||
@@ -114,6 +117,84 @@ export function parseNeteaseTrial(item: any): number | undefined {
|
||||
return Math.round(secs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recognise NetEase's IP risk control inside an axios error. The status alone
|
||||
* is not enough — axios reports every 4xx as ERR_BAD_REQUEST — so the body has
|
||||
* to be read. See RiskControlError for the measured behaviour.
|
||||
*/
|
||||
function riskControlFrom(err: unknown): RiskControlError | null {
|
||||
const e = err as {
|
||||
response?: { status?: number; data?: { code?: number } };
|
||||
};
|
||||
if (e?.response?.status === 400 && e.response.data?.code === RISK_CONTROL_CODE) {
|
||||
return new RiskControlError("网易云请求被风控拦截 (-460)");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a 200-with-no-URL answer.
|
||||
*
|
||||
* `/song/url/v1` reports "no URL here" for at least four unrelated reasons, and
|
||||
* they need different fixes: open a membership, pick another track, drop the
|
||||
* quality, or just wait. The response does carry enough to tell them apart
|
||||
* (`code`, `fee`, `payed`, `level`), and not reading those fields is exactly
|
||||
* why every one of them reached the user as 「区域/版权限制」.
|
||||
*
|
||||
* Field meanings (NetEase):
|
||||
* fee 0 = free, 1 = VIP, 4 = album-only purchase, 8 = free / low quality
|
||||
* payed 1 = this account already paid for it
|
||||
* code 404 on the item = the id does not resolve to a playable track
|
||||
*/
|
||||
export function diagnoseNeteaseMiss(
|
||||
songId: string,
|
||||
level: string,
|
||||
item: Record<string, any> | undefined,
|
||||
body: Record<string, any> | undefined,
|
||||
): PlayFailure {
|
||||
const upstream = {
|
||||
code: item?.code ?? body?.code,
|
||||
fee: item?.fee,
|
||||
payed: item?.payed,
|
||||
level: item?.level ?? level,
|
||||
br: item?.br,
|
||||
freeTrial: Boolean(item?.freeTrialInfo),
|
||||
};
|
||||
const suffix = `(${String(upstream.level)})`;
|
||||
const base = { platform: "netease" as const, songId, upstream };
|
||||
|
||||
if (!item) {
|
||||
return {
|
||||
...base,
|
||||
code: "unknown",
|
||||
message: `音源没有返回该曲目${suffix}`,
|
||||
};
|
||||
}
|
||||
if (upstream.code === 404) {
|
||||
return {
|
||||
...base,
|
||||
code: "no_copyright",
|
||||
message: `无版权或已下架${suffix}`,
|
||||
};
|
||||
}
|
||||
const fee = typeof upstream.fee === "number" ? upstream.fee : -1;
|
||||
if ((fee === 1 || fee === 4) && !upstream.payed) {
|
||||
return {
|
||||
...base,
|
||||
code: "vip_required",
|
||||
message: fee === 4 ? `需要购买该专辑${suffix}` : `需要会员${suffix}`,
|
||||
};
|
||||
}
|
||||
// Everything else that has the track but no URL is a per-level restriction:
|
||||
// the same id often plays at another level (measured: 192k OK while both
|
||||
// 320k and 128k returned null).
|
||||
return {
|
||||
...base,
|
||||
code: "quality_denied",
|
||||
message: `当前音质无播放权限${suffix}`,
|
||||
};
|
||||
}
|
||||
|
||||
// NetEase quality levels: standard(128k) higher(192k) exhigh(320k) lossless(flac) hires(hi-res) jyeffect jymaster
|
||||
export const NETEASE_QUALITY_LEVELS = [
|
||||
{ value: "standard", label: "标准 (128kbps)", bitrate: 128 },
|
||||
@@ -124,6 +205,29 @@ export const NETEASE_QUALITY_LEVELS = [
|
||||
{ value: "jymaster", label: "超清母带", bitrate: 4000 },
|
||||
] as const;
|
||||
|
||||
function getPlaybackUserAgent(cookie: string): string {
|
||||
let decoded = cookie;
|
||||
try {
|
||||
decoded = decodeURIComponent(cookie);
|
||||
} catch {
|
||||
// A malformed cookie escape must not prevent a playback request.
|
||||
}
|
||||
// The sidecar's cookie parser keeps the last value of a repeated key.
|
||||
const platform = [...decoded.matchAll(/(?:^|;)\s*os\s*=\s*([^;=]*)(?=;|$)/g)].at(-1)?.[1].trim();
|
||||
// NCM API 4.32.0 defaults cookie profiles to PC but eapi's UA to iPhone.
|
||||
// Match its client profiles here, and scope the override to playback only.
|
||||
switch (platform) {
|
||||
case "android":
|
||||
return "NeteaseMusic/9.1.65.240927161425(9001065);Dalvik/2.1.0 (Linux; U; Android 14; 23013RK75C Build/UKQ1.230804.001)";
|
||||
case "iphone":
|
||||
return "NeteaseMusic 9.0.90/5038 (iPhone; iOS 16.2; zh_CN)";
|
||||
case "linux":
|
||||
return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36";
|
||||
default:
|
||||
return "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 Chrome/91.0.4472.164 NeteaseMusicDesktop/3.0.18.203152";
|
||||
}
|
||||
}
|
||||
|
||||
export class NeteaseProvider implements MusicProvider {
|
||||
readonly platform = "netease" as const;
|
||||
private api: AxiosInstance;
|
||||
@@ -197,15 +301,48 @@ export class NeteaseProvider implements MusicProvider {
|
||||
|
||||
async getSongUrl(songId: string, quality?: string): Promise<SongUrlResult | null> {
|
||||
const level = quality ?? this.quality;
|
||||
const res = await this.api.get("/song/url/v1", {
|
||||
params: { id: songId, level, ...this.cookieParams },
|
||||
});
|
||||
let res;
|
||||
try {
|
||||
res = await this.api.get("/song/url/v1", {
|
||||
params: { id: songId, level, ua: getPlaybackUserAgent(this.cookie), ...this.cookieParams },
|
||||
});
|
||||
} catch (err) {
|
||||
// -460 arrives as HTTP 400, and left as-is it looks like "this track is
|
||||
// unavailable" to every caller. Surface it as its own error type so the
|
||||
// retry layer can wait out the risk-control window instead of giving up.
|
||||
const risk = riskControlFrom(err);
|
||||
if (risk) throw risk;
|
||||
throw err;
|
||||
}
|
||||
const item = res.data?.data?.[0];
|
||||
const url = item?.url;
|
||||
if (!url) return null;
|
||||
// A bare `null` here forced every caller to invent an explanation, and the
|
||||
// one they invented was 「区域/版权限制」 — wrong for a lapsed membership, for
|
||||
// a delisted track, and for a quality the account cannot stream. Throw the
|
||||
// reason instead; the retry layer still spends its budget, it just stops
|
||||
// lying about why nothing worked.
|
||||
if (!url) throw new SongUrlUnavailable(diagnoseNeteaseMiss(songId, level, item, res.data));
|
||||
return { url, trialDuration: parseNeteaseTrial(item) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Levels to fall back to when the configured one returns no URL.
|
||||
*
|
||||
* NetEase does not offer a continuous quality ladder per track: measured on a
|
||||
* real library, a track can be available at "higher" (192k) while BOTH
|
||||
* "exhigh" (320k) and "standard" (128k) answer `url: null`. So the caller must
|
||||
* sweep every level BELOW the current one instead of assuming "just drop to
|
||||
* the cheapest".
|
||||
*/
|
||||
getFallbackQualities(): string[] {
|
||||
const order = NETEASE_QUALITY_LEVELS.map((l) => l.value as string);
|
||||
const index = order.indexOf(this.quality);
|
||||
if (index <= 0) return [];
|
||||
// order is low→high, so everything before the current level reversed gives
|
||||
// best→worst below it (exhigh → ["higher", "standard"]).
|
||||
return order.slice(0, index).reverse();
|
||||
}
|
||||
|
||||
async getSongDetail(songId: string): Promise<Song | null> {
|
||||
const res = await this.api.get("/song/detail", {
|
||||
params: { ids: songId, ...this.cookieParams },
|
||||
@@ -390,7 +527,9 @@ export class NeteaseProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -34,6 +34,77 @@ export interface SongUrlResult {
|
||||
trialDuration?: number;
|
||||
}
|
||||
|
||||
/** NetEase upstream risk-control response code. */
|
||||
export const RISK_CONTROL_CODE = -460;
|
||||
|
||||
export class RiskControlError extends Error {
|
||||
readonly code: number = RISK_CONTROL_CODE;
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "RiskControlError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a track could not be turned into a playable URL.
|
||||
*
|
||||
* Every one of these used to reach the user as the same string —
|
||||
* 「无法播放(区域/版权限制)」 — which is why a genuine -460, a lapsed membership
|
||||
* and a delisted track were indistinguishable for weeks of debugging. Naming
|
||||
* the cause is the whole point of this type.
|
||||
*/
|
||||
export type PlayFailureCode =
|
||||
/** Upstream refused the caller's IP (-460). Transient by nature. */
|
||||
| "risk_control"
|
||||
/** Paid track with no entitlement on the account (NetEase fee=1 VIP / fee=4). */
|
||||
| "vip_required"
|
||||
/** Delisted, region-blocked, or the id no longer resolves (upstream 404). */
|
||||
| "no_copyright"
|
||||
/** The track exists, but this quality level is not ours to serve. */
|
||||
| "quality_denied"
|
||||
/** 200 with no URL and nothing that explains why. */
|
||||
| "unknown";
|
||||
|
||||
export interface PlayFailure {
|
||||
platform: string;
|
||||
songId: string;
|
||||
code: PlayFailureCode;
|
||||
/** One short line in the UI's language — safe to render as-is. */
|
||||
message: string;
|
||||
/** Raw upstream fields (fee / payed / code / level). Logs only, never shown. */
|
||||
upstream?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when a provider knows *why* no URL came back.
|
||||
*
|
||||
* `resolveUrlWithRetry` still runs the full budget on it — a lower level can
|
||||
* genuinely help, and "deterministic" judgements about this API have been wrong
|
||||
* before — but it remembers the last one so the eventual message can name the
|
||||
* cause instead of falling back to a guess.
|
||||
*/
|
||||
export class SongUrlUnavailable extends Error {
|
||||
readonly failure: PlayFailure;
|
||||
constructor(failure: PlayFailure) {
|
||||
super(failure.message);
|
||||
this.name = "SongUrlUnavailable";
|
||||
this.failure = failure;
|
||||
}
|
||||
}
|
||||
|
||||
export function toPlayFailure(platform: string, songId: string, error: unknown): PlayFailure {
|
||||
if (error instanceof SongUrlUnavailable) return error.failure;
|
||||
if (error instanceof RiskControlError) {
|
||||
return {
|
||||
platform,
|
||||
songId,
|
||||
code: "risk_control",
|
||||
message: "网易云暂时拒绝播放请求(-460),请稍后重试",
|
||||
};
|
||||
}
|
||||
return { platform, songId, code: "unknown", message: "解析播放地址失败" };
|
||||
}
|
||||
|
||||
export interface Playlist {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -42,6 +113,7 @@ export interface Playlist {
|
||||
platform: Platform;
|
||||
}
|
||||
|
||||
|
||||
export interface PlaylistDetail {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -134,6 +206,25 @@ export interface MusicProvider {
|
||||
setCookie(cookie: string): void;
|
||||
getCookie(): string;
|
||||
getAuthStatus(): Promise<AuthStatus>;
|
||||
/**
|
||||
* Lower quality levels to try when the configured one has no URL, ordered
|
||||
* best→worst.
|
||||
*
|
||||
* NetEase does not publish a uniform ladder: a track can be playable at 192k
|
||||
* ("higher") while BOTH 320k ("exhigh") and 128k ("standard") return null —
|
||||
* so the list has to contain every level below the current one, not just the
|
||||
* cheapest. Sources whose quality is not a user-selectable knob (Bilibili,
|
||||
* local files, Jellyfin) omit this and the caller keeps its single attempt.
|
||||
*/
|
||||
getFallbackQualities?(): string[];
|
||||
/**
|
||||
* A view of this same provider logged in as another account, without
|
||||
* disturbing the shared instance. Implemented by the sources that support
|
||||
* per-account logins — NetEase since #164, QQ / Kugou / Bilibili following in
|
||||
* the #164 follow-up. The rest simply omit it and the web layer falls back to
|
||||
* the shared login (see web/api/provider-scope.ts).
|
||||
*/
|
||||
withCookie?(cookie: string): MusicProvider;
|
||||
getPersonalFm?(): Promise<Song[]>;
|
||||
getDailyRecommendSongs?(): Promise<Song[]>;
|
||||
getUserPlaylists?(): Promise<Playlist[]>;
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { get, post } = vi.hoisted(() => ({ get: vi.fn(), post: vi.fn() }));
|
||||
vi.mock("axios", () => ({ default: { create: () => ({ get, post }), isAxiosError: () => false } }));
|
||||
|
||||
import { createQqLoginClient, parseQqCredential } from "./qq-login.js";
|
||||
|
||||
const credential = {
|
||||
musicid: 12345, musickey: "test-music-key", openid: "test-openid", access_token: "test-access",
|
||||
refresh_token: "test-token", refresh_key: "test-refresh", expired_at: 1234,
|
||||
musickeyCreateTime: 5678, keyExpiresIn: 3600,
|
||||
};
|
||||
|
||||
describe("QQ login transport", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it("accepts the QQ QR image when Tencent omits its content type", async () => {
|
||||
get.mockResolvedValueOnce({
|
||||
data: Buffer.from("89504e470d0a1a0a", "hex"),
|
||||
headers: { "set-cookie": ["qrsig=test-sig; Path=/"] },
|
||||
});
|
||||
expect(await createQqLoginClient().getQr()).toMatchObject({
|
||||
img: "data:image/png;base64,iVBORw0KGgo=", sig: "test-sig",
|
||||
});
|
||||
});
|
||||
|
||||
it("exchanges a confirmed QR for the full JSON credential", async () => {
|
||||
get
|
||||
.mockResolvedValueOnce({
|
||||
data: "ptuiCB('0','0','https://ssl.ptlogin2.graph.qq.com/check_sig?uin=12345&ptsigx=sigx','0','','');",
|
||||
})
|
||||
.mockResolvedValueOnce({ headers: { "set-cookie": ["p_skey=test==; Path=/; Secure"] } });
|
||||
post
|
||||
.mockResolvedValueOnce({ headers: { location: "https://y.qq.com/portal/wx_redirect.html?code=example&state=state" } })
|
||||
.mockResolvedValueOnce({
|
||||
headers: {},
|
||||
data: { code: 0, req_0: { code: 0, data: { ...credential, loginType: 2 } } },
|
||||
});
|
||||
expect(await createQqLoginClient().pollQr("test-sig")).toEqual({ status: "confirmed", credential });
|
||||
expect(post).toHaveBeenNthCalledWith(
|
||||
1, "https://graph.qq.com/oauth2.0/authorize", expect.any(URLSearchParams),
|
||||
expect.objectContaining({ headers: { Cookie: "p_skey=test==" } }),
|
||||
);
|
||||
expect(post).toHaveBeenNthCalledWith(
|
||||
2, "https://u.y.qq.com/cgi-bin/musicu.fcg",
|
||||
expect.objectContaining({
|
||||
req_0: { module: "QQConnectLogin.LoginServer", method: "QQLogin", param: { code: "example" } },
|
||||
}),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("sends the login type 2 refresh payload and validates the CGI status", async () => {
|
||||
post.mockResolvedValue({
|
||||
headers: {},
|
||||
data: { code: 0, req_0: { code: 104604, data: { ...credential, musickey: "do-not-use" } } },
|
||||
});
|
||||
expect(await createQqLoginClient().refresh(credential)).toEqual({ status: "rate_limited" });
|
||||
expect(post).toHaveBeenCalledWith(
|
||||
"https://u.y.qq.com/cgi-bin/musicu.fcg",
|
||||
expect.objectContaining({
|
||||
comm: expect.objectContaining({ tmeLoginType: "2" }),
|
||||
req_0: {
|
||||
module: "music.login.LoginServer", method: "Login",
|
||||
param: {
|
||||
loginMode: 2, musicid: 12345, musickey: "test-music-key", openid: "test-openid",
|
||||
access_token: "test-access", refresh_token: "test-token", refresh_key: "test-refresh", expired_in: 1234,
|
||||
},
|
||||
},
|
||||
}),
|
||||
expect.anything(),
|
||||
);
|
||||
post.mockResolvedValueOnce({ headers: {}, data: { code: 104401 } });
|
||||
expect(await createQqLoginClient().refresh(credential)).toEqual({ status: "reauth_required" });
|
||||
post.mockResolvedValueOnce({ headers: {}, data: { code: 0, req_0: { code: 0, data: { musicid: 12345 } } } });
|
||||
expect(await createQqLoginClient().refresh(credential)).toEqual({ status: "upstream_error" });
|
||||
});
|
||||
|
||||
it("accepts playback-only QQ credentials and rejects other types or invalid keys", () => {
|
||||
expect(parseQqCredential({ str_musicid: "12345", musickey: "music-key" })).toMatchObject({
|
||||
musicid: 12345, musickey: "music-key", refresh_key: "",
|
||||
});
|
||||
expect(parseQqCredential({ ...credential, loginType: 1 })).toBeUndefined();
|
||||
expect(parseQqCredential({ ...credential, musickey: "music-key\r\n" })).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps unchanged OAuth fields when QQ returns a partial rotation for the same account", async () => {
|
||||
post.mockResolvedValueOnce({
|
||||
headers: {},
|
||||
data: { code: 0, req_0: { code: 0, data: {
|
||||
musicid: 12345, musickey: "rotated-key", refresh_token: "rotated-token",
|
||||
} } },
|
||||
});
|
||||
expect(await createQqLoginClient().refresh(credential)).toMatchObject({
|
||||
status: "refreshed",
|
||||
credential: {
|
||||
musicid: 12345, musickey: "rotated-key", refresh_token: "rotated-token",
|
||||
openid: credential.openid, access_token: credential.access_token,
|
||||
musickeyCreateTime: 0, keyExpiresIn: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("fills missing expiration fields only for the same account and playback key", async () => {
|
||||
const sameKey = { musicid: credential.musicid, musickey: credential.musickey, refresh_token: "rotated-token" };
|
||||
post.mockResolvedValueOnce({
|
||||
headers: {},
|
||||
data: { code: 0, req_0: { code: 0, data: sameKey } },
|
||||
});
|
||||
expect(await createQqLoginClient().refresh(credential)).toMatchObject({
|
||||
status: "refreshed",
|
||||
credential: { refresh_token: "rotated-token", musickeyCreateTime: 5678, keyExpiresIn: 3600 },
|
||||
});
|
||||
expect(parseQqCredential({ ...sameKey, keyExpiresIn: 7200 }, credential)).toMatchObject({
|
||||
musickeyCreateTime: 5678, keyExpiresIn: 7200,
|
||||
});
|
||||
expect(parseQqCredential({ ...sameKey, musicid: 999 }, credential)).toMatchObject({
|
||||
musickeyCreateTime: 0, keyExpiresIn: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,229 @@
|
||||
import axios from "axios";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
export interface QqCredential {
|
||||
musicid: number;
|
||||
musickey: string;
|
||||
openid: string;
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
refresh_key: string;
|
||||
expired_at: number;
|
||||
musickeyCreateTime: number;
|
||||
keyExpiresIn: number;
|
||||
}
|
||||
|
||||
export type QqPollResult =
|
||||
| { status: "waiting" | "scanned" | "expired" }
|
||||
| { status: "confirmed"; credential: QqCredential };
|
||||
|
||||
export type QqRefreshResult =
|
||||
| { status: "refreshed"; credential: QqCredential }
|
||||
| { status: "reauth_required" | "rate_limited" | "upstream_error" };
|
||||
|
||||
export interface QqLoginClient {
|
||||
getQr(): Promise<{ img: string; sig: string }>;
|
||||
pollQr(sig: string): Promise<QqPollResult>;
|
||||
refresh(credential: QqCredential): Promise<QqRefreshResult>;
|
||||
}
|
||||
|
||||
const QR_HOST = "https://ssl.ptlogin2.qq.com";
|
||||
const REFERER = "https://xui.ptlogin2.qq.com/";
|
||||
const QQ_JUMP = "https://graph.qq.com/oauth2.0/login_jump";
|
||||
const MUSIC_REDIRECT = "https://y.qq.com/portal/wx_redirect.html";
|
||||
const APP_ID = "100497308";
|
||||
const LOGIN_SCOPE = { daid: "383", pt_3rd_aid: APP_ID };
|
||||
const AUTH_REJECTED = new Set([1000, 104400, 104401, 20261, 20272, 20274, 20277, 20278, 20279, 20450]);
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
function token(value: unknown): string {
|
||||
return typeof value === "string" && /^[\x21-\x3a\x3c-\x7e]+$/.test(value) ? value : "";
|
||||
}
|
||||
|
||||
function positiveInt(value: unknown): number {
|
||||
const n = typeof value === "string" && /^\d+$/.test(value) ? Number(value) : value;
|
||||
return typeof n === "number" && Number.isSafeInteger(n) && n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
export function parseQqCredential(value: unknown, previous?: QqCredential): QqCredential | undefined {
|
||||
const data = record(value);
|
||||
const type = data.loginType ?? data.login_type;
|
||||
if (type !== undefined && type !== 2 && type !== "2") return;
|
||||
const musicid = positiveInt(data.musicid) || positiveInt(data.str_musicid);
|
||||
const musickey = token(data.musickey);
|
||||
if (!musicid || !musickey) return;
|
||||
const sameAccount = previous?.musicid === musicid ? previous : undefined;
|
||||
const sameKey = sameAccount?.musickey === musickey ? sameAccount : undefined;
|
||||
return {
|
||||
musicid,
|
||||
musickey,
|
||||
openid: token(data.openid ?? sameAccount?.openid),
|
||||
access_token: token(data.access_token ?? sameAccount?.access_token),
|
||||
refresh_token: token(data.refresh_token ?? sameAccount?.refresh_token),
|
||||
refresh_key: token(data.refresh_key),
|
||||
expired_at: positiveInt(data.expired_at ?? sameAccount?.expired_at),
|
||||
musickeyCreateTime: positiveInt(data.musickeyCreateTime ?? sameKey?.musickeyCreateTime),
|
||||
keyExpiresIn: positiveInt(data.keyExpiresIn ?? sameKey?.keyExpiresIn),
|
||||
};
|
||||
}
|
||||
|
||||
export function hasQqRenewalMaterial(credential?: QqCredential): credential is QqCredential {
|
||||
// QQ's web QR flow may return OAuth tokens without a separate refresh key.
|
||||
return Boolean(credential?.refresh_key || (credential?.openid && credential.access_token && credential.refresh_token));
|
||||
}
|
||||
|
||||
export function qqPlaybackCookie({ musicid, musickey }: QqCredential): string {
|
||||
return `uin=${musicid}; qqmusic_uin=${musicid}; qm_keyst=${musickey}; qqmusic_key=${musickey}; login_type=2; tmeLoginType=2`;
|
||||
}
|
||||
|
||||
function hash33(value: string, seed: number): number {
|
||||
let hash = seed;
|
||||
for (let i = 0; i < value.length; i++) hash = (hash * 33 + value.charCodeAt(i)) | 0;
|
||||
return hash & 0x7fffffff;
|
||||
}
|
||||
|
||||
function setCookies(headers: string[] = []): Map<string, string> {
|
||||
const cookies = new Map<string, string>();
|
||||
for (const header of headers) {
|
||||
const pair = header.split(";", 1)[0];
|
||||
const equals = pair.indexOf("=");
|
||||
if (equals < 1) continue;
|
||||
const value = token(pair.slice(equals + 1));
|
||||
if (value) cookies.set(pair.slice(0, equals), value);
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
function cookieHeader(cookies: Map<string, string>): string {
|
||||
return Array.from(cookies, ([key, value]) => `${key}=${value}`).join("; ");
|
||||
}
|
||||
|
||||
export function createQqLoginClient(): QqLoginClient {
|
||||
const http = axios.create({ timeout: 10_000, maxRedirects: 0 });
|
||||
|
||||
// QQMusicApi's web CGI profile. Keep authorization fields in the HTTPS body.
|
||||
async function musicu(module: string, method: string, param: object, credential?: QqCredential) {
|
||||
const gTk = String(hash33(credential?.musickey ?? "", 5381));
|
||||
const res = await http.post("https://u.y.qq.com/cgi-bin/musicu.fcg", {
|
||||
comm: {
|
||||
ct: "24", cv: "4747474", platform: "yqq.json", chid: "0",
|
||||
uin: String(credential?.musicid ?? 0), g_tk: gTk, g_tk_new_20200303: gTk,
|
||||
format: "json", inCharset: "utf-8", outCharset: "utf-8", notice: "0",
|
||||
need_new_code: "1", tmeLoginType: "2",
|
||||
},
|
||||
req_0: { module, method, param },
|
||||
}, { headers: { Referer: "https://y.qq.com/" } });
|
||||
const body = record(res.data);
|
||||
const item = record(body.req_0);
|
||||
return { code: body.code === 0 ? item.code : body.code, data: item.data, cookies: setCookies(res.headers["set-cookie"]) };
|
||||
}
|
||||
|
||||
async function authorize(redirect: string): Promise<QqCredential | undefined> {
|
||||
const url = new URL(redirect);
|
||||
const uin = url.searchParams.get("uin");
|
||||
const sigx = url.searchParams.get("ptsigx");
|
||||
if (!uin || !/^\d+$/.test(uin) || !sigx) return;
|
||||
const noFollow = (status: number) => status >= 200 && status < 400;
|
||||
const checked = await http.get("https://ssl.ptlogin2.graph.qq.com/check_sig", {
|
||||
params: {
|
||||
...LOGIN_SCOPE, uin, ptsigx: sigx, pttype: "1", service: "ptqrlogin",
|
||||
nodirect: "0", s_url: QQ_JUMP, ptlang: "2052", ptredirect: "100",
|
||||
aid: "716027609", j_later: "0", low_login_hour: "0", regmaster: "0",
|
||||
pt_login_type: "3", pt_aid: "0", pt_aaid: "16", pt_light: "0",
|
||||
},
|
||||
headers: { Referer: REFERER },
|
||||
validateStatus: noFollow,
|
||||
});
|
||||
const cookies = setCookies(checked.headers["set-cookie"]);
|
||||
const pSkey = cookies.get("p_skey");
|
||||
if (!pSkey) return;
|
||||
|
||||
const authorized = await http.post("https://graph.qq.com/oauth2.0/authorize", new URLSearchParams({
|
||||
response_type: "code", client_id: APP_ID, redirect_uri: `${MUSIC_REDIRECT}?login_type=1&surl=https://y.qq.com/`,
|
||||
scope: "get_user_info,get_app_friends", state: "state", switch: "",
|
||||
from_ptlogin: "1", src: "1", update_auth: "1", openapi: "1010_1030",
|
||||
g_tk: String(hash33(pSkey, 5381)), auth_time: String(Date.now()), ui: randomUUID(),
|
||||
}), { headers: { Cookie: cookieHeader(cookies) }, validateStatus: noFollow });
|
||||
if (typeof authorized.headers.location !== "string") return;
|
||||
const callback = new URL(authorized.headers.location);
|
||||
if (callback.origin + callback.pathname !== MUSIC_REDIRECT) return;
|
||||
const code = callback.searchParams.get("code");
|
||||
if (!code) return;
|
||||
|
||||
const result = await musicu("QQConnectLogin.LoginServer", "QQLogin", { code });
|
||||
if (result.code !== 0) return;
|
||||
return parseQqCredential(result.data) ?? parseQqCredential({
|
||||
musicid: result.cookies.get("qqmusic_uin") ?? uin,
|
||||
musickey: result.cookies.get("qqmusic_key") ?? result.cookies.get("qm_keyst"),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
async getQr() {
|
||||
try {
|
||||
const res = await http.get(`${QR_HOST}/ptqrshow`, {
|
||||
params: { ...LOGIN_SCOPE, appid: "716027609", e: "2", l: "M", s: "3", d: "72", v: "4", t: Math.random() },
|
||||
headers: { Referer: REFERER },
|
||||
responseType: "arraybuffer",
|
||||
});
|
||||
const sig = setCookies(res.headers["set-cookie"]).get("qrsig");
|
||||
// Tencent can send the PNG without a Content-Type header.
|
||||
const bytes = Buffer.from(res.data);
|
||||
const isPng = bytes.subarray(0, 8).toString("hex") === "89504e470d0a1a0a";
|
||||
const isJpeg = bytes.subarray(0, 3).toString("hex") === "ffd8ff";
|
||||
if (sig && (isPng || isJpeg)) {
|
||||
return { img: `data:image/${isPng ? "png" : "jpeg"};base64,${bytes.toString("base64")}`, sig };
|
||||
}
|
||||
} catch { /* Do not expose the request or response. */ }
|
||||
throw new Error("QQ QR code unavailable");
|
||||
},
|
||||
async pollQr(sig) {
|
||||
let response: string;
|
||||
try {
|
||||
const res = await http.get<string>(`${QR_HOST}/ptqrlogin`, {
|
||||
params: {
|
||||
...LOGIN_SCOPE, u1: QQ_JUMP, ptqrtoken: hash33(sig, 0), ptredirect: "0",
|
||||
h: "1", t: "1", g: "1", from_ui: "1", ptlang: "2052",
|
||||
action: `0-0-${Date.now()}`, js_ver: "20102616", js_type: "1",
|
||||
pt_uistyle: "40", aid: "716027609", has_onekey: "1",
|
||||
},
|
||||
headers: { Referer: REFERER, Cookie: `qrsig=${sig}` },
|
||||
responseType: "text",
|
||||
});
|
||||
response = res.data;
|
||||
} catch { return { status: "waiting" }; }
|
||||
|
||||
const fields = /^\s*ptuiCB\((.*)\)/.exec(response)?.[1].match(/'((?:\\.|[^'])*)'/g);
|
||||
const code = fields?.[0]?.slice(1, -1);
|
||||
if (code === "66") return { status: "waiting" };
|
||||
if (code === "67") return { status: "scanned" };
|
||||
if (code === "0" && fields?.[2]) {
|
||||
try {
|
||||
const credential = await authorize(fields[2].slice(1, -1));
|
||||
if (credential) return { status: "confirmed", credential };
|
||||
} catch { /* A used QR cannot safely replay the authorization code. */ }
|
||||
}
|
||||
return { status: "expired" };
|
||||
},
|
||||
async refresh(credential) {
|
||||
const { openid, access_token, refresh_token, expired_at, musicid, musickey, refresh_key } = credential;
|
||||
try {
|
||||
const result = await musicu("music.login.LoginServer", "Login", {
|
||||
openid, access_token, refresh_token, expired_in: expired_at, musicid, musickey, refresh_key, loginMode: 2,
|
||||
}, credential);
|
||||
const code = Number(result.code);
|
||||
if (code === 104604 || code === 2001) return { status: "rate_limited" };
|
||||
if (AUTH_REJECTED.has(code)) return { status: "reauth_required" };
|
||||
const next = result.code === 0 ? parseQqCredential(result.data, credential) : undefined;
|
||||
if (next) return { status: "refreshed", credential: next };
|
||||
} catch (err) {
|
||||
if (axios.isAxiosError(err) && err.response?.status === 429) return { status: "rate_limited" };
|
||||
}
|
||||
return { status: "upstream_error" };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import pino from "pino";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createCookieStore } from "./auth.js";
|
||||
import { parseQqCredential, qqPlaybackCookie, type QqCredential, type QqLoginClient, type QqRefreshResult } from "./qq-login.js";
|
||||
import { createQqSessionStore, QQManagedSession } from "./qq-session.js";
|
||||
|
||||
const NOW = new Date("2026-11-09T00:00:00.000Z");
|
||||
const MINUTE = 60_000;
|
||||
const DAY = 24 * 60 * MINUTE;
|
||||
const first: QqCredential = {
|
||||
musicid: 123456, musickey: "first-key", refresh_key: "first-refresh",
|
||||
openid: "test-openid", access_token: "test-access", refresh_token: "test-refresh",
|
||||
expired_at: 123, musickeyCreateTime: NOW.valueOf() / 1000, keyExpiresIn: 3 * DAY / 1000,
|
||||
};
|
||||
const second = { ...first, musickey: "second-key", refresh_key: "second-refresh" };
|
||||
|
||||
describe("managed QQ session", () => {
|
||||
let dir: string;
|
||||
let file: string;
|
||||
let store: ReturnType<typeof createQqSessionStore>;
|
||||
let client: QqLoginClient;
|
||||
let session: QQManagedSession;
|
||||
const logger = pino({ level: "silent" });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(NOW);
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), "tsbot-qq-"));
|
||||
file = path.join(dir, "qq-session.json");
|
||||
store = createQqSessionStore(file);
|
||||
client = {
|
||||
getQr: vi.fn().mockResolvedValue({ img: "test-image", sig: "private-qr-sig" }),
|
||||
pollQr: vi.fn().mockResolvedValue({ status: "confirmed", credential: first }),
|
||||
refresh: vi.fn().mockResolvedValue({ status: "refreshed", credential: second }),
|
||||
};
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
session.stop();
|
||||
vi.useRealTimers();
|
||||
fs.rmSync(file, { force: true });
|
||||
fs.rmSync(path.join(dir, "qq.json"), { force: true });
|
||||
fs.rmdirSync(dir);
|
||||
});
|
||||
|
||||
async function scan() {
|
||||
const qr = await session.getQrCode();
|
||||
expect(qr.key).not.toContain("private-qr-sig");
|
||||
expect(await Promise.all([
|
||||
session.checkQrCodeStatus(qr.key),
|
||||
session.checkQrCodeStatus(qr.key),
|
||||
])).toEqual(["confirmed", "confirmed"]);
|
||||
expect(client.pollQr).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
|
||||
it("persists the scan, refreshes after 24 hours and keeps the next due date across restarts", async () => {
|
||||
await scan();
|
||||
expect(store.load()?.credential).toEqual(first);
|
||||
if (process.platform !== "win32") expect(fs.statSync(file).mode & 0o777).toBe(0o600);
|
||||
expect(session.getStatus()).toEqual({
|
||||
renewalStatus: "scheduled",
|
||||
nextRefreshAt: new Date(NOW.valueOf() + DAY).toISOString(),
|
||||
lastRefreshAt: null,
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(DAY / 2);
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
await vi.advanceTimersByTimeAsync(DAY / 2 - 1);
|
||||
expect(client.refresh).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(client.refresh).toHaveBeenCalledWith(first);
|
||||
expect(store.load()?.credential).toEqual(second);
|
||||
expect(session.getCookie()).toContain("qm_keyst=second-key");
|
||||
expect(store.load()?.lastRefreshAt).toBe(NOW.valueOf() + DAY);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(DAY / 2);
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
expect(session.getStatus()).toEqual({
|
||||
renewalStatus: "scheduled",
|
||||
nextRefreshAt: new Date(NOW.valueOf() + 2 * DAY).toISOString(),
|
||||
lastRefreshAt: new Date(NOW.valueOf() + DAY).toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
it("renews before expiry when a QQ key lasts less than one day", async () => {
|
||||
const shortLived = { ...first, keyExpiresIn: 3600 };
|
||||
vi.mocked(client.pollQr).mockResolvedValueOnce({ status: "confirmed", credential: shortLived });
|
||||
await scan();
|
||||
await vi.advanceTimersByTimeAsync(54 * MINUTE - 1);
|
||||
expect(client.refresh).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(client.refresh).toHaveBeenCalledWith(shortLived);
|
||||
});
|
||||
|
||||
it("keeps scheduling before expiry after a same-key token rotation", async () => {
|
||||
const shortLived = { ...first, keyExpiresIn: 3600 };
|
||||
vi.mocked(client.pollQr).mockResolvedValueOnce({ status: "confirmed", credential: shortLived });
|
||||
await scan();
|
||||
vi.setSystemTime(NOW.valueOf() + 54 * MINUTE);
|
||||
const rotated = parseQqCredential({
|
||||
musicid: first.musicid, musickey: first.musickey, refresh_token: "rotated-token",
|
||||
}, shortLived)!;
|
||||
vi.mocked(client.refresh).mockResolvedValueOnce({ status: "refreshed", credential: rotated });
|
||||
|
||||
expect(await session.refresh()).toBe("refreshed");
|
||||
expect(store.load()?.credential?.refresh_token).toBe("rotated-token");
|
||||
expect(session.getStatus().nextRefreshAt).toBe(new Date(NOW.valueOf() + 55 * MINUTE).toISOString());
|
||||
});
|
||||
|
||||
it("schedules older saved sessions using QQ's issue time without inventing a last renewal", () => {
|
||||
const older = { ...first, musickeyCreateTime: (NOW.valueOf() - DAY / 2) / 1000 };
|
||||
store.save({ cookie: qqPlaybackCookie(older), credential: older });
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
expect(session.getStatus()).toEqual({
|
||||
renewalStatus: "scheduled",
|
||||
nextRefreshAt: new Date(NOW.valueOf() + DAY / 2).toISOString(),
|
||||
lastRefreshAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("shares an in-flight refresh and uses the rotated credential after restart", async () => {
|
||||
await scan();
|
||||
const a = session.refresh();
|
||||
expect(session.refresh()).toBe(a);
|
||||
expect(await a).toBe("refreshed");
|
||||
expect(client.refresh).toHaveBeenCalledTimes(1);
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
vi.mocked(client.refresh).mockResolvedValueOnce({
|
||||
status: "refreshed", credential: { ...second, musickey: "third-key" },
|
||||
});
|
||||
expect(await session.refresh()).toBe("refreshed");
|
||||
expect(client.refresh).toHaveBeenLastCalledWith(second);
|
||||
expect(session.getCookie()).toContain("qm_keyst=third-key");
|
||||
});
|
||||
|
||||
it("refreshes a web login with OAuth authorization even when QQ omits refresh_key", async () => {
|
||||
const webCredential = { ...first, refresh_key: "" };
|
||||
vi.mocked(client.pollQr).mockResolvedValueOnce({ status: "confirmed", credential: webCredential });
|
||||
await scan();
|
||||
expect(session.getStatus().renewalStatus).toBe("scheduled");
|
||||
expect(await session.refresh()).toBe("refreshed");
|
||||
expect(client.refresh).toHaveBeenCalledWith(webCredential);
|
||||
});
|
||||
|
||||
it("keeps the current cookie on rate limiting and retries after the backoff", async () => {
|
||||
await scan();
|
||||
vi.mocked(client.refresh).mockResolvedValueOnce({ status: "rate_limited" });
|
||||
expect(await session.refresh()).toBe("rate_limited");
|
||||
expect(session.getStatus()).toMatchObject({ renewalStatus: "retrying" });
|
||||
expect(await session.refresh()).toBe("cooldown");
|
||||
expect(store.load()?.credential).toEqual(first);
|
||||
await vi.advanceTimersByTimeAsync(15 * MINUTE);
|
||||
expect(client.refresh).toHaveBeenCalledTimes(2);
|
||||
expect(store.load()?.credential).toEqual(second);
|
||||
});
|
||||
|
||||
it("retries only the disk write when QQ has already rotated the credential", async () => {
|
||||
await scan();
|
||||
vi.spyOn(store, "save").mockImplementationOnce(() => { throw new Error("test write failed"); });
|
||||
expect(await session.refresh()).toBe("persist_failed");
|
||||
expect(session.getCookie()).toContain("qm_keyst=first-key");
|
||||
expect(session.getStatus().lastRefreshAt).toBeNull();
|
||||
await vi.advanceTimersByTimeAsync(5 * MINUTE);
|
||||
expect(client.refresh).toHaveBeenCalledTimes(1);
|
||||
expect(store.load()?.credential).toEqual(second);
|
||||
expect(session.getCookie()).toContain("qm_keyst=second-key");
|
||||
expect(session.getStatus().lastRefreshAt).toBe(new Date(NOW.valueOf() + 5 * MINUTE).toISOString());
|
||||
});
|
||||
|
||||
it("discards a late response when an operator imports another account", async () => {
|
||||
await scan();
|
||||
let resolve!: (response: QqRefreshResult) => void;
|
||||
vi.mocked(client.refresh).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
|
||||
const refresh = session.refresh();
|
||||
session.setCookie("uin=999; qm_keyst=manual");
|
||||
resolve({ status: "refreshed", credential: second });
|
||||
expect(await refresh).toBe("superseded");
|
||||
expect(store.load()).toMatchObject({ cookie: "uin=999; qm_keyst=manual" });
|
||||
expect(store.load()?.credential).toBeUndefined();
|
||||
expect(await session.refresh()).toBe("reauth_required");
|
||||
});
|
||||
|
||||
it("does not accept another account from the upstream refresh endpoint", async () => {
|
||||
await scan();
|
||||
vi.mocked(client.refresh).mockResolvedValueOnce({
|
||||
status: "refreshed", credential: { ...second, musicid: 999 },
|
||||
});
|
||||
expect(await session.refresh()).toBe("upstream_error");
|
||||
expect(store.load()?.credential).toEqual(first);
|
||||
});
|
||||
|
||||
it("persists a suspension when QQ explicitly rejects renewal", async () => {
|
||||
await scan();
|
||||
vi.mocked(client.refresh).mockResolvedValueOnce({ status: "reauth_required" });
|
||||
expect(await session.refresh()).toBe("reauth_required");
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
expect(session.getStatus()).toEqual({ renewalStatus: "reauth_required", nextRefreshAt: null, lastRefreshAt: null });
|
||||
expect(await session.refresh()).toBe("reauth_required");
|
||||
expect(client.refresh).toHaveBeenCalledTimes(1);
|
||||
expect(session.getCookie()).toContain("qm_keyst=first-key");
|
||||
});
|
||||
|
||||
it("preserves a legacy cookie and renews daily even when QQ omits the key expiration", async () => {
|
||||
createCookieStore(dir).save("qq", "uin=123; qm_keyst=legacy");
|
||||
session.stop();
|
||||
store = createQqSessionStore(file, path.join(dir, "qq.json"));
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
expect(session.getCookie()).toContain("qm_keyst=legacy");
|
||||
expect(session.getStatus()).toEqual({ renewalStatus: "cookie_only", nextRefreshAt: null, lastRefreshAt: null });
|
||||
expect(fs.existsSync(file)).toBe(false);
|
||||
vi.mocked(client.pollQr).mockResolvedValueOnce({
|
||||
status: "confirmed", credential: { ...first, musickeyCreateTime: 0, keyExpiresIn: 0 },
|
||||
});
|
||||
await scan();
|
||||
expect(session.getStatus()).toMatchObject({
|
||||
renewalStatus: "scheduled",
|
||||
nextRefreshAt: new Date(NOW.valueOf() + DAY).toISOString(),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(DAY);
|
||||
expect(client.refresh).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("shares the current login across managed and unmanaged restarts", async () => {
|
||||
const legacyFile = path.join(dir, "qq.json");
|
||||
store = createQqSessionStore(file, legacyFile);
|
||||
session.stop();
|
||||
session = new QQManagedSession(client, store, logger);
|
||||
await scan();
|
||||
session.stop();
|
||||
|
||||
const cookies = createCookieStore(dir, store);
|
||||
expect(cookies.load("qq")).toBe(qqPlaybackCookie(first));
|
||||
cookies.save("qq", "uin=999; qm_keyst=imported");
|
||||
session = new QQManagedSession(client, createQqSessionStore(file, legacyFile), logger);
|
||||
expect(session.getCookie()).toBe("uin=999; qm_keyst=imported");
|
||||
expect(await session.refresh()).toBe("reauth_required");
|
||||
expect(client.refresh).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("normalises manual cookies in memory and at the shared session store", () => {
|
||||
const raw = "Set-Cookie: uin=999; Path=/\r\nSet-Cookie: qm_keyst=manual; Secure";
|
||||
const expected = "uin=999; qm_keyst=manual";
|
||||
session.setCookie(raw);
|
||||
expect(session.getCookie()).toBe(expected);
|
||||
expect(store.load()?.cookie).toBe(expected);
|
||||
createCookieStore(dir, store).save("qq", raw);
|
||||
expect(store.load()?.cookie).toBe(expected);
|
||||
});
|
||||
|
||||
it("normalises cookies migrated from old installations", () => {
|
||||
const legacyFile = path.join(dir, "qq.json");
|
||||
const raw = "uin=999; Path=/;;qm_keyst=legacy; Secure";
|
||||
fs.writeFileSync(legacyFile, JSON.stringify({ cookie: raw }));
|
||||
store = createQqSessionStore(file, legacyFile);
|
||||
expect(store.load()).toEqual({ cookie: "uin=999; qm_keyst=legacy" });
|
||||
});
|
||||
|
||||
it("uses the newer login when both older session files already exist", () => {
|
||||
const legacyFile = path.join(dir, "qq.json");
|
||||
const legacyCookie = "uin=999; qm_keyst=legacy";
|
||||
fs.writeFileSync(file, JSON.stringify({ version: 1, cookie: qqPlaybackCookie(first), credential: first }));
|
||||
createCookieStore(dir).save("qq", legacyCookie);
|
||||
fs.utimesSync(file, 1, 1);
|
||||
fs.utimesSync(legacyFile, 2, 2);
|
||||
store = createQqSessionStore(file, legacyFile);
|
||||
expect(store.load()).toEqual({ cookie: legacyCookie });
|
||||
|
||||
fs.utimesSync(file, 3, 3);
|
||||
expect(store.load()?.credential).toEqual(first);
|
||||
|
||||
store.save({ cookie: "uin=42; qm_keyst=shared" });
|
||||
fs.utimesSync(file, 1, 1);
|
||||
expect(store.load()?.cookie).toBe("uin=42; qm_keyst=shared");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,294 @@
|
||||
import fs from "node:fs";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { QrCodeResult } from "./provider.js";
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import { hasQqRenewalMaterial, parseQqCredential, qqPlaybackCookie, type QqCredential, type QqLoginClient, type QqPollResult } from "./qq-login.js";
|
||||
|
||||
interface QqSessionRecord {
|
||||
cookie: string;
|
||||
credential?: QqCredential;
|
||||
reauthRequired?: boolean;
|
||||
authorizedAt?: number;
|
||||
lastRefreshAt?: number;
|
||||
}
|
||||
|
||||
type QrStatus = QqPollResult["status"];
|
||||
export type QqRenewalStatus = "cookie_only" | "scheduled" | "retrying" | "reauth_required";
|
||||
export type QqRenewalResult = "refreshed" | "reauth_required" | "upstream_error" | "rate_limited" | "persist_failed" | "cooldown" | "superseded";
|
||||
|
||||
const MINUTE = 60_000;
|
||||
const DAY = 24 * 60 * MINUTE;
|
||||
const QR_TTL = 3 * MINUTE;
|
||||
|
||||
function timestamp(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= 8.64e15
|
||||
? value : undefined;
|
||||
}
|
||||
|
||||
function expiryTime(credential: QqCredential): number | undefined {
|
||||
if (!credential.musickeyCreateTime || !credential.keyExpiresIn) return;
|
||||
return timestamp((credential.musickeyCreateTime + credential.keyExpiresIn) * 1000);
|
||||
}
|
||||
|
||||
export function createQqSessionStore(file: string, legacyFile?: string) {
|
||||
function loadLegacy(newerThan = -Infinity): QqSessionRecord | undefined {
|
||||
if (!legacyFile) return;
|
||||
try {
|
||||
if (fs.statSync(legacyFile).mtimeMs <= newerThan) return;
|
||||
const { cookie } = JSON.parse(fs.readFileSync(legacyFile, "utf8"));
|
||||
const clean = typeof cookie === "string" ? normalizeCookie(cookie) : "";
|
||||
if (clean) return { cookie: clean };
|
||||
} catch { /* The legacy cookie is missing or unreadable. */ }
|
||||
}
|
||||
|
||||
return {
|
||||
load(): QqSessionRecord | undefined {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = fs.readFileSync(file, "utf8");
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === "ENOENT") return loadLegacy();
|
||||
throw err;
|
||||
}
|
||||
const data = JSON.parse(raw);
|
||||
if (data?.version !== 1 || typeof data.cookie !== "string") throw new Error("Invalid QQ session record");
|
||||
// Before the stores were shared, a newer login could be in the legacy file.
|
||||
if (data.shared !== true && legacyFile) {
|
||||
const legacy = loadLegacy(fs.statSync(file).mtimeMs);
|
||||
if (legacy) return legacy;
|
||||
}
|
||||
const credential = parseQqCredential(data.credential);
|
||||
const cookie = normalizeCookie(data.cookie);
|
||||
if (data.credential && (!credential || qqPlaybackCookie(credential) !== cookie)) {
|
||||
throw new Error("Invalid QQ session credential");
|
||||
}
|
||||
return {
|
||||
cookie,
|
||||
credential,
|
||||
reauthRequired: data.reauthRequired === true,
|
||||
authorizedAt: timestamp(data.authorizedAt),
|
||||
lastRefreshAt: timestamp(data.lastRefreshAt),
|
||||
};
|
||||
},
|
||||
save(data: QqSessionRecord): void {
|
||||
const temp = path.join(path.dirname(file), `.qq-session-${randomUUID()}.tmp`);
|
||||
try {
|
||||
fs.writeFileSync(temp, JSON.stringify({ version: 1, shared: true, ...data, cookie: normalizeCookie(data.cookie) }), {
|
||||
encoding: "utf8", mode: 0o600, flag: "wx", flush: true,
|
||||
});
|
||||
fs.renameSync(temp, file);
|
||||
} finally {
|
||||
try { fs.unlinkSync(temp); } catch { /* Already renamed or unavailable. */ }
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface ActiveQr {
|
||||
key: string;
|
||||
sig: string;
|
||||
expiresAt: number;
|
||||
terminal?: "confirmed" | "expired";
|
||||
poll?: Promise<QrStatus>;
|
||||
}
|
||||
|
||||
export class QQManagedSession {
|
||||
private state: QqSessionRecord = { cookie: "" };
|
||||
private generation = 0;
|
||||
private qrGeneration = 0;
|
||||
private qr?: ActiveQr;
|
||||
private inFlight?: Promise<QqRenewalResult>;
|
||||
private pending?: { record: QqSessionRecord; result: "refreshed" | "reauth_required" };
|
||||
private timer?: ReturnType<typeof setTimeout>;
|
||||
private retryAt?: number;
|
||||
private nextAttempt?: number;
|
||||
private failures = 0;
|
||||
private stopped = false;
|
||||
|
||||
constructor(
|
||||
private readonly client: QqLoginClient,
|
||||
private readonly store: ReturnType<typeof createQqSessionStore>,
|
||||
private readonly logger: Logger,
|
||||
) {
|
||||
try {
|
||||
const saved = store.load();
|
||||
if (saved) this.state = saved;
|
||||
} catch {
|
||||
logger.warn("Could not read QQ managed session");
|
||||
}
|
||||
this.schedule();
|
||||
}
|
||||
|
||||
getCookie(): string {
|
||||
return this.state.cookie;
|
||||
}
|
||||
|
||||
getStatus(): { renewalStatus: QqRenewalStatus; nextRefreshAt: string | null; lastRefreshAt: string | null } {
|
||||
const renewalStatus = this.retryAt ? "retrying"
|
||||
: this.state.reauthRequired ? "reauth_required"
|
||||
: !hasQqRenewalMaterial(this.state.credential) ? "cookie_only"
|
||||
: "scheduled";
|
||||
const { lastRefreshAt } = this.state;
|
||||
return {
|
||||
renewalStatus,
|
||||
nextRefreshAt: this.nextAttempt === undefined ? null : new Date(this.nextAttempt).toISOString(),
|
||||
lastRefreshAt: lastRefreshAt === undefined ? null : new Date(lastRefreshAt).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
setCookie(cookie: string): void {
|
||||
this.replace({ cookie: normalizeCookie(cookie) });
|
||||
this.qrGeneration++;
|
||||
this.qr = undefined;
|
||||
}
|
||||
|
||||
async getQrCode(): Promise<QrCodeResult> {
|
||||
const generation = ++this.qrGeneration;
|
||||
this.qr = undefined;
|
||||
const { img, sig } = await this.client.getQr();
|
||||
if (this.stopped || generation !== this.qrGeneration) throw new Error("QQ QR code superseded");
|
||||
const key = randomUUID();
|
||||
this.qr = { key, sig, expiresAt: Date.now() + QR_TTL };
|
||||
return { key, qrUrl: "", qrImg: img };
|
||||
}
|
||||
|
||||
async checkQrCodeStatus(key: string): Promise<QrStatus> {
|
||||
const qr = this.qr;
|
||||
if (!qr || qr.key !== key || this.stopped || qr.expiresAt <= Date.now()) return "expired";
|
||||
if (qr.terminal) return qr.terminal;
|
||||
qr.poll ??= this.poll(qr).finally(() => { qr.poll = undefined; });
|
||||
return qr.poll;
|
||||
}
|
||||
|
||||
private async poll(qr: ActiveQr): Promise<QrStatus> {
|
||||
const result = await this.client.pollQr(qr.sig);
|
||||
if (this.stopped || this.qr !== qr || qr.expiresAt <= Date.now()) return "expired";
|
||||
if (result.status === "confirmed") {
|
||||
try {
|
||||
this.replace({
|
||||
cookie: qqPlaybackCookie(result.credential),
|
||||
credential: result.credential,
|
||||
authorizedAt: Date.now(),
|
||||
});
|
||||
} catch {
|
||||
this.logger.warn("Could not save QQ login");
|
||||
return qr.terminal = "expired";
|
||||
}
|
||||
qr.terminal = "confirmed";
|
||||
}
|
||||
if (result.status === "expired") qr.terminal = "expired";
|
||||
return result.status;
|
||||
}
|
||||
|
||||
private replace(record: QqSessionRecord): void {
|
||||
this.store.save(record);
|
||||
this.state = record;
|
||||
this.generation++;
|
||||
this.inFlight = undefined;
|
||||
this.pending = undefined;
|
||||
this.retryAt = undefined;
|
||||
this.failures = 0;
|
||||
this.schedule();
|
||||
}
|
||||
|
||||
private schedule(earliest = 0): void {
|
||||
clearTimeout(this.timer);
|
||||
this.nextAttempt = undefined;
|
||||
if (this.stopped) return;
|
||||
const credential = this.state.credential;
|
||||
this.nextAttempt = this.retryAt;
|
||||
if (this.nextAttempt === undefined && !this.state.reauthRequired && hasQqRenewalMaterial(credential)) {
|
||||
const now = Date.now();
|
||||
// Older session records predate local timestamps. Use QQ's key creation
|
||||
// time to establish their first due date without inventing a renewal history.
|
||||
const keyCreatedAt = credential.musickeyCreateTime
|
||||
? timestamp(credential.musickeyCreateTime * 1000) : undefined;
|
||||
const anchor = this.state.lastRefreshAt ?? this.state.authorizedAt ?? keyCreatedAt;
|
||||
const dailyAt = anchor === undefined ? now : Math.min(anchor, now) + DAY;
|
||||
const expiresAt = expiryTime(credential);
|
||||
const leadTime = Math.min(30 * MINUTE, credential.keyExpiresIn * 100);
|
||||
const dueAt = expiresAt === undefined ? dailyAt : Math.min(dailyAt, expiresAt - leadTime);
|
||||
this.nextAttempt = Math.max(earliest, now, dueAt);
|
||||
}
|
||||
if (this.nextAttempt === undefined) return;
|
||||
this.timer = setTimeout(() => {
|
||||
if (this.nextAttempt !== undefined && Date.now() < this.nextAttempt) this.schedule(earliest);
|
||||
else void this.refresh();
|
||||
}, Math.min(2 ** 31 - 1, this.nextAttempt - Date.now()));
|
||||
this.timer.unref();
|
||||
}
|
||||
|
||||
refresh(): Promise<QqRenewalResult> {
|
||||
if (this.stopped) return Promise.resolve("superseded");
|
||||
if (this.inFlight) return this.inFlight;
|
||||
if (this.retryAt && Date.now() < this.retryAt) return Promise.resolve("cooldown");
|
||||
if (this.pending) return Promise.resolve(this.commitPending());
|
||||
const credential = this.state.credential;
|
||||
if (!hasQqRenewalMaterial(credential) || this.state.reauthRequired) return Promise.resolve("reauth_required");
|
||||
const generation = this.generation;
|
||||
this.inFlight = this.renew(credential, generation).finally(() => {
|
||||
if (generation === this.generation) this.inFlight = undefined;
|
||||
});
|
||||
return this.inFlight;
|
||||
}
|
||||
|
||||
private async renew(credential: QqCredential, generation: number): Promise<QqRenewalResult> {
|
||||
const result = await this.client.refresh(credential).catch(() => ({ status: "upstream_error" } as const));
|
||||
if (this.stopped || this.generation !== generation) return "superseded";
|
||||
if (result.status === "reauth_required") {
|
||||
this.pending = { record: { ...this.state, reauthRequired: true }, result: "reauth_required" };
|
||||
return this.commitPending();
|
||||
}
|
||||
if (result.status === "refreshed") {
|
||||
const next = result.credential;
|
||||
const renewed = next.musickey !== credential.musickey
|
||||
|| (expiryTime(next) ?? 0) > (expiryTime(credential) ?? 0)
|
||||
|| (next.refresh_key && next.refresh_key !== credential.refresh_key)
|
||||
|| (next.refresh_token && next.refresh_token !== credential.refresh_token);
|
||||
if (next.musicid === credential.musicid && renewed) {
|
||||
this.pending = {
|
||||
record: { cookie: qqPlaybackCookie(next), credential: next, reauthRequired: !hasQqRenewalMaterial(next) },
|
||||
result: "refreshed",
|
||||
};
|
||||
return this.commitPending();
|
||||
}
|
||||
}
|
||||
const outcome = result.status === "rate_limited" ? "rate_limited" : "upstream_error";
|
||||
this.defer(outcome);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
private commitPending(): QqRenewalResult {
|
||||
const pending = this.pending!;
|
||||
const record = pending.result === "refreshed"
|
||||
? { ...pending.record, lastRefreshAt: Date.now() }
|
||||
: pending.record;
|
||||
try {
|
||||
this.store.save(record);
|
||||
} catch {
|
||||
this.defer("persist_failed");
|
||||
return "persist_failed";
|
||||
}
|
||||
this.state = record;
|
||||
this.pending = undefined;
|
||||
this.retryAt = undefined;
|
||||
this.failures = 0;
|
||||
this.schedule(Date.now() + MINUTE);
|
||||
this.logger.info({ outcome: pending.result }, "QQ session renewal");
|
||||
return pending.result;
|
||||
}
|
||||
|
||||
private defer(outcome: "rate_limited" | "upstream_error" | "persist_failed"): void {
|
||||
const initialMinutes = outcome === "rate_limited" ? 15 : 5;
|
||||
this.retryAt = Date.now() + Math.min(60, initialMinutes * 2 ** this.failures++) * MINUTE;
|
||||
this.schedule();
|
||||
this.logger.warn({ outcome }, "QQ session renewal deferred");
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
this.schedule();
|
||||
}
|
||||
}
|
||||
+32
-4
@@ -1,3 +1,4 @@
|
||||
import { normalizeCookie } from "./cookie-normalize.js";
|
||||
import axios, { type AxiosInstance } from "axios";
|
||||
import type {
|
||||
MusicProvider,
|
||||
@@ -15,6 +16,7 @@ import type {
|
||||
ArtistSongPage,
|
||||
} from "./provider.js";
|
||||
import { parseLyrics } from "./netease.js";
|
||||
import type { QQManagedSession } from "./qq-session.js";
|
||||
|
||||
// Primary search client: u.y.qq.com/cgi-bin/musicu.fcg (JSON sub-request
|
||||
// batch). Was broken ca. 2026-05 due to two upstream API changes:
|
||||
@@ -171,17 +173,21 @@ function computeGtk(pSkey: string): number {
|
||||
export class QQMusicProvider implements MusicProvider {
|
||||
readonly platform = "qq" as const;
|
||||
private api: AxiosInstance;
|
||||
private cookie = "";
|
||||
private legacyCookie = "";
|
||||
private quality = "exhigh";
|
||||
private radarPage = 1;
|
||||
|
||||
constructor(baseUrl: string) {
|
||||
constructor(baseUrl: string, readonly managedSession?: QQManagedSession) {
|
||||
this.api = axios.create({
|
||||
baseURL: baseUrl,
|
||||
timeout: 10000,
|
||||
});
|
||||
}
|
||||
|
||||
private get cookie(): string {
|
||||
return this.managedSession?.getCookie() ?? this.legacyCookie;
|
||||
}
|
||||
|
||||
setQuality(quality: string): void {
|
||||
this.quality = quality;
|
||||
}
|
||||
@@ -768,6 +774,7 @@ export class QQMusicProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
async getQrCode(): Promise<QrCodeResult> {
|
||||
if (this.managedSession) return this.managedSession.getQrCode();
|
||||
// @sansenjian/qq-music-api 2.x returns { img, qrsig, ptqrtoken } via
|
||||
// customResponse (no { response: ... } wrapping). /checkQQLoginQr
|
||||
// requires BOTH qrsig AND ptqrtoken — passing only one gives a 400
|
||||
@@ -787,6 +794,12 @@ export class QQMusicProvider implements MusicProvider {
|
||||
async checkQrCodeStatus(
|
||||
key: string
|
||||
): Promise<"waiting" | "scanned" | "confirmed" | "expired"> {
|
||||
if (this.managedSession) {
|
||||
const previous = this.cookie;
|
||||
const status = await this.managedSession.checkQrCodeStatus(key);
|
||||
if (status === "confirmed" && this.cookie !== previous) this.radarPage = 1;
|
||||
return status;
|
||||
}
|
||||
const [qrsig, ptqrtoken] = key.split("|");
|
||||
if (!qrsig || !ptqrtoken) return "expired";
|
||||
|
||||
@@ -808,7 +821,7 @@ export class QQMusicProvider implements MusicProvider {
|
||||
const body = res.data;
|
||||
if (body?.isOk === true) {
|
||||
const cookie: string = body.session?.cookie ?? "";
|
||||
if (cookie) this.cookie = cookie;
|
||||
if (cookie) this.setCookie(cookie);
|
||||
return "confirmed";
|
||||
}
|
||||
if (body?.refresh === true) return "expired";
|
||||
@@ -818,12 +831,27 @@ export class QQMusicProvider implements MusicProvider {
|
||||
}
|
||||
|
||||
setCookie(cookie: string): void {
|
||||
this.cookie = cookie;
|
||||
if (this.managedSession) this.managedSession.setCookie(cookie);
|
||||
else this.legacyCookie = normalizeCookie(cookie);
|
||||
// Reset radar pagination so a re-login (different account) starts from the
|
||||
// first page rather than inheriting the previous account's cursor.
|
||||
this.radarPage = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* A view of the same provider logged in as another account (#164 follow-up):
|
||||
* a web user's own QQ 音乐 login instead of the bot's shared one.
|
||||
*
|
||||
* The per-user view points at the SAME API server (`this.api.defaults.baseURL`)
|
||||
* — only the cookie differs, so the shared login keeps its own instance.
|
||||
*/
|
||||
withCookie(cookie: string): QQMusicProvider {
|
||||
const view = new QQMusicProvider(this.api.defaults.baseURL ?? "");
|
||||
view.quality = this.quality;
|
||||
view.setCookie(cookie);
|
||||
return view;
|
||||
}
|
||||
|
||||
getCookie(): string {
|
||||
return this.cookie;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { isAxiosError } from "axios";
|
||||
|
||||
/** Axios errors can include music-account cookies in the message or config. */
|
||||
export function musicRequestError(error: unknown): Error {
|
||||
if (isAxiosError(error)) {
|
||||
const status = error.response?.status;
|
||||
return new Error(typeof status === "number" ? `Music service request failed (HTTP ${status})` : "Music service request failed");
|
||||
}
|
||||
return error instanceof Error ? error : new Error("Music service request failed");
|
||||
}
|
||||
@@ -29,7 +29,11 @@ function withFakeClient(
|
||||
): string[] {
|
||||
const calls: string[] = [];
|
||||
const fake = {
|
||||
execCommandWithResponse: vi.fn(async (cmd: string) => {
|
||||
send: vi.fn(async (req: { command: string; params?: readonly (readonly [string, unknown])[] }) => {
|
||||
const paramPairs = (req.params ?? [])
|
||||
.filter(([, v]) => v !== undefined)
|
||||
.map(([k, v]) => `${k}=${String(v)}`);
|
||||
const cmd = paramPairs.length > 0 ? `${req.command} ${paramPairs.join(" ")}` : req.command;
|
||||
calls.push(cmd);
|
||||
return respond(cmd);
|
||||
}),
|
||||
|
||||
@@ -1,34 +1,77 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { Client as SDKClient, type ResolvedAddr } from "@honeybbq/teamspeak-client";
|
||||
import { Resolver } from "@honeybbq/teamspeak-client/discovery";
|
||||
import { Resolver, type Client as SDKClient, type ClientOptions as SDKClientOptions, type ResolvedAddr } from "@honeybbq/teamspeak/client";
|
||||
import { TS3Client, type TS3VoiceSendFailure } from "./client.js";
|
||||
import type { TrackingVoiceEndpointResolver } from "./voice-endpoint.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
|
||||
class FakeSdkClient extends EventEmitter {
|
||||
clientID = 0;
|
||||
channelID = 1n;
|
||||
uid = "fake-uid";
|
||||
readonly addr: string;
|
||||
readonly options: SDKClientOptions;
|
||||
|
||||
constructor(addr: string, options: SDKClientOptions) {
|
||||
super();
|
||||
this.addr = addr;
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
this.clientID = 42;
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.emit("disconnected", { error: undefined, willReconnect: false });
|
||||
}
|
||||
|
||||
async send(_request: { command: string; params?: Record<string, unknown> }): Promise<Record<string, string>[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
sendVoice(_data: Uint8Array, _codec: number): void {}
|
||||
|
||||
emitDisconnected(error?: Error): void {
|
||||
this.emit("disconnected", { error, willReconnect: false });
|
||||
}
|
||||
}
|
||||
|
||||
type Failure = TS3VoiceSendFailure;
|
||||
type Harness = { client: SDKClient | null; voiceFramesSent: number };
|
||||
type Harness = { client: FakeSdkClient | null; voiceFramesSent: number };
|
||||
|
||||
describe("TS3Client voice send failure lifecycle", () => {
|
||||
let client: TS3Client;
|
||||
let sdk: SDKClient;
|
||||
let sdk: FakeSdkClient;
|
||||
let logger: Logger;
|
||||
let records: Array<{ level: string; args: unknown[] }>;
|
||||
let onCreateSdk: ((sdk: FakeSdkClient) => void) | undefined;
|
||||
|
||||
const createClient = (extra: Partial<ConstructorParameters<typeof TS3Client>[0]> = {}) =>
|
||||
new TS3Client(
|
||||
{
|
||||
host: "localhost",
|
||||
port: 9987,
|
||||
queryPort: 10011,
|
||||
nickname: "VoiceTest",
|
||||
serverProtocol: "ts3",
|
||||
sdkClientFactory: (_identity, addr, _nickname, sdkOptions) => {
|
||||
const fake = new FakeSdkClient(addr, sdkOptions);
|
||||
onCreateSdk?.(fake);
|
||||
return fake as unknown as SDKClient;
|
||||
},
|
||||
...extra,
|
||||
},
|
||||
logger,
|
||||
);
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.useFakeTimers();
|
||||
// Keep the real SDK object, logger bridge and event dispatch. Replace only
|
||||
// its network handshake and explicit shutdown so no UDP socket is opened.
|
||||
vi.spyOn(SDKClient.prototype, "connect").mockImplementation(async function (this: SDKClient) {
|
||||
this.clid = 42;
|
||||
this._markConnected();
|
||||
});
|
||||
vi.spyOn(SDKClient.prototype, "disconnect").mockImplementation(async function (this: SDKClient) {
|
||||
this.handler.onClosed?.(null);
|
||||
});
|
||||
records = [];
|
||||
onCreateSdk = undefined;
|
||||
const capture = (level: string) => (...args: unknown[]) => records.push({ level, args });
|
||||
logger = { info: capture("info"), warn: capture("warn"), error: capture("error"), debug() {} } as unknown as Logger;
|
||||
client = new TS3Client({ host: "localhost", port: 9987, queryPort: 10011, nickname: "VoiceTest", serverProtocol: "ts3" }, logger);
|
||||
client = createClient();
|
||||
await client.connect();
|
||||
sdk = (client as unknown as Harness).client!;
|
||||
});
|
||||
@@ -141,7 +184,7 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
send.mockImplementation(() => { throw { code: "EPIPE" }; });
|
||||
client.sendVoiceData(Buffer.from([1]));
|
||||
sdk.handler.onClosed?.(new Error("synthetic connection loss"));
|
||||
sdk.emitDisconnected(new Error("synthetic connection loss"));
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(terminal).toEqual([]);
|
||||
expect((client as unknown as Harness).voiceFramesSent).toBe(0);
|
||||
@@ -152,22 +195,21 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
|
||||
it("does not revive a connection whose handshake was cancelled", async () => {
|
||||
let finishHandshake!: () => void;
|
||||
vi.spyOn(SDKClient.prototype, "connect").mockImplementationOnce(function (this: SDKClient) {
|
||||
return new Promise<void>(resolve => {
|
||||
onCreateSdk = (fake) => {
|
||||
vi.spyOn(fake, "connect").mockImplementationOnce(() => new Promise<void>(resolve => {
|
||||
finishHandshake = () => {
|
||||
this.clid = 99;
|
||||
this._markConnected();
|
||||
fake.clientID = 99;
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
});
|
||||
}));
|
||||
};
|
||||
const connected = vi.fn();
|
||||
client.on("connected", connected);
|
||||
const pending = client.connect();
|
||||
await Promise.resolve();
|
||||
expect(finishHandshake).toBeTypeOf("function");
|
||||
const connectingSdk = (client as unknown as Harness).client!;
|
||||
const close = vi.spyOn(connectingSdk.handler, "close");
|
||||
const close = vi.spyOn(connectingSdk, "disconnect");
|
||||
const send = vi.spyOn(connectingSdk, "sendVoice");
|
||||
client.disconnect();
|
||||
finishHandshake();
|
||||
@@ -188,7 +230,7 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
await client.connect();
|
||||
// Old disconnect dispatch is queued; old socket callbacks may follow it.
|
||||
const before = records.length;
|
||||
sdk.logger.warn("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" }));
|
||||
sdk.options.logger?.warn?.("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" }));
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(client.getClientId()).toBe(42);
|
||||
expect(records.slice(before).filter(record => record.level === "warn")).toEqual([]);
|
||||
@@ -198,28 +240,44 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
it("does not let an older named-channel lookup move the replacement connection", async () => {
|
||||
client.disconnect();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
client = new TS3Client({ host: "localhost", port: 9987, queryPort: 10011, nickname: "VoiceTest", serverProtocol: "ts3", defaultChannel: "Music" }, logger);
|
||||
client = createClient({ defaultChannel: "Music" });
|
||||
let nextClientId = 101;
|
||||
vi.mocked(SDKClient.prototype.connect).mockImplementation(async function (this: SDKClient) {
|
||||
this.clid = nextClientId++;
|
||||
this._markConnected();
|
||||
});
|
||||
let finishOlderLookup!: (rows: Record<string, string>[]) => void;
|
||||
vi.spyOn(SDKClient.prototype, "execCommandWithResponse").mockImplementation(function (this: SDKClient) {
|
||||
if (this.clid === 101) return new Promise(resolve => { finishOlderLookup = resolve; });
|
||||
return Promise.resolve([{ cid: "20", channel_name: "Music" }]);
|
||||
});
|
||||
const moves: Array<{ clientId: number; command: string }> = [];
|
||||
vi.spyOn(SDKClient.prototype, "execCommand").mockImplementation(async function (this: SDKClient, command: string) {
|
||||
moves.push({ clientId: this.clid, command });
|
||||
});
|
||||
const moves: Array<{ clientId: number; command: string; params: Record<string, unknown> | undefined }> = [];
|
||||
onCreateSdk = (fake) => {
|
||||
vi.spyOn(fake, "connect").mockImplementation(async () => {
|
||||
fake.clientID = nextClientId++;
|
||||
});
|
||||
vi.spyOn(fake, "send").mockImplementation(async (req) => {
|
||||
if (req.command === "channellist") {
|
||||
if (fake.clientID === 101) {
|
||||
return new Promise(resolve => { finishOlderLookup = resolve; });
|
||||
}
|
||||
return [{ cid: "20", channel_name: "Music", pid: "0", channel_order: "0" }];
|
||||
}
|
||||
if (req.command === "clientmove") {
|
||||
moves.push({ clientId: fake.clientID, command: req.command, params: req.params });
|
||||
}
|
||||
return [];
|
||||
});
|
||||
};
|
||||
const first = client.connect();
|
||||
for (let i = 0; i < 8; i++) await Promise.resolve();
|
||||
expect(finishOlderLookup).toBeTypeOf("function");
|
||||
await client.connect();
|
||||
finishOlderLookup([{ cid: "10", channel_name: "Music" }]);
|
||||
finishOlderLookup([{ cid: "10", channel_name: "Music", pid: "0", channel_order: "0" }]);
|
||||
await first;
|
||||
expect(moves).toEqual([{ clientId: 102, command: "clientmove clid=102 cid=20" }]);
|
||||
expect(moves).toEqual([
|
||||
{
|
||||
clientId: 102,
|
||||
command: "clientmove",
|
||||
params: [
|
||||
["clid", 102],
|
||||
["cid", 20n],
|
||||
["cpw", undefined],
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(records.filter(record => record.args[1] === "Joined channel").map(record => record.args[0])).toEqual([{ channelName: "Music", cid: "20" }]);
|
||||
expect(client.getClientId()).toBe(102);
|
||||
});
|
||||
@@ -230,13 +288,14 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
vi.spyOn(Resolver.prototype, "resolve").mockImplementationOnce(() => new Promise(resolve => { finishOlderResolution = resolve; }))
|
||||
.mockResolvedValue([row("192.0.2.2:9987")]);
|
||||
let sequence = 0;
|
||||
vi.mocked(SDKClient.prototype.connect).mockImplementation(async function (this: SDKClient) {
|
||||
const clientId = 101 + sequence++;
|
||||
const resolver = (client as unknown as { voiceEndpointResolver: TrackingVoiceEndpointResolver }).voiceEndpointResolver;
|
||||
await resolver.resolve("voice.test:9987");
|
||||
this.clid = clientId;
|
||||
this._markConnected();
|
||||
});
|
||||
onCreateSdk = (fake) => {
|
||||
vi.spyOn(fake, "connect").mockImplementation(async () => {
|
||||
const clientId = 101 + sequence++;
|
||||
const resolver = (client as unknown as { voiceEndpointResolver: TrackingVoiceEndpointResolver }).voiceEndpointResolver;
|
||||
await resolver.resolve("voice.test:9987");
|
||||
fake.clientID = clientId;
|
||||
});
|
||||
};
|
||||
const first = client.connect();
|
||||
for (let i = 0; i < 8; i++) await Promise.resolve();
|
||||
expect(finishOlderResolution).toBeTypeOf("function");
|
||||
@@ -249,12 +308,20 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
});
|
||||
|
||||
it.each(["10", "Music"])("does not report an old %s channel move after connection replacement", async channel => {
|
||||
vi.spyOn(SDKClient.prototype, "execCommandWithResponse").mockResolvedValue([{ cid: "10", channel_name: "Music" }]);
|
||||
let finishMove!: () => void;
|
||||
const move = vi.spyOn(sdk, "execCommand").mockImplementation(() => new Promise<void>(resolve => { finishMove = resolve; }));
|
||||
const moveSpy = vi.fn(() => new Promise<void>(resolve => { finishMove = resolve; }));
|
||||
vi.spyOn(sdk, "send").mockImplementation(async (req) => {
|
||||
if (req.command === "channellist") {
|
||||
return [{ cid: "10", channel_name: "Music", pid: "0", channel_order: "0" }];
|
||||
}
|
||||
if (req.command === "clientmove") {
|
||||
await moveSpy();
|
||||
}
|
||||
return [];
|
||||
});
|
||||
const joining = client.joinChannel(channel);
|
||||
for (let i = 0; i < 8; i++) await Promise.resolve();
|
||||
expect(move).toHaveBeenCalledWith("clientmove clid=42 cid=10", 10000);
|
||||
expect(moveSpy).toHaveBeenCalledTimes(1);
|
||||
await client.connect();
|
||||
finishMove();
|
||||
await joining;
|
||||
@@ -263,7 +330,7 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
|
||||
it("does not report a stale channel lookup failure against the new connection", async () => {
|
||||
let failLookup!: (error: Error) => void;
|
||||
vi.spyOn(sdk, "execCommandWithResponse").mockImplementation(() => new Promise((_resolve, reject) => { failLookup = reject; }));
|
||||
vi.spyOn(sdk, "send").mockImplementation(() => new Promise((_resolve, reject) => { failLookup = reject; }));
|
||||
const joining = client.joinChannel("Music");
|
||||
await client.connect();
|
||||
failLookup(new Error("old credential-secret failure"));
|
||||
@@ -275,7 +342,7 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
it("keeps safe async UDP error detail while throttling without terminalizing it", async () => {
|
||||
const terminal: Failure[] = [];
|
||||
client.on("voiceSendFailed", event => terminal.push(event));
|
||||
for (let i = 0; i < 100; i++) sdk.logger.warn("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" }));
|
||||
for (let i = 0; i < 100; i++) sdk.options.logger?.warn?.("udp send error", Object.assign(new Error("credential-secret"), { code: "ECONNREFUSED" }));
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
const warnings = records.filter(record => record.level === "warn");
|
||||
expect(warnings).toHaveLength(2);
|
||||
@@ -286,7 +353,7 @@ describe("TS3Client voice send failure lifecycle", () => {
|
||||
});
|
||||
|
||||
it("discards unsafe async UDP codes and cancels their summary on disconnect", async () => {
|
||||
sdk.logger.warn("udp send error", { code: "credential-secret", message: "credential-secret" });
|
||||
sdk.options.logger?.warn?.("udp send error", { code: "credential-secret", message: "credential-secret" });
|
||||
client.disconnect();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(records.filter(record => record.level === "warn").filter(record => String(record.args[1]).includes("udp send error"))).toHaveLength(1);
|
||||
|
||||
+150
-75
@@ -1,24 +1,39 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Readable } from "node:stream";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
generateIdentity as genTS3Identity,
|
||||
getUidFromPublicKey,
|
||||
identityFromString,
|
||||
sendTextMessage,
|
||||
asChannelID,
|
||||
asClientID,
|
||||
Codec,
|
||||
deleteFile,
|
||||
getClientProperties,
|
||||
initFileUpload,
|
||||
listChannels,
|
||||
listClients,
|
||||
clientMove,
|
||||
getClientInfo,
|
||||
fileTransferDeleteFile,
|
||||
type Identity,
|
||||
type TextMessage,
|
||||
type ClientInfo,
|
||||
type ClientLeftViewEvent,
|
||||
moveClient,
|
||||
sendChannelMessage,
|
||||
sendPluginCommand as sdkSendPluginCommand,
|
||||
sendPrivateMessage,
|
||||
sendServerMessage,
|
||||
type ChannelID,
|
||||
type ClientEnterEvent,
|
||||
type ClientEntry,
|
||||
type ClientLeaveEvent,
|
||||
type ClientMovedEvent,
|
||||
type VoiceData,
|
||||
type DisconnectedEvent,
|
||||
type FileUploadInfo,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
type PluginCommandEvent,
|
||||
type PluginCommandTarget,
|
||||
type TextMessageEvent,
|
||||
type VoiceDataEvent,
|
||||
} from "@honeybbq/teamspeak";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
generateIdentitySync as genTS3Identity,
|
||||
parseIdentity,
|
||||
UIDAlgorithm,
|
||||
type ClientOptions as SDKClientOptions,
|
||||
type Identity,
|
||||
} from "@honeybbq/teamspeak/client";
|
||||
import type { Logger } from "../logger.js";
|
||||
import {
|
||||
detectServerProtocol,
|
||||
@@ -32,7 +47,7 @@ import {
|
||||
|
||||
export { CODEC_OPUS_MUSIC } from "./voice.js";
|
||||
export type { ServerProtocol } from "./protocol-detect.js";
|
||||
export type { FileUploadInfo } from "@honeybbq/teamspeak-client";
|
||||
export type { FileUploadInfo, PluginCommandTarget } from "@honeybbq/teamspeak";
|
||||
|
||||
/** Escape a string for use in TS3 ServerQuery-style commands. */
|
||||
export function escapeTS3(str: string): string {
|
||||
@@ -60,6 +75,13 @@ export interface TS3ClientOptions {
|
||||
serverProtocol?: ServerProtocol;
|
||||
/** API key for TS6 HTTP Query authentication. */
|
||||
ts6ApiKey?: string;
|
||||
/** @internal Test seam to substitute the underlying SDK Client instance. */
|
||||
sdkClientFactory?: (
|
||||
identity: Identity,
|
||||
addr: string,
|
||||
nickname: string,
|
||||
options: SDKClientOptions,
|
||||
) => TS3FullClient;
|
||||
}
|
||||
|
||||
export interface TS3TextMessage {
|
||||
@@ -71,6 +93,14 @@ export interface TS3TextMessage {
|
||||
invokerGroups: string[]; // sender's TS server-group ids; [] when not in view cache
|
||||
}
|
||||
|
||||
export interface TS3PluginCommand {
|
||||
name: string;
|
||||
data: string;
|
||||
invokerId: number;
|
||||
invokerName: string;
|
||||
invokerUid: string;
|
||||
}
|
||||
|
||||
/** Lightweight voice-packet signal used for activity detection. The encoded
|
||||
* payload is intentionally not forwarded beyond this protocol wrapper. */
|
||||
export interface TS3VoiceActivity {
|
||||
@@ -115,26 +145,36 @@ function safeSocketErrorCode(error: unknown): string | undefined {
|
||||
const VISIBLE_CLIENT_UID_RELEASE_GRACE_MS = 1_000;
|
||||
|
||||
/**
|
||||
* Map the library's TextMessage to our wrapper. Preserves invokerGroups (the
|
||||
* Map the library's TextMessageEvent to our wrapper. Preserves invokerGroups (the
|
||||
* sender's TS server groups), which the library populates only when the sender
|
||||
* is in the bot's client-view cache; otherwise it is []. Used by the chat
|
||||
* command permission gate.
|
||||
*/
|
||||
export function toTS3TextMessage(msg: TextMessage): TS3TextMessage {
|
||||
export function toTS3TextMessage(msg: TextMessageEvent): TS3TextMessage {
|
||||
return {
|
||||
invokerName: msg.invokerName,
|
||||
invokerId: String(msg.invokerID),
|
||||
invokerUid: msg.invokerUID,
|
||||
message: msg.message,
|
||||
targetMode: msg.targetMode,
|
||||
invokerGroups: msg.invokerGroups ?? [],
|
||||
invokerGroups: (msg.invokerGroups ?? []).map((groupId) => String(groupId)),
|
||||
};
|
||||
}
|
||||
|
||||
export function toTS3PluginCommand(ev: PluginCommandEvent): TS3PluginCommand {
|
||||
return {
|
||||
name: ev.name,
|
||||
data: ev.data,
|
||||
invokerId: Number(ev.invokerID),
|
||||
invokerName: ev.invokerName,
|
||||
invokerUid: ev.invokerUID,
|
||||
};
|
||||
}
|
||||
|
||||
export class TS3Client extends EventEmitter {
|
||||
private client: TS3FullClient | null = null;
|
||||
private identity: Identity;
|
||||
private readonly clientUid: string;
|
||||
private clientUid: string;
|
||||
private clientId = 0;
|
||||
private readonly visibleClientUids = new Map<number, string>();
|
||||
private readonly visibleClientUidReleaseTimers = new Map<
|
||||
@@ -156,11 +196,11 @@ export class TS3Client extends EventEmitter {
|
||||
this.logger = logger;
|
||||
|
||||
if (options.identity) {
|
||||
this.identity = identityFromString(options.identity);
|
||||
this.identity = parseIdentity(options.identity);
|
||||
} else {
|
||||
this.identity = genTS3Identity(8);
|
||||
}
|
||||
this.clientUid = getUidFromPublicKey(this.identity.publicKeyBase64());
|
||||
this.clientUid = this.identity.uid(UIDAlgorithm.SHA1);
|
||||
}
|
||||
|
||||
/** The detected (or forced) server protocol after connect(). */
|
||||
@@ -275,43 +315,52 @@ export class TS3Client extends EventEmitter {
|
||||
this.logger.warn(msg);
|
||||
};
|
||||
|
||||
sdkClient = new TS3FullClient(this.identity, addr, this.options.nickname, {
|
||||
const sdkOptions: SDKClientOptions = {
|
||||
// Forward server password to the protocol library so it can be
|
||||
// included in clientinit for password-protected servers
|
||||
serverPassword: this.options.serverPassword,
|
||||
resolver: voiceEndpointResolver,
|
||||
logger: {
|
||||
debug: (msg) => { if (isCurrent()) this.logger.debug(msg); },
|
||||
info: (msg) => { if (isCurrent()) this.logger.info(msg); },
|
||||
debug: (msg: string) => { if (isCurrent()) this.logger.debug(msg); },
|
||||
info: (msg: string) => { if (isCurrent()) this.logger.info(msg); },
|
||||
warn: throttledWarn,
|
||||
error: (msg) => { if (isCurrent()) this.logger.error(msg); },
|
||||
error: (msg: string) => { if (isCurrent()) this.logger.error(msg); },
|
||||
},
|
||||
});
|
||||
};
|
||||
sdkClient = this.options.sdkClientFactory
|
||||
? this.options.sdkClientFactory(this.identity, addr, this.options.nickname, sdkOptions)
|
||||
: new TS3FullClient(this.identity, addr, this.options.nickname, sdkOptions);
|
||||
this.client = sdkClient;
|
||||
|
||||
sdkClient.on("textMessage", (msg: TextMessage) => {
|
||||
sdkClient.on("textMessage", (msg: TextMessageEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
if (msg.invokerID === this.clientId) return;
|
||||
this.emit("textMessage", toTS3TextMessage(msg));
|
||||
});
|
||||
|
||||
sdkClient.on("voiceData", (voice: VoiceData) => {
|
||||
sdkClient.on("pluginCommand", (ev: PluginCommandEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
this.emit("pluginCommand", toTS3PluginCommand(ev));
|
||||
});
|
||||
|
||||
sdkClient.on("voiceData", (voice: VoiceDataEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
// The library normally suppresses our own packets; retain the explicit
|
||||
// guard so a future protocol change cannot make a bot duck itself.
|
||||
if (voice.clientId === this.clientId) return;
|
||||
const clientUid = this.visibleClientUids.get(voice.clientId);
|
||||
const voiceClientId = Number(voice.clientID);
|
||||
if (voiceClientId === this.clientId) return;
|
||||
const clientUid = this.visibleClientUids.get(voiceClientId);
|
||||
const activity: TS3VoiceActivity = {
|
||||
clientId: voice.clientId,
|
||||
clientId: voiceClientId,
|
||||
codec: voice.codec,
|
||||
...(clientUid ? { clientUid } : {}),
|
||||
};
|
||||
this.emit("voiceActivity", activity);
|
||||
});
|
||||
|
||||
sdkClient.on("disconnected", (err) => {
|
||||
sdkClient.on("disconnected", (ev: DisconnectedEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
const code = safeSocketErrorCode(err);
|
||||
const code = safeSocketErrorCode(ev.error);
|
||||
this.logger.warn(code ? { code } : {}, "Connection closed");
|
||||
++this.connectionGeneration;
|
||||
this.resetVoiceSendState();
|
||||
@@ -321,48 +370,44 @@ export class TS3Client extends EventEmitter {
|
||||
this.emit("disconnected");
|
||||
});
|
||||
|
||||
sdkClient.on("clientEnter", (info: ClientInfo) => {
|
||||
sdkClient.on("clientEnter", (info: ClientEnterEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
this.rememberVisibleClientUid(info.id, info.uid);
|
||||
this.rememberVisibleClientUid(Number(info.id), info.uid ?? "");
|
||||
this.logger.debug(
|
||||
{ nickname: info.nickname, id: info.id },
|
||||
{ nickname: info.nickname, id: Number(info.id) },
|
||||
"Client entered"
|
||||
);
|
||||
this.emit("clientEnter", info);
|
||||
});
|
||||
|
||||
sdkClient.on("clientLeave", (ev: ClientLeftViewEvent) => {
|
||||
sdkClient.on("clientLeave", (ev: ClientLeaveEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
this.releaseVisibleClientUid(ev.id);
|
||||
this.logger.debug({ id: ev.id }, "Client left");
|
||||
this.emit("clientLeave", ev);
|
||||
const id = Number(ev.clientID);
|
||||
this.releaseVisibleClientUid(id);
|
||||
this.logger.debug({ id }, "Client left");
|
||||
this.emit("clientLeave", { ...ev, id });
|
||||
});
|
||||
|
||||
sdkClient.on("clientMoved", (ev: ClientMovedEvent) => {
|
||||
if (!isCurrent()) return;
|
||||
const id = Number(ev.clientID);
|
||||
this.logger.debug(
|
||||
{ id: ev.id, targetChannelID: ev.targetChannelID.toString() },
|
||||
{ id, targetChannelID: ev.targetChannelID.toString() },
|
||||
"Client moved"
|
||||
);
|
||||
this.emit("clientMoved", ev);
|
||||
this.emit("clientMoved", { ...ev, id });
|
||||
});
|
||||
|
||||
await sdkClient.connect();
|
||||
if (!isCurrent()) {
|
||||
// DNS/socket setup may finish after disconnect() closed the transport.
|
||||
// Close it again without waiting on command replies from a stale session.
|
||||
sdkClient.handler.close();
|
||||
// Handshake may finish after disconnect() or a newer connect() superseded it.
|
||||
await sdkClient.disconnect().catch(() => {});
|
||||
return;
|
||||
}
|
||||
// Note: @honeybbq/teamspeak-client 0.2.x ships a universal clientinit
|
||||
// (client_version "3.?.? [Build: 5680278000]" + matching signature)
|
||||
// that works against both TS3 and TS6 servers. The old 3.6.2 monkey-
|
||||
// patch on handler.sendPacket was removed when we bumped to 0.2.1 — it
|
||||
// would have replaced the library's new correct version with a stale
|
||||
// signature and made TS6 handshakes fail.
|
||||
await sdkClient.waitConnected();
|
||||
if (!isCurrent()) return;
|
||||
this.clientId = sdkClient.clientID();
|
||||
this.clientId = Number(sdkClient.clientID);
|
||||
if (sdkClient.uid) {
|
||||
this.clientUid = sdkClient.uid;
|
||||
}
|
||||
this.voiceFramesSent = 0;
|
||||
this.logger.info(
|
||||
{ clientId: this.clientId, protocol: this.detectedProtocol },
|
||||
@@ -393,7 +438,12 @@ export class TS3Client extends EventEmitter {
|
||||
const isNumeric = /^\d+$/.test(channelName);
|
||||
if (isNumeric) {
|
||||
try {
|
||||
await clientMove(client, clientId, BigInt(channelName), password);
|
||||
await moveClient(
|
||||
client,
|
||||
asClientID(clientId),
|
||||
asChannelID(BigInt(channelName)),
|
||||
password ? { password } : undefined,
|
||||
);
|
||||
if (!isCurrent()) return;
|
||||
this.logger.info({ channelName }, "Joined channel");
|
||||
} catch (err) {
|
||||
@@ -412,7 +462,12 @@ export class TS3Client extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
await clientMove(client, clientId, channel.id, password);
|
||||
await moveClient(
|
||||
client,
|
||||
asClientID(clientId),
|
||||
channel.id,
|
||||
password ? { password } : undefined,
|
||||
);
|
||||
if (!isCurrent()) return;
|
||||
this.logger.info(
|
||||
{ channelName, cid: channel.id.toString() },
|
||||
@@ -425,19 +480,38 @@ export class TS3Client extends EventEmitter {
|
||||
|
||||
async sendTextMessage(
|
||||
message: string,
|
||||
targetMode: number = 2
|
||||
targetMode: number = 2,
|
||||
targetClientId?: number,
|
||||
): Promise<void> {
|
||||
if (!this.client) return;
|
||||
// targetMode 2 = channel, target 0 = current channel
|
||||
const target = targetMode === 2 ? BigInt(0) : BigInt(this.clientId);
|
||||
await sendTextMessage(this.client, targetMode, target, message);
|
||||
if (targetMode === 1) {
|
||||
if (targetClientId === undefined) return;
|
||||
await sendPrivateMessage(this.client, asClientID(targetClientId), message);
|
||||
return;
|
||||
}
|
||||
if (targetMode === 3) {
|
||||
await sendServerMessage(this.client, message);
|
||||
return;
|
||||
}
|
||||
await sendChannelMessage(this.client, message);
|
||||
}
|
||||
|
||||
async getClientsInChannel(): Promise<ClientInfo[]> {
|
||||
async sendPluginCommand(
|
||||
name: string,
|
||||
data: string,
|
||||
target: PluginCommandTarget | number = "channel",
|
||||
): Promise<void> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
const resolvedTarget: PluginCommandTarget =
|
||||
typeof target === "number" ? { clientID: asClientID(target) } : target;
|
||||
await sdkSendPluginCommand(this.client, name, data, resolvedTarget);
|
||||
}
|
||||
|
||||
async getClientsInChannel(): Promise<ClientEntry[]> {
|
||||
if (!this.client) return [];
|
||||
try {
|
||||
const allClients = await listClients(this.client);
|
||||
const myChannelId = this.client.channelID();
|
||||
const myChannelId = this.client.channelID;
|
||||
return allClients.filter((c) => c.channelID === myChannelId);
|
||||
} catch {
|
||||
return [];
|
||||
@@ -454,9 +528,7 @@ export class TS3Client extends EventEmitter {
|
||||
async getClientServerGroups(clid: number): Promise<string[]> {
|
||||
if (!this.client) return [];
|
||||
try {
|
||||
const info = await getClientInfo(this.client, clid);
|
||||
// `client_servergroups`: comma-separated server-group ids (verified in
|
||||
// @honeybbq/teamspeak-client dist/index.mjs; listClients parses the same).
|
||||
const info = await getClientProperties(this.client, asClientID(clid));
|
||||
const raw = info.client_servergroups ?? "";
|
||||
return raw ? raw.split(",") : [];
|
||||
} catch {
|
||||
@@ -468,29 +540,32 @@ export class TS3Client extends EventEmitter {
|
||||
|
||||
async execCommand(cmd: string): Promise<void> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
await this.client.execCommand(cmd);
|
||||
await this.client.exec(cmd);
|
||||
}
|
||||
|
||||
/** Fire a command without waiting for the server's response. */
|
||||
async sendCommandNoWait(cmd: string): Promise<void> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
await this.client.sendCommandNoWait(cmd);
|
||||
await this.client.execNoWait(cmd);
|
||||
}
|
||||
|
||||
async execCommandWithResponse(cmd: string): Promise<Record<string, string>[]> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
return this.client.execCommandWithResponse(cmd);
|
||||
return this.client.exec(cmd);
|
||||
}
|
||||
|
||||
async fileTransferInitUpload(
|
||||
channelID: bigint,
|
||||
channelID: bigint | ChannelID,
|
||||
path: string,
|
||||
password: string,
|
||||
size: bigint,
|
||||
overwrite = true,
|
||||
): Promise<FileUploadInfo> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
return this.client.fileTransferInitUpload(channelID, path, password, size, overwrite);
|
||||
return initFileUpload(this.client, asChannelID(channelID), path, size, {
|
||||
password,
|
||||
overwrite,
|
||||
});
|
||||
}
|
||||
|
||||
async uploadFileData(host: string, info: FileUploadInfo, data: Readable): Promise<void> {
|
||||
@@ -498,9 +573,9 @@ export class TS3Client extends EventEmitter {
|
||||
await this.client.uploadFileData(host, info, data);
|
||||
}
|
||||
|
||||
async fileTransferDeleteFile(channelID: bigint, paths: string[]): Promise<void> {
|
||||
async fileTransferDeleteFile(channelID: bigint | ChannelID, paths: string[]): Promise<void> {
|
||||
if (!this.client) throw new Error("Not connected");
|
||||
await fileTransferDeleteFile(this.client, channelID, paths);
|
||||
await deleteFile(this.client, asChannelID(channelID), paths);
|
||||
}
|
||||
|
||||
/** The server host (needed for file transfer TCP connections). */
|
||||
@@ -511,7 +586,7 @@ export class TS3Client extends EventEmitter {
|
||||
/** The current channel ID of this client. */
|
||||
getChannelId(): bigint {
|
||||
if (!this.client) return 0n;
|
||||
return this.client.channelID();
|
||||
return this.client.channelID;
|
||||
}
|
||||
|
||||
private voiceFramesSent = 0;
|
||||
@@ -520,7 +595,7 @@ export class TS3Client extends EventEmitter {
|
||||
const client = this.client;
|
||||
if (!client || this.disconnecting) return "unavailable";
|
||||
try {
|
||||
client.sendVoice(opusFrame, 5);
|
||||
client.sendVoice(opusFrame, Codec.OpusMusic);
|
||||
} catch (err) {
|
||||
if (this.voiceFailure) {
|
||||
this.voiceFailure.consecutiveFailures++;
|
||||
@@ -581,7 +656,7 @@ export class TS3Client extends EventEmitter {
|
||||
}
|
||||
|
||||
getIdentityExport(): string {
|
||||
return this.identity.toString();
|
||||
return this.identity.export();
|
||||
}
|
||||
|
||||
getClientId(): number {
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import pino from "pino";
|
||||
import { APP_VERSION } from "../version.js";
|
||||
import {
|
||||
ACK_GLOBAL_BURST,
|
||||
ANNOUNCE_DEBOUNCE_MS,
|
||||
ANNOUNCE_RETRY_DELAY_MS,
|
||||
APP_NAME,
|
||||
BOT_CAPABILITIES,
|
||||
COMMANDS_LIST_REQ_COOLDOWN_MS,
|
||||
COMMANDS_PLUGIN,
|
||||
IDENTITY_ANNOUNCE_COOLDOWN_MS,
|
||||
IDENTITY_PLUGIN,
|
||||
IDENTITY_QUERY_COOLDOWN_MS,
|
||||
MAX_CMD_ARGS_CHARS,
|
||||
MAX_CMD_DESC_CHARS,
|
||||
MAX_CMD_NAME_CHARS,
|
||||
MAX_COMMANDS,
|
||||
MAX_PAYLOAD_BYTES,
|
||||
OPEN_PROTOCOL_VERSION,
|
||||
OpenProtocolManager,
|
||||
buildCommandsListAckJson,
|
||||
buildIdentityPayloadJson,
|
||||
buildOpenProtocolCommands,
|
||||
type OpenProtocolRuntimeConfig,
|
||||
type OpenProtocolTransport,
|
||||
} from "./open-protocol.js";
|
||||
import type { TS3PluginCommand } from "./client.js";
|
||||
|
||||
function makeCmd(overrides: Partial<TS3PluginCommand> = {}): TS3PluginCommand {
|
||||
return {
|
||||
name: IDENTITY_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "announce" }),
|
||||
invokerId: 7,
|
||||
invokerName: "Alice",
|
||||
invokerUid: "uid-alice",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("OpenProtocol payload builders", () => {
|
||||
it("builds valid v1 identity payloads with package version under 1024 bytes", () => {
|
||||
const raw = buildIdentityPayloadJson("announce");
|
||||
expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES);
|
||||
expect(JSON.parse(raw)).toEqual({
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action: "announce",
|
||||
client_type: "bot",
|
||||
app_name: APP_NAME,
|
||||
app_version: APP_VERSION,
|
||||
capabilities: [...BOT_CAPABILITIES],
|
||||
});
|
||||
|
||||
const ack = JSON.parse(buildIdentityPayloadJson("announce_ack"));
|
||||
expect(ack.action).toBe("announce_ack");
|
||||
expect(ack.command_prefix).toBeUndefined();
|
||||
});
|
||||
|
||||
it("advertises only playback mode values supported by the bot", () => {
|
||||
for (const locale of ["zh", "en"] as const) {
|
||||
expect(buildOpenProtocolCommands(locale).find(({ name }) => name === "mode")?.args)
|
||||
.toBe("<seq|loop|random|rloop>");
|
||||
}
|
||||
});
|
||||
|
||||
it("builds localized command lists adhering to field caps and <1024 byte UTF-8 limit", () => {
|
||||
for (const locale of ["zh", "en"] as const) {
|
||||
const cmds = buildOpenProtocolCommands(locale);
|
||||
expect(cmds.length).toBeGreaterThan(0);
|
||||
expect(cmds.length).toBeLessThanOrEqual(MAX_COMMANDS);
|
||||
|
||||
for (const cmd of cmds) {
|
||||
expect(Array.from(cmd.name).length).toBeLessThanOrEqual(MAX_CMD_NAME_CHARS);
|
||||
expect(Array.from(cmd.desc).length).toBeLessThanOrEqual(MAX_CMD_DESC_CHARS);
|
||||
if (cmd.args !== undefined) {
|
||||
expect(Array.from(cmd.args).length).toBeLessThanOrEqual(MAX_CMD_ARGS_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
const raw = buildCommandsListAckJson(locale, "!");
|
||||
if (raw === null) throw new Error("Expected a command list for a valid prefix");
|
||||
expect(Buffer.byteLength(raw, "utf8")).toBeLessThan(MAX_PAYLOAD_BYTES);
|
||||
const parsed = JSON.parse(raw) as {
|
||||
v: number;
|
||||
action: string;
|
||||
command_prefix: string;
|
||||
commands: unknown[];
|
||||
};
|
||||
expect(parsed.v).toBe(OPEN_PROTOCOL_VERSION);
|
||||
expect(parsed.action).toBe("list_ack");
|
||||
expect(parsed.command_prefix).toBe("!");
|
||||
expect(parsed.commands.length).toBe(cmds.length);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenProtocolManager", () => {
|
||||
let nowMs: number;
|
||||
let clientId: number;
|
||||
let config: OpenProtocolRuntimeConfig;
|
||||
let sendPluginCommand: ReturnType<typeof vi.fn>;
|
||||
let manager: OpenProtocolManager;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
nowMs = 100_000;
|
||||
clientId = 42;
|
||||
config = { locale: "zh", commandPrefix: "!" };
|
||||
sendPluginCommand = vi.fn(async () => {});
|
||||
const transport: OpenProtocolTransport = {
|
||||
getClientId: () => clientId,
|
||||
sendPluginCommand: sendPluginCommand as OpenProtocolTransport["sendPluginCommand"],
|
||||
};
|
||||
manager = new OpenProtocolManager({
|
||||
transport,
|
||||
getConfig: () => config,
|
||||
logger: pino({ level: "silent" }),
|
||||
now: () => nowMs,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
manager.reset();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("ignores unrelated plugins, self-sent commands, malformed JSON, and non-v1 versions", async () => {
|
||||
await manager.handlePluginCommand(makeCmd({ name: "other:plugin" }));
|
||||
await manager.handlePluginCommand(makeCmd({ invokerId: 42 }));
|
||||
await manager.handlePluginCommand(makeCmd({ data: "{not-json" }));
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 2, action: "query" }) }));
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce_ack" }) }));
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({ name: COMMANDS_PLUGIN, data: JSON.stringify({ v: 1, action: "list_ack" }) }),
|
||||
);
|
||||
expect(sendPluginCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("replies with unicast announce_ack to announce and query, with separate cooldowns", async () => {
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
expect(sendPluginCommand).toHaveBeenLastCalledWith(IDENTITY_PLUGIN, expect.any(String), 7);
|
||||
expect(JSON.parse(sendPluginCommand.mock.calls[0][1] as string).action).toBe("announce_ack");
|
||||
|
||||
// Repeated announce within 10s cooldown is suppressed
|
||||
nowMs += 3_000;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
|
||||
// query uses an independent 5s cooldown bucket, so it succeeds immediately
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Repeated query within 5s is suppressed, then allowed after 5s
|
||||
nowMs += IDENTITY_QUERY_COOLDOWN_MS - 1;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
nowMs += 1;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "query" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
|
||||
// announce still respects its 10s cooldown until elapsed
|
||||
nowMs += 1_000; // total 9_000ms since first announce
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
nowMs += IDENTITY_ANNOUNCE_COOLDOWN_MS;
|
||||
await manager.handlePluginCommand(makeCmd({ data: JSON.stringify({ v: 1, action: "announce" }) }));
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it("replies with localized unicast list_ack on commands list_req using dynamic config", async () => {
|
||||
config = { locale: "en", commandPrefix: "?" };
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 11,
|
||||
invokerUid: "",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
expect(sendPluginCommand).toHaveBeenCalledWith(COMMANDS_PLUGIN, expect.any(String), 11);
|
||||
const payload = JSON.parse(sendPluginCommand.mock.calls[0][1] as string);
|
||||
expect(payload.v).toBe(1);
|
||||
expect(payload.action).toBe("list_ack");
|
||||
expect(payload.command_prefix).toBe("?");
|
||||
expect(payload.commands[0]).toEqual({ name: "play", args: "<query>", desc: "Play song" });
|
||||
|
||||
// Cooldown falls back to invokerId when invokerUid is empty
|
||||
nowMs += COMMANDS_LIST_REQ_COOLDOWN_MS - 10;
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 11,
|
||||
invokerUid: "",
|
||||
}),
|
||||
);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not advertise command discovery with a prefix too long to send unchanged", async () => {
|
||||
config.commandPrefix = "musicbot!!";
|
||||
manager.scheduleAnnounce();
|
||||
await manager.handlePluginCommand(makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
}));
|
||||
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
const identity = JSON.parse(sendPluginCommand.mock.calls[0][1] as string);
|
||||
expect(identity.capabilities).not.toContain("chat:slash_commands");
|
||||
});
|
||||
|
||||
it("ignores inbound payloads beyond the protocol byte limit", async () => {
|
||||
await manager.handlePluginCommand(makeCmd({
|
||||
data: JSON.stringify({ v: 1, action: "query", padding: "中".repeat(MAX_PAYLOAD_BYTES / 2) }),
|
||||
}));
|
||||
expect(sendPluginCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("enforces global and peer cooldowns when sending replies fails", async () => {
|
||||
for (let i = 1; i <= ACK_GLOBAL_BURST; i++) {
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: i,
|
||||
invokerUid: `peer-${i}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST);
|
||||
|
||||
// 5th distinct peer in same millisecond is throttled by global burst
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 99,
|
||||
invokerUid: "peer-99",
|
||||
}),
|
||||
);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST);
|
||||
|
||||
// After 500ms, 1 token refills (2/sec)
|
||||
nowMs += 500;
|
||||
sendPluginCommand.mockRejectedValueOnce(new Error("transient send failure"));
|
||||
await manager.handlePluginCommand(
|
||||
makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 99,
|
||||
invokerUid: "peer-99",
|
||||
}),
|
||||
);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 1);
|
||||
|
||||
// A rejected reply still consumes the global allowance for other peers.
|
||||
const otherRequest = makeCmd({
|
||||
name: COMMANDS_PLUGIN,
|
||||
data: JSON.stringify({ v: 1, action: "list_req" }),
|
||||
invokerId: 98,
|
||||
invokerUid: "peer-98",
|
||||
});
|
||||
await manager.handlePluginCommand(otherRequest);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 1);
|
||||
|
||||
// Once a global slot refills, the original peer is still cooling down.
|
||||
nowMs += 500;
|
||||
await manager.handlePluginCommand({ ...otherRequest, invokerId: 99, invokerUid: "peer-99" });
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 1);
|
||||
await manager.handlePluginCommand(otherRequest);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(ACK_GLOBAL_BURST + 2);
|
||||
});
|
||||
|
||||
it("debounces self-announce over 2s window and emits at most one trailing announce", async () => {
|
||||
manager.scheduleAnnounce();
|
||||
await Promise.resolve();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
expect(sendPluginCommand).toHaveBeenLastCalledWith(IDENTITY_PLUGIN, expect.any(String), "channel");
|
||||
|
||||
// Two calls inside 2s window coalesce into a single trailing broadcast
|
||||
nowMs += 400;
|
||||
manager.scheduleAnnounce();
|
||||
nowMs += 600;
|
||||
manager.scheduleAnnounce();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
|
||||
nowMs += ANNOUNCE_DEBOUNCE_MS - 1_000;
|
||||
await vi.advanceTimersByTimeAsync(ANNOUNCE_DEBOUNCE_MS - 400);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("retries failed announce once after 500ms and cancels pending timers on reset", async () => {
|
||||
sendPluginCommand.mockRejectedValueOnce(new Error("channel broadcast error"));
|
||||
manager.scheduleAnnounce();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(1);
|
||||
|
||||
nowMs += ANNOUNCE_RETRY_DELAY_MS;
|
||||
await vi.advanceTimersByTimeAsync(ANNOUNCE_RETRY_DELAY_MS);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Trigger another failure then reset before retry fires
|
||||
nowMs += ANNOUNCE_DEBOUNCE_MS;
|
||||
sendPluginCommand.mockRejectedValueOnce(new Error("error before disconnect"));
|
||||
manager.scheduleAnnounce();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
|
||||
manager.reset();
|
||||
await vi.advanceTimersByTimeAsync(ANNOUNCE_RETRY_DELAY_MS);
|
||||
expect(sendPluginCommand).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,473 @@
|
||||
import { PlayMode } from "../audio/queue.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { APP_VERSION } from "../version.js";
|
||||
import type { PluginCommandTarget, TS3PluginCommand } from "./client.js";
|
||||
|
||||
export const OPEN_PROTOCOL_VERSION = 1;
|
||||
export const IDENTITY_PLUGIN = "tsclient:identity";
|
||||
export const COMMANDS_PLUGIN = "tsclient:commands";
|
||||
export const MAX_PAYLOAD_BYTES = 1024;
|
||||
|
||||
export const APP_NAME = "TSMusicBot";
|
||||
export const BOT_CAPABILITIES = ["chat:slash_commands"] as const;
|
||||
|
||||
export const ANNOUNCE_DEBOUNCE_MS = 2_000;
|
||||
export const ANNOUNCE_RETRY_DELAY_MS = 500;
|
||||
|
||||
export const IDENTITY_ANNOUNCE_COOLDOWN_MS = 10_000;
|
||||
export const IDENTITY_QUERY_COOLDOWN_MS = 5_000;
|
||||
export const COMMANDS_LIST_REQ_COOLDOWN_MS = 5_000;
|
||||
|
||||
export const ACK_GLOBAL_BURST = 4;
|
||||
export const ACK_GLOBAL_RATE_PER_SEC = 2;
|
||||
|
||||
export const MAX_COMMANDS = 16;
|
||||
export const MAX_CMD_PREFIX_CHARS = 8;
|
||||
export const MAX_CMD_NAME_CHARS = 24;
|
||||
export const MAX_CMD_ARGS_CHARS = 32;
|
||||
export const MAX_CMD_DESC_CHARS = 64;
|
||||
export const MAX_APP_META_CHARS = 32;
|
||||
const MAX_COOLDOWN_ENTRIES_BEFORE_PRUNE = 128;
|
||||
|
||||
export interface OpenProtocolCommandSpec {
|
||||
name: string;
|
||||
args?: string;
|
||||
desc: string;
|
||||
}
|
||||
|
||||
export interface OpenProtocolIdentityPayload {
|
||||
v: 1;
|
||||
action: "announce" | "announce_ack";
|
||||
client_type: "bot";
|
||||
app_name: string;
|
||||
app_version: string;
|
||||
capabilities: string[];
|
||||
}
|
||||
|
||||
export interface OpenProtocolCommandsListAckPayload {
|
||||
v: 1;
|
||||
action: "list_ack";
|
||||
command_prefix: string;
|
||||
commands: OpenProtocolCommandSpec[];
|
||||
}
|
||||
|
||||
export interface OpenProtocolRuntimeConfig {
|
||||
locale: "zh" | "en";
|
||||
commandPrefix: string;
|
||||
}
|
||||
|
||||
export interface OpenProtocolTransport {
|
||||
getClientId(): number;
|
||||
sendPluginCommand(
|
||||
name: string,
|
||||
data: string,
|
||||
target?: PluginCommandTarget | number,
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
interface CommandCatalogEntry {
|
||||
name: string;
|
||||
args?: string;
|
||||
descZh: string;
|
||||
descEn: string;
|
||||
}
|
||||
|
||||
const CORE_COMMAND_CATALOG: readonly CommandCatalogEntry[] = [
|
||||
{ name: "play", args: "<歌曲>", descZh: "点歌并立即播放", descEn: "Play song" },
|
||||
{ name: "add", args: "<歌曲>", descZh: "添加到队列", descEn: "Add to queue" },
|
||||
{ name: "search", args: "<关键词>", descZh: "搜索歌曲", descEn: "Search songs" },
|
||||
{ name: "pause", descZh: "暂停播放", descEn: "Pause playback" },
|
||||
{ name: "resume", descZh: "恢复播放", descEn: "Resume playback" },
|
||||
{ name: "next", descZh: "下一首", descEn: "Next track" },
|
||||
{ name: "prev", descZh: "上一首", descEn: "Previous track" },
|
||||
{ name: "stop", descZh: "停止并清空队列", descEn: "Stop & clear" },
|
||||
{ name: "now", descZh: "当前播放", descEn: "Current track" },
|
||||
{ name: "queue", descZh: "查看队列", descEn: "Show queue" },
|
||||
{ name: "vol", args: "<0-100>", descZh: "调节音量", descEn: "Set volume" },
|
||||
{ name: "mode", args: `<${Object.values(PlayMode).join("|")}>`, descZh: "切换播放模式", descEn: "Set play mode" },
|
||||
{ name: "clear", descZh: "清空队列", descEn: "Clear queue" },
|
||||
{ name: "remove", args: "<序号>", descZh: "移除指定曲目", descEn: "Remove track" },
|
||||
{ name: "playlist", args: "<歌单>", descZh: "导入歌单", descEn: "Load playlist" },
|
||||
{ name: "help", descZh: "命令帮助", descEn: "Command help" },
|
||||
];
|
||||
|
||||
const CORE_COMMAND_ARGS_EN: Readonly<Record<string, string>> = {
|
||||
play: "<query>",
|
||||
add: "<query>",
|
||||
search: "<keyword>",
|
||||
vol: "<0-100>",
|
||||
remove: "<index>",
|
||||
playlist: "<id|url>",
|
||||
};
|
||||
|
||||
function truncateChars(value: string, maxChars: number): string {
|
||||
const sanitized = value.replace(/[\u0000-\u001F\u007F]/g, "");
|
||||
const chars = Array.from(sanitized);
|
||||
if (chars.length <= maxChars) return sanitized;
|
||||
return chars.slice(0, maxChars).join("");
|
||||
}
|
||||
|
||||
function isDiscoverablePrefix(prefix: string): boolean {
|
||||
return typeof prefix === "string"
|
||||
&& prefix.length > 0
|
||||
&& prefix.trim() === prefix
|
||||
&& truncateChars(prefix, MAX_CMD_PREFIX_CHARS) === prefix;
|
||||
}
|
||||
|
||||
export function buildIdentityPayloadJson(
|
||||
action: "announce" | "announce_ack",
|
||||
appVersion: string = APP_VERSION,
|
||||
commandPrefix = "!",
|
||||
): string {
|
||||
const payload: OpenProtocolIdentityPayload = {
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action,
|
||||
client_type: "bot",
|
||||
app_name: truncateChars(APP_NAME, MAX_APP_META_CHARS),
|
||||
app_version: truncateChars(appVersion, MAX_APP_META_CHARS),
|
||||
capabilities: isDiscoverablePrefix(commandPrefix) ? [...BOT_CAPABILITIES] : [],
|
||||
};
|
||||
|
||||
return JSON.stringify(payload);
|
||||
}
|
||||
|
||||
export function buildOpenProtocolCommands(locale: "zh" | "en"): OpenProtocolCommandSpec[] {
|
||||
return CORE_COMMAND_CATALOG.slice(0, MAX_COMMANDS).map((entry) => {
|
||||
const rawArgs = locale === "zh" ? entry.args : (CORE_COMMAND_ARGS_EN[entry.name] ?? entry.args);
|
||||
const rawDesc = locale === "zh" ? entry.descZh : entry.descEn;
|
||||
const spec: OpenProtocolCommandSpec = {
|
||||
name: truncateChars(entry.name, MAX_CMD_NAME_CHARS),
|
||||
desc: truncateChars(rawDesc, MAX_CMD_DESC_CHARS),
|
||||
};
|
||||
if (rawArgs) {
|
||||
spec.args = truncateChars(rawArgs, MAX_CMD_ARGS_CHARS);
|
||||
}
|
||||
return spec;
|
||||
});
|
||||
}
|
||||
|
||||
export function buildCommandsListAckJson(
|
||||
locale: "zh" | "en",
|
||||
commandPrefix: string,
|
||||
): string | null {
|
||||
if (!isDiscoverablePrefix(commandPrefix)) return null;
|
||||
|
||||
const commands = buildOpenProtocolCommands(locale);
|
||||
while (commands.length > 0) {
|
||||
const payload: OpenProtocolCommandsListAckPayload = {
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action: "list_ack",
|
||||
command_prefix: commandPrefix,
|
||||
commands,
|
||||
};
|
||||
const json = JSON.stringify(payload);
|
||||
if (Buffer.byteLength(json, "utf8") < MAX_PAYLOAD_BYTES) {
|
||||
return json;
|
||||
}
|
||||
commands.pop();
|
||||
}
|
||||
|
||||
return JSON.stringify({
|
||||
v: OPEN_PROTOCOL_VERSION,
|
||||
action: "list_ack",
|
||||
command_prefix: commandPrefix,
|
||||
commands: [],
|
||||
} satisfies OpenProtocolCommandsListAckPayload);
|
||||
}
|
||||
|
||||
class AckRateLimiter {
|
||||
private readonly lastSent = new Map<string, number>();
|
||||
private tokens = ACK_GLOBAL_BURST;
|
||||
private lastRefillMs: number | null = null;
|
||||
|
||||
private refill(nowMs: number): void {
|
||||
if (this.lastRefillMs === null) {
|
||||
this.lastRefillMs = nowMs;
|
||||
return;
|
||||
}
|
||||
const elapsedMs = Math.max(0, nowMs - this.lastRefillMs);
|
||||
this.tokens = Math.min(
|
||||
ACK_GLOBAL_BURST,
|
||||
this.tokens + (elapsedMs / 1000) * ACK_GLOBAL_RATE_PER_SEC,
|
||||
);
|
||||
this.lastRefillMs = nowMs;
|
||||
}
|
||||
|
||||
private prune(nowMs: number): void {
|
||||
if (this.lastSent.size <= MAX_COOLDOWN_ENTRIES_BEFORE_PRUNE) return;
|
||||
const maxAgeMs = Math.max(
|
||||
IDENTITY_ANNOUNCE_COOLDOWN_MS,
|
||||
IDENTITY_QUERY_COOLDOWN_MS,
|
||||
COMMANDS_LIST_REQ_COOLDOWN_MS,
|
||||
);
|
||||
for (const [key, ts] of this.lastSent) {
|
||||
if (nowMs - ts >= maxAgeMs) {
|
||||
this.lastSent.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tryAcquire(peerKey: string, actionKey: string, cooldownMs: number, nowMs: number): boolean {
|
||||
this.prune(nowMs);
|
||||
const key = `${peerKey}:${actionKey}`;
|
||||
const prev = this.lastSent.get(key);
|
||||
if (prev !== undefined && nowMs - prev < cooldownMs) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.refill(nowMs);
|
||||
if (this.tokens < 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.tokens -= 1;
|
||||
this.lastSent.set(key, nowMs);
|
||||
return true;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.lastSent.clear();
|
||||
this.tokens = ACK_GLOBAL_BURST;
|
||||
this.lastRefillMs = null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface OpenProtocolManagerOptions {
|
||||
transport: OpenProtocolTransport;
|
||||
getConfig: () => OpenProtocolRuntimeConfig;
|
||||
logger: Logger;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export class OpenProtocolManager {
|
||||
private readonly transport: OpenProtocolTransport;
|
||||
private readonly getConfig: () => OpenProtocolRuntimeConfig;
|
||||
private readonly logger: Logger;
|
||||
private readonly now: () => number;
|
||||
private readonly rateLimiter = new AckRateLimiter();
|
||||
|
||||
private generation = 0;
|
||||
private announceSeq = 0;
|
||||
private lastSuccessSeq = 0;
|
||||
private lastAnnounceAttemptMs: number | null = null;
|
||||
private trailingAnnounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private retryAnnounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor(options: OpenProtocolManagerOptions) {
|
||||
this.transport = options.transport;
|
||||
this.getConfig = options.getConfig;
|
||||
this.logger = options.logger;
|
||||
this.now = options.now ?? (() => Date.now());
|
||||
}
|
||||
|
||||
/** Reset timers and rate-limit state on disconnect or teardown. */
|
||||
reset(): void {
|
||||
this.generation += 1;
|
||||
this.announceSeq = 0;
|
||||
this.lastSuccessSeq = 0;
|
||||
this.lastAnnounceAttemptMs = null;
|
||||
this.clearTimers();
|
||||
this.rateLimiter.clear();
|
||||
}
|
||||
|
||||
/** Schedule or send a debounced channel broadcast announcing this bot's identity. */
|
||||
scheduleAnnounce(): void {
|
||||
const clientId = this.transport.getClientId();
|
||||
if (clientId <= 0) return;
|
||||
|
||||
const nowMs = this.now();
|
||||
if (
|
||||
this.lastAnnounceAttemptMs !== null &&
|
||||
nowMs - this.lastAnnounceAttemptMs < ANNOUNCE_DEBOUNCE_MS
|
||||
) {
|
||||
if (!this.trailingAnnounceTimer) {
|
||||
const delayMs = Math.max(
|
||||
0,
|
||||
ANNOUNCE_DEBOUNCE_MS - (nowMs - this.lastAnnounceAttemptMs),
|
||||
);
|
||||
const gen = this.generation;
|
||||
this.trailingAnnounceTimer = setTimeout(() => {
|
||||
this.trailingAnnounceTimer = null;
|
||||
if (gen !== this.generation) return;
|
||||
this.dispatchAnnounce(gen);
|
||||
}, delayMs);
|
||||
this.trailingAnnounceTimer.unref?.();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.clearTimers();
|
||||
this.dispatchAnnounce(this.generation);
|
||||
}
|
||||
|
||||
/** Handle an incoming TeamSpeak plugin command. */
|
||||
async handlePluginCommand(cmd: TS3PluginCommand): Promise<void> {
|
||||
if (cmd.name !== IDENTITY_PLUGIN && cmd.name !== COMMANDS_PLUGIN) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selfClientId = this.transport.getClientId();
|
||||
if (selfClientId <= 0 || cmd.invokerId === selfClientId || cmd.invokerId <= 0
|
||||
|| Buffer.byteLength(cmd.data, "utf8") >= MAX_PAYLOAD_BYTES) {
|
||||
return;
|
||||
}
|
||||
|
||||
let parsed: Record<string, unknown>;
|
||||
try {
|
||||
const value = JSON.parse(cmd.data) as unknown;
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
parsed = value as Record<string, unknown>;
|
||||
} catch {
|
||||
this.logger.debug(
|
||||
{ name: cmd.name, invokerId: cmd.invokerId },
|
||||
"Ignoring malformed OpenProtocol JSON payload",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (parsed.v !== OPEN_PROTOCOL_VERSION || typeof parsed.action !== "string") {
|
||||
return;
|
||||
}
|
||||
|
||||
const peerKey = cmd.invokerUid.trim() || String(cmd.invokerId);
|
||||
|
||||
if (cmd.name === IDENTITY_PLUGIN) {
|
||||
await this.handleIdentityAction(parsed.action, peerKey, cmd.invokerId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (cmd.name === COMMANDS_PLUGIN) {
|
||||
await this.handleCommandsAction(parsed.action, peerKey, cmd.invokerId);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleIdentityAction(
|
||||
action: string,
|
||||
peerKey: string,
|
||||
invokerId: number,
|
||||
): Promise<void> {
|
||||
let cooldownMs: number;
|
||||
if (action === "announce") {
|
||||
cooldownMs = IDENTITY_ANNOUNCE_COOLDOWN_MS;
|
||||
} else if (action === "query") {
|
||||
cooldownMs = IDENTITY_QUERY_COOLDOWN_MS;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.rateLimiter.tryAcquire(
|
||||
peerKey, `${IDENTITY_PLUGIN}:${action}`, cooldownMs, this.now(),
|
||||
)) return;
|
||||
|
||||
const payload = buildIdentityPayloadJson("announce_ack", APP_VERSION, this.getConfig().commandPrefix);
|
||||
await this.sendAck(IDENTITY_PLUGIN, payload, invokerId);
|
||||
}
|
||||
|
||||
private async handleCommandsAction(
|
||||
action: string,
|
||||
peerKey: string,
|
||||
invokerId: number,
|
||||
): Promise<void> {
|
||||
if (action !== "list_req") return;
|
||||
|
||||
const { locale, commandPrefix } = this.getConfig();
|
||||
if (!isDiscoverablePrefix(commandPrefix) || !this.rateLimiter.tryAcquire(
|
||||
peerKey, `${COMMANDS_PLUGIN}:list_req`, COMMANDS_LIST_REQ_COOLDOWN_MS, this.now(),
|
||||
)) return;
|
||||
|
||||
const payload = buildCommandsListAckJson(locale, commandPrefix);
|
||||
if (payload !== null) await this.sendAck(COMMANDS_PLUGIN, payload, invokerId);
|
||||
}
|
||||
|
||||
private async sendAck(
|
||||
pluginName: string,
|
||||
payload: string,
|
||||
invokerId: number,
|
||||
): Promise<void> {
|
||||
if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) {
|
||||
this.logger.debug({ pluginName }, "OpenProtocol payload exceeded size limit");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.transport.sendPluginCommand(pluginName, payload, invokerId);
|
||||
} catch (err) {
|
||||
this.logger.debug(
|
||||
{ err, pluginName, invokerId },
|
||||
"Failed to send OpenProtocol response",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private dispatchAnnounce(expectedGen: number): void {
|
||||
if (expectedGen !== this.generation || this.transport.getClientId() <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastAnnounceAttemptMs = this.now();
|
||||
const seq = ++this.announceSeq;
|
||||
const payload = buildIdentityPayloadJson("announce", APP_VERSION, this.getConfig().commandPrefix);
|
||||
|
||||
if (Buffer.byteLength(payload, "utf8") >= MAX_PAYLOAD_BYTES) {
|
||||
this.logger.debug("OpenProtocol announce payload exceeded size limit");
|
||||
return;
|
||||
}
|
||||
|
||||
this.transport
|
||||
.sendPluginCommand(IDENTITY_PLUGIN, payload, "channel")
|
||||
.then(() => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.lastSuccessSeq = Math.max(this.lastSuccessSeq, seq);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.logger.debug({ err }, "OpenProtocol announce broadcast failed");
|
||||
this.scheduleAnnounceRetry(expectedGen, seq);
|
||||
});
|
||||
}
|
||||
|
||||
private scheduleAnnounceRetry(expectedGen: number, failedSeq: number): void {
|
||||
if (this.retryAnnounceTimer) {
|
||||
clearTimeout(this.retryAnnounceTimer);
|
||||
this.retryAnnounceTimer = null;
|
||||
}
|
||||
|
||||
this.retryAnnounceTimer = setTimeout(() => {
|
||||
this.retryAnnounceTimer = null;
|
||||
if (
|
||||
expectedGen !== this.generation ||
|
||||
this.lastSuccessSeq >= failedSeq ||
|
||||
this.transport.getClientId() <= 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const retrySeq = ++this.announceSeq;
|
||||
const payload = buildIdentityPayloadJson("announce", APP_VERSION, this.getConfig().commandPrefix);
|
||||
this.lastAnnounceAttemptMs = this.now();
|
||||
this.transport
|
||||
.sendPluginCommand(IDENTITY_PLUGIN, payload, "channel")
|
||||
.then(() => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.lastSuccessSeq = Math.max(this.lastSuccessSeq, retrySeq);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (expectedGen !== this.generation) return;
|
||||
this.logger.debug({ err }, "OpenProtocol announce retry failed");
|
||||
});
|
||||
}, ANNOUNCE_RETRY_DELAY_MS);
|
||||
this.retryAnnounceTimer.unref?.();
|
||||
}
|
||||
|
||||
private clearTimers(): void {
|
||||
if (this.trailingAnnounceTimer) {
|
||||
clearTimeout(this.trailingAnnounceTimer);
|
||||
this.trailingAnnounceTimer = null;
|
||||
}
|
||||
if (this.retryAnnounceTimer) {
|
||||
clearTimeout(this.retryAnnounceTimer);
|
||||
this.retryAnnounceTimer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,21 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { toTS3TextMessage } from "./client.js";
|
||||
import type { TextMessage } from "@honeybbq/teamspeak-client";
|
||||
import {
|
||||
asClientID,
|
||||
asServerGroupID,
|
||||
asUID,
|
||||
type TextMessageEvent,
|
||||
} from "@honeybbq/teamspeak";
|
||||
|
||||
function makeMsg(over: Partial<TextMessage> = {}): TextMessage {
|
||||
function makeMsg(over: Partial<TextMessageEvent> = {}): TextMessageEvent {
|
||||
return {
|
||||
invokerName: "Alice",
|
||||
invokerUID: "uid-abc",
|
||||
invokerUID: asUID("uid-abc"),
|
||||
message: "!stop",
|
||||
invokerGroups: ["6", "8"],
|
||||
invokerGroups: [asServerGroupID(6n), asServerGroupID(8n)],
|
||||
targetMode: 2,
|
||||
targetID: 0n,
|
||||
invokerID: 5,
|
||||
targetID: asClientID(0),
|
||||
invokerID: asClientID(5),
|
||||
...over,
|
||||
};
|
||||
}
|
||||
@@ -26,18 +31,20 @@ describe("toTS3TextMessage", () => {
|
||||
});
|
||||
|
||||
it("preserves the sender's server groups", () => {
|
||||
expect(toTS3TextMessage(makeMsg({ invokerGroups: ["6"] })).invokerGroups).toEqual(["6"]);
|
||||
expect(
|
||||
toTS3TextMessage(makeMsg({ invokerGroups: [asServerGroupID(6n)] })).invokerGroups,
|
||||
).toEqual(["6"]);
|
||||
});
|
||||
|
||||
it("defaults missing invokerGroups to an empty array", () => {
|
||||
const partial = {
|
||||
invokerName: "Bob",
|
||||
invokerUID: "u",
|
||||
invokerUID: asUID("u"),
|
||||
message: "!stop",
|
||||
targetMode: 1,
|
||||
targetID: 0n,
|
||||
invokerID: 7,
|
||||
} as unknown as TextMessage;
|
||||
targetID: asClientID(0),
|
||||
invokerID: asClientID(7),
|
||||
} as unknown as TextMessageEvent;
|
||||
expect(toTS3TextMessage(partial).invokerGroups).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { AddrResolver, ResolvedAddr } from "@honeybbq/teamspeak-client";
|
||||
import type { AddrResolver, ResolvedAddr } from "@honeybbq/teamspeak/client";
|
||||
import { TrackingVoiceEndpointResolver } from "./voice-endpoint.js";
|
||||
|
||||
function result(addr: string): ResolvedAddr {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import { Resolver } from "@honeybbq/teamspeak-client/discovery";
|
||||
import { Resolver } from "@honeybbq/teamspeak/client";
|
||||
import type {
|
||||
AddrResolver,
|
||||
ResolvedAddr,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
} from "@honeybbq/teamspeak/client";
|
||||
|
||||
export interface ResolvedVoiceEndpoint {
|
||||
host: string;
|
||||
@@ -66,9 +66,12 @@ export class TrackingVoiceEndpointResolver implements AddrResolver {
|
||||
private readonly resolveHost: ResolveIpv4 = resolveIpv4,
|
||||
) {}
|
||||
|
||||
async resolve(input: string, signal?: AbortSignal): Promise<ResolvedAddr[]> {
|
||||
async resolve(
|
||||
input: string,
|
||||
options?: { readonly signal?: AbortSignal },
|
||||
): Promise<readonly ResolvedAddr[]> {
|
||||
this.endpoint = null;
|
||||
const candidates = await this.delegate.resolve(input, signal);
|
||||
const candidates = await this.delegate.resolve(input, options);
|
||||
const selected = candidates[0];
|
||||
if (!selected) return candidates;
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
function loadAppVersion(): string {
|
||||
try {
|
||||
const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version?: unknown };
|
||||
if (typeof manifest.version === "string" && manifest.version.trim()) {
|
||||
return manifest.version.trim();
|
||||
}
|
||||
} catch {
|
||||
// A custom bundle may omit the package manifest.
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export const APP_VERSION = loadAppVersion();
|
||||
@@ -3,6 +3,7 @@ import express from "express";
|
||||
import request from "supertest";
|
||||
import pino from "pino";
|
||||
import type { MusicProvider } from "../../music/provider.js";
|
||||
import type { QQMusicProvider } from "../../music/qq.js";
|
||||
import { getDefaultConfig, type JellyfinConfig } from "../../data/config.js";
|
||||
import { createAuthRouter } from "./auth.js";
|
||||
|
||||
@@ -72,3 +73,79 @@ describe("auth router POST /jellyfin/test", () => {
|
||||
expect(testConnection).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed QQ authentication routes", () => {
|
||||
function mount(managed: boolean, user: unknown = { role: "admin" }) {
|
||||
const renewal = {
|
||||
renewalStatus: "scheduled" as const,
|
||||
nextRefreshAt: "2026-11-10T00:00:00.000Z",
|
||||
lastRefreshAt: "2026-11-09T00:00:00.000Z",
|
||||
};
|
||||
const refresh = vi.fn().mockResolvedValue("refreshed");
|
||||
const qq = {
|
||||
platform: "qq",
|
||||
managedSession: managed ? { refresh, getStatus: () => renewal } : undefined,
|
||||
checkQrCodeStatus: vi.fn().mockResolvedValue("confirmed"),
|
||||
setCookie: vi.fn(),
|
||||
getCookie: () => "private-test-cookie",
|
||||
getAuthStatus: vi.fn().mockResolvedValue({ loggedIn: true }),
|
||||
} as unknown as QQMusicProvider;
|
||||
const legacyStore = { load: vi.fn(), save: vi.fn() };
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { (req as { user?: unknown }).user = user; next(); });
|
||||
app.use("/api/auth", createAuthRouter(
|
||||
fakeProvider("netease"), qq, fakeProvider("bilibili"), pino({ level: "silent" }), legacyStore,
|
||||
));
|
||||
return { app, qq, refresh, legacyStore };
|
||||
}
|
||||
|
||||
it("returns status only and delegates persistence to the managed session", async () => {
|
||||
const { app, qq, refresh, legacyStore } = mount(true);
|
||||
await request(app).get("/api/auth/qrcode/status").query({ platform: "qq", key: "opaque" }).expect(200);
|
||||
await request(app).post("/api/auth/cookie").send({ platform: "qq", cookie: "uin=1" }).expect(200);
|
||||
expect(qq.setCookie).toHaveBeenCalledWith("uin=1");
|
||||
expect(legacyStore.save).not.toHaveBeenCalled();
|
||||
const status = await request(app).get("/api/auth/status").query({ platform: "qq" }).expect(200);
|
||||
expect(status.body.lastRefreshAt).toBe("2026-11-09T00:00:00.000Z");
|
||||
const res = await request(app).post("/api/auth/qq/refresh").expect(200);
|
||||
expect(res.body).toEqual({
|
||||
outcome: "refreshed", renewalStatus: "scheduled", nextRefreshAt: "2026-11-10T00:00:00.000Z",
|
||||
lastRefreshAt: "2026-11-09T00:00:00.000Z",
|
||||
});
|
||||
expect(refresh).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("guards managed QQ polling and refresh with platform.auth", async () => {
|
||||
const { app, qq, refresh } = mount(true, { role: "member", capabilities: new Set() });
|
||||
await request(app).get("/api/auth/qrcode/status").query({ platform: "qq", key: "opaque" }).expect(403);
|
||||
await request(app).post("/api/auth/qq/refresh").expect(403);
|
||||
expect(qq.checkQrCodeStatus).not.toHaveBeenCalled();
|
||||
expect(refresh).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the current QQ login when an import contains only response attributes", async () => {
|
||||
const { app, qq } = mount(true);
|
||||
await request(app).post("/api/auth/cookie")
|
||||
.send({ platform: "qq", cookie: "Path=/; HttpOnly" })
|
||||
.expect(400);
|
||||
expect(qq.setCookie).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("continues persisting the legacy cookie when the feature is disabled", async () => {
|
||||
const { app, legacyStore } = mount(false);
|
||||
await request(app).get("/api/auth/qrcode/status").query({ platform: "qq", key: "legacy" }).expect(200);
|
||||
expect(legacyStore.save).toHaveBeenCalledWith("qq", "private-test-cookie");
|
||||
await request(app).post("/api/auth/qq/refresh").expect(404);
|
||||
});
|
||||
|
||||
it("keeps the current QQ cookie when an unmanaged import cannot be saved", async () => {
|
||||
const { app, qq, legacyStore } = mount(false);
|
||||
legacyStore.save.mockImplementationOnce(() => { throw new Error("test write failed"); });
|
||||
await request(app).post("/api/auth/cookie").send({ platform: "qq", cookie: "uin=999" }).expect(503);
|
||||
expect(qq.setCookie).not.toHaveBeenCalled();
|
||||
await request(app).post("/api/auth/cookie").send({ platform: "qq", cookie: "uin=999" }).expect(200);
|
||||
expect(legacyStore.save).toHaveBeenLastCalledWith("qq", "uin=999");
|
||||
expect(qq.setCookie).toHaveBeenCalledWith("uin=999");
|
||||
});
|
||||
});
|
||||
+95
-12
@@ -1,24 +1,34 @@
|
||||
import { Router } from "express";
|
||||
import type { ParamsDictionary } from "express-serve-static-core";
|
||||
import type { MusicProvider } from "../../music/provider.js";
|
||||
import type { QQMusicProvider } from "../../music/qq.js";
|
||||
import { normalizeCookie } from "../../music/cookie-normalize.js";
|
||||
import { musicRequestError } from "../../music/request-error.js";
|
||||
import { YouTubeProvider } from "../../music/youtube.js";
|
||||
import type { CookieStore } from "../../music/auth.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import type { BotConfig, JellyfinConfig } from "../../data/config.js";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
import { requirePermission } from "../middleware/requirePermission.js";
|
||||
import { requireNotGuest } from "../middleware/requireNotGuest.js";
|
||||
import { resolveMusicCookie } from "./provider-scope.js";
|
||||
|
||||
export function createAuthRouter(
|
||||
neteaseProvider: MusicProvider,
|
||||
qqProvider: MusicProvider,
|
||||
qqProvider: MusicProvider & Partial<Pick<QQMusicProvider, "managedSession">>,
|
||||
bilibiliProvider: MusicProvider,
|
||||
logger: Logger,
|
||||
cookieStore?: CookieStore,
|
||||
kugouProvider?: MusicProvider,
|
||||
spotifyProvider?: MusicProvider,
|
||||
jellyfinProvider?: MusicProvider,
|
||||
config?: BotConfig
|
||||
config?: BotConfig,
|
||||
// Per-user music accounts (#164 follow-up). Omitted by unit-test routers →
|
||||
// every caller keeps seeing the bot's shared login status.
|
||||
database?: BotDatabase,
|
||||
): Router {
|
||||
const router = Router();
|
||||
const qqSession = qqProvider.managedSession;
|
||||
// YouTube is auth-less; we only use this instance so /auth/status can
|
||||
// report whether yt-dlp is actually installed (loggedIn=false otherwise).
|
||||
const youtubeProvider: MusicProvider = new YouTubeProvider();
|
||||
@@ -36,12 +46,56 @@ export function createAuthRouter(
|
||||
try {
|
||||
const platform = req.query.platform as string;
|
||||
const provider = getProvider(platform);
|
||||
// Per-user accounts (#164 follow-up). Two different questions, two
|
||||
// different answers:
|
||||
//
|
||||
// /api/auth/status → "is the BOT's shared login alive?" This is the
|
||||
// admin console (Settings → 音乐平台), so an
|
||||
// admin always gets the shared status even if
|
||||
// they linked or were assigned a personal one.
|
||||
// /api/me/music/status → "which account does THIS user actually play
|
||||
// through?" (personal-music.ts) — that one does
|
||||
// report the personal/granted view.
|
||||
//
|
||||
// For a non-admin the shared nickname/avatar must never be returned: that
|
||||
// is exactly the leak this feature exists to close, so they get
|
||||
// loggedIn:false instead until they have an account of their own.
|
||||
const user = (req as { user?: { id?: string; role?: string } }).user;
|
||||
// A platform without per-account login support (spotify / jellyfin /
|
||||
// youtube) keeps reporting the shared status for everyone: the toggle only
|
||||
// governs sources that can actually build a per-user view.
|
||||
const perUser =
|
||||
config?.perUserMusicAccounts === true &&
|
||||
user?.role !== "admin" &&
|
||||
typeof provider.withCookie === "function";
|
||||
|
||||
if (perUser) {
|
||||
const own = resolveMusicCookie(req, provider.platform, { database, config });
|
||||
if (own && typeof provider.withCookie === "function") {
|
||||
const view = provider.withCookie(own.cookie);
|
||||
const status = await view.getAuthStatus();
|
||||
res.json({
|
||||
platform: provider.platform,
|
||||
personal: true,
|
||||
source: own.source,
|
||||
// Admin-facing name for an assigned account; absent for self-linked.
|
||||
label: own.label,
|
||||
...status,
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.json({ platform: provider.platform, loggedIn: false, personal: true, source: "none" });
|
||||
return;
|
||||
}
|
||||
|
||||
const status = await provider.getAuthStatus();
|
||||
logger.debug({ platform, status }, "Auth status check");
|
||||
res.json({ platform: provider.platform, ...status });
|
||||
logger.debug({ platform, loggedIn: status.loggedIn }, "Auth status check");
|
||||
const renewal = platform === "qq" ? qqSession?.getStatus() : undefined;
|
||||
res.json({ platform: provider.platform, source: "shared", ...status, ...renewal });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Auth status check failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Auth status check failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -50,7 +104,7 @@ export function createAuthRouter(
|
||||
const { platform } = req.body;
|
||||
const provider = getProvider(platform);
|
||||
const qr = await provider.getQrCode();
|
||||
logger.info({ platform, key: qr.key }, "QR code generated");
|
||||
logger.info({ platform }, "QR code generated");
|
||||
res.json(qr);
|
||||
} catch (err) {
|
||||
logger.error({ err }, "QR code generation failed");
|
||||
@@ -58,7 +112,11 @@ export function createAuthRouter(
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/qrcode/status", requireNotGuest, async (req, res) => {
|
||||
const requirePlatformAuth = requirePermission<ParamsDictionary>("platform.auth");
|
||||
router.get("/qrcode/status", requireNotGuest, (req, res, next) => {
|
||||
if (qqSession && req.query.platform === "qq") requirePlatformAuth(req, res, next);
|
||||
else next();
|
||||
}, async (req, res) => {
|
||||
try {
|
||||
const { key, platform } = req.query;
|
||||
if (!key) {
|
||||
@@ -67,10 +125,10 @@ export function createAuthRouter(
|
||||
}
|
||||
const provider = getProvider(platform as string);
|
||||
const status = await provider.checkQrCodeStatus(key as string);
|
||||
logger.info({ platform, status, key }, "QR status check");
|
||||
logger.info({ platform, status }, "QR status check");
|
||||
|
||||
// When confirmed, persist cookie
|
||||
if (status === "confirmed") {
|
||||
if (status === "confirmed" && !(platform === "qq" && qqSession)) {
|
||||
const cookie = provider.getCookie();
|
||||
const plat = (platform as string) === "bilibili" ? "bilibili" as const
|
||||
: (platform as string) === "kugou" ? "kugou" as const
|
||||
@@ -88,6 +146,19 @@ export function createAuthRouter(
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/qq/refresh", requirePlatformAuth, async (_req, res) => {
|
||||
if (!qqSession) {
|
||||
res.status(404).json({ outcome: "disabled" });
|
||||
return;
|
||||
}
|
||||
const outcome = await qqSession.refresh();
|
||||
const status = outcome === "refreshed" ? 200
|
||||
: outcome === "cooldown" || outcome === "rate_limited" ? 429
|
||||
: outcome === "reauth_required" || outcome === "superseded" ? 409
|
||||
: outcome === "persist_failed" ? 503 : 502;
|
||||
res.status(status).json({ outcome, ...qqSession.getStatus() });
|
||||
});
|
||||
|
||||
// Jellyfin has no QR/cookie flow — the connection is admin-configured. This
|
||||
// round-trips /System/Info so Settings can verify form values BEFORE saving.
|
||||
// Empty/missing credential fields fall back to the stored config, so a
|
||||
@@ -169,7 +240,8 @@ export function createAuthRouter(
|
||||
});
|
||||
|
||||
router.post("/cookie", requirePermission("platform.auth"), (req, res) => {
|
||||
const { platform, cookie } = req.body;
|
||||
const { platform, cookie: raw } = req.body;
|
||||
const cookie = typeof raw === "string" ? normalizeCookie(raw) : "";
|
||||
if (!cookie) {
|
||||
res.status(400).json({ error: "cookie is required" });
|
||||
return;
|
||||
@@ -191,10 +263,21 @@ export function createAuthRouter(
|
||||
return;
|
||||
}
|
||||
const provider = getProvider(platform);
|
||||
if (platform === "qq") {
|
||||
try {
|
||||
if (!qqSession) cookieStore?.save("qq", cookie);
|
||||
provider.setCookie(cookie);
|
||||
res.json({ success: true });
|
||||
} catch {
|
||||
logger.warn("Could not save imported QQ cookie");
|
||||
res.status(503).json({ error: "Could not save QQ cookie" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
provider.setCookie(cookie);
|
||||
const plat = platform === "bilibili" ? "bilibili" as const
|
||||
: platform === "kugou" ? "kugou" as const
|
||||
: platform === "qq" ? "qq" as const : "netease" as const;
|
||||
: "netease" as const;
|
||||
if (cookieStore) {
|
||||
cookieStore.save(plat, cookie);
|
||||
}
|
||||
|
||||
+10
-2
@@ -677,12 +677,12 @@ describe("bot router /settings jellyfin block + enabledProviders", () => {
|
||||
rmSync(tmpDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function mountBot(): express.Express {
|
||||
function mountBot(user: unknown = { role: "admin" }): express.Express {
|
||||
const fakeManager = { getAllBots: () => [] } as unknown as BotManager;
|
||||
const avatarStore = createAvatarStore(tmpDir);
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => { (req as { user?: unknown }).user = { role: "admin" }; next(); });
|
||||
app.use((req, _res, next) => { (req as { user?: unknown }).user = user; next(); });
|
||||
app.use(
|
||||
"/api/bot",
|
||||
createBotRouter(
|
||||
@@ -694,6 +694,14 @@ describe("bot router /settings jellyfin block + enabledProviders", () => {
|
||||
return app;
|
||||
}
|
||||
|
||||
it("reserves the music-account policy toggle for administrators", async () => {
|
||||
const member = mountBot({ role: "member", capabilities: new Set(["bot.manage"]) });
|
||||
await request(member).post("/api/bot/settings").send({ perUserMusicAccounts: true }).expect(403);
|
||||
expect(config.perUserMusicAccounts).toBe(false);
|
||||
await request(mountBot()).post("/api/bot/settings").send({ perUserMusicAccounts: true }).expect(200);
|
||||
expect(config.perUserMusicAccounts).toBe(true);
|
||||
});
|
||||
|
||||
it("GET /settings exposes a masked jellyfin block (no password/apiKey echo)", async () => {
|
||||
config.jellyfin.serverUrl = "https://jf.example.com";
|
||||
config.jellyfin.password = "secret";
|
||||
|
||||
@@ -74,7 +74,10 @@ export function createBotRouter(
|
||||
voiceDucking: config.voiceDucking,
|
||||
localAudioEnabled: config.localAudioEnabled,
|
||||
savedQueuesEnabled: config.savedQueuesEnabled,
|
||||
perUserMusicAccounts: config.perUserMusicAccounts === true,
|
||||
playKeepsQueue: config.playKeepsQueue,
|
||||
// Silent re-resolve budget for a track whose URL came back empty.
|
||||
playUrlRetries: config.playUrlRetries ?? 0,
|
||||
adminGroups: config.adminGroups ?? [],
|
||||
guestMode: config.guestMode,
|
||||
spotify: maskedSpotify(),
|
||||
@@ -94,6 +97,8 @@ export function createBotRouter(
|
||||
voiceDucking,
|
||||
guestMode,
|
||||
adminGroups,
|
||||
playUrlRetries,
|
||||
perUserMusicAccounts,
|
||||
} = req.body;
|
||||
|
||||
const hasIdle = idleTimeoutMinutes !== undefined;
|
||||
@@ -104,10 +109,31 @@ export function createBotRouter(
|
||||
|
||||
const hasAutoPause = typeof autoPauseOnEmpty === "boolean";
|
||||
const hasLocalAudioEnabled = typeof localAudioEnabled === "boolean";
|
||||
// Retry budget is an integer 0..5; out-of-range is a client bug, not
|
||||
// something to silently clamp, so it 400s like the other numeric fields.
|
||||
const hasPlayUrlRetries = playUrlRetries !== undefined;
|
||||
if (
|
||||
hasPlayUrlRetries &&
|
||||
(typeof playUrlRetries !== "number" ||
|
||||
!Number.isInteger(playUrlRetries) ||
|
||||
playUrlRetries < 0 ||
|
||||
playUrlRetries > 5)
|
||||
) {
|
||||
res.status(400).json({ error: "playUrlRetries must be an integer 0-5" });
|
||||
return;
|
||||
}
|
||||
|
||||
const hasPerUserMusicAccounts = typeof perUserMusicAccounts === "boolean";
|
||||
if (hasPerUserMusicAccounts && req.user?.role !== "admin") {
|
||||
res.status(403).json({ error: "forbidden" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasIdle) config.idleTimeoutMinutes = idleTimeoutMinutes;
|
||||
if (hasAutoPause) config.autoPauseOnEmpty = autoPauseOnEmpty;
|
||||
if (hasLocalAudioEnabled) config.localAudioEnabled = localAudioEnabled;
|
||||
if (hasPlayUrlRetries) config.playUrlRetries = playUrlRetries;
|
||||
if (hasPerUserMusicAccounts) config.perUserMusicAccounts = perUserMusicAccounts;
|
||||
|
||||
// Voice ducking is a partial settings block. Merge only known, strictly
|
||||
// valid fields so malformed JSON cannot replace the object or inject NaN /
|
||||
@@ -282,7 +308,10 @@ export function createBotRouter(
|
||||
voiceDucking: config.voiceDucking,
|
||||
localAudioEnabled: config.localAudioEnabled,
|
||||
savedQueuesEnabled: config.savedQueuesEnabled,
|
||||
perUserMusicAccounts: config.perUserMusicAccounts === true,
|
||||
playKeepsQueue: config.playKeepsQueue,
|
||||
// Silent re-resolve budget for a track whose URL came back empty.
|
||||
playUrlRetries: config.playUrlRetries ?? 0,
|
||||
adminGroups: config.adminGroups ?? [],
|
||||
guestMode: config.guestMode,
|
||||
spotify: maskedSpotify(),
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import pino from "pino";
|
||||
import { createDatabase } from "../../data/database.js";
|
||||
import { createUserStore } from "../../data/users.js";
|
||||
import { createMusicAccountsRouter } from "./music-accounts.js";
|
||||
|
||||
function mount(opts: { cookieStore?: { save: any; load: any }; providers?: Record<string, any> } = {}) {
|
||||
const db = createDatabase(":memory:");
|
||||
const insert = db.db.prepare(
|
||||
"INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)",
|
||||
);
|
||||
insert.run("u1", "alice", "x", 0, 0, "member");
|
||||
insert.run("u2", "bob", "x", 0, 0, "member");
|
||||
insert.run("u3", "carol", "x", 0, 0, "member");
|
||||
insert.run("u4", "root2", "x", 0, 0, "admin");
|
||||
|
||||
const users = createUserStore(db.db);
|
||||
const providers = opts.providers ?? {
|
||||
netease: {
|
||||
platform: "netease",
|
||||
withCookie: vi.fn(() => ({ getAuthStatus: async () => ({ loggedIn: true, nickname: "主号" }) })),
|
||||
},
|
||||
};
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
(req as any).user = { id: "admin", username: "admin", role: "admin" };
|
||||
next();
|
||||
});
|
||||
app.use(
|
||||
"/api/music-accounts",
|
||||
createMusicAccountsRouter(db, users, providers as any, pino({ level: "silent" }), opts.cookieStore as any),
|
||||
);
|
||||
return { app, db, providers };
|
||||
}
|
||||
|
||||
const SECRET = "MUSIC_U=abcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
async function seed(app: express.Express, over: Record<string, unknown> = {}) {
|
||||
const res = await request(app)
|
||||
.post("/api/music-accounts")
|
||||
.send({ platform: "netease", label: "主号", cookie: SECRET, ...over });
|
||||
return res;
|
||||
}
|
||||
|
||||
describe("admin music account pool", () => {
|
||||
it("creates an account and never echoes the cookie", async () => {
|
||||
const { app } = mount();
|
||||
const res = await seed(app);
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.label).toBe("主号");
|
||||
expect(res.body.capacity).toBe(0);
|
||||
expect(res.body.enabled).toBe(true);
|
||||
expect(JSON.stringify(res.body)).not.toContain(SECRET);
|
||||
expect(res.body.cookiePreview).toContain("…");
|
||||
});
|
||||
|
||||
it("rejects an unknown platform and a missing cookie", async () => {
|
||||
const { app } = mount();
|
||||
expect((await seed(app, { platform: "deezer" })).status).toBe(400);
|
||||
expect((await seed(app, { cookie: "" })).status).toBe(400);
|
||||
expect((await seed(app, { label: "" })).status).toBe(400);
|
||||
});
|
||||
|
||||
it("lists accounts with their holders and the assignable users", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app);
|
||||
await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" });
|
||||
|
||||
const res = await request(app).get("/api/music-accounts");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.accounts).toHaveLength(1);
|
||||
expect(res.body.accounts[0].granteeCount).toBe(1);
|
||||
expect(res.body.accounts[0].grantees[0]).toMatchObject({ userId: "u1", username: "alice" });
|
||||
// Guests are excluded from the dropdown by UserStore.listUsers().
|
||||
expect(res.body.users.map((u: any) => u.username)).toEqual(["alice", "bob", "carol", "root2"]);
|
||||
expect(JSON.stringify(res.body)).not.toContain(SECRET);
|
||||
});
|
||||
|
||||
it("toggles enabled and capacity", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app);
|
||||
const res = await request(app)
|
||||
.patch(`/api/music-accounts/${created.body.id}`)
|
||||
.send({ enabled: false, capacity: 1, label: "备用" });
|
||||
expect(res.body).toEqual(expect.objectContaining({ enabled: false, capacity: 1, label: "备用" }));
|
||||
});
|
||||
|
||||
it("enforces exclusive capacity (capacity = 1)", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app, { capacity: 1 });
|
||||
const id = created.body.id;
|
||||
|
||||
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200);
|
||||
const second = await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u2" });
|
||||
expect(second.status).toBe(409);
|
||||
expect(second.body.error).toBe("account_exclusive");
|
||||
expect(second.body.holders).toEqual([{ userId: "u1", username: "alice" }]);
|
||||
|
||||
// Re-assigning the SAME user is idempotent, not a conflict.
|
||||
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200);
|
||||
});
|
||||
|
||||
it("enforces a numeric capacity", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app, { capacity: 2 });
|
||||
const id = created.body.id;
|
||||
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u1" })).status).toBe(200);
|
||||
expect((await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u2" })).status).toBe(200);
|
||||
const third = await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId: "u3" });
|
||||
expect(third.status).toBe(409);
|
||||
expect(third.body.error).toBe("account_full");
|
||||
});
|
||||
|
||||
it("allows unlimited grantees when capacity is 0", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app);
|
||||
for (const userId of ["u1", "u2", "u3", "u4"]) {
|
||||
expect(
|
||||
(await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId })).status,
|
||||
).toBe(200);
|
||||
}
|
||||
// An admin can be a grantee too — "assigning an admin out" is allowed.
|
||||
const list = await request(app).get("/api/music-accounts");
|
||||
expect(list.body.accounts[0].grantees.map((g: any) => g.username).sort()).toEqual([
|
||||
"alice", "bob", "carol", "root2",
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses an assignment to a missing user", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app);
|
||||
expect(
|
||||
(await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "nope" })).status,
|
||||
).toBe(404);
|
||||
});
|
||||
|
||||
it("refuses an assignment from a disabled account", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app, { enabled: false });
|
||||
const res = await request(app)
|
||||
.post(`/api/music-accounts/${created.body.id}/assign`)
|
||||
.send({ userId: "u1" });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error).toBe("account_disabled");
|
||||
});
|
||||
|
||||
it("replaces the previous assignment for the same platform", async () => {
|
||||
const { app, db } = mount();
|
||||
const first = await seed(app, { label: "一号" });
|
||||
const second = await seed(app, { label: "二号" });
|
||||
await request(app).post(`/api/music-accounts/${first.body.id}/assign`).send({ userId: "u1" });
|
||||
const res = await request(app)
|
||||
.post(`/api/music-accounts/${second.body.id}/assign`)
|
||||
.send({ userId: "u1" });
|
||||
expect(res.body.replacedAccountId).toBe(first.body.id);
|
||||
|
||||
// PK (userId, platform) keeps it to one assigned login per platform.
|
||||
const grants = db.listAllMusicAccountGrants().filter((g) => g.userId === "u1");
|
||||
expect(grants).toHaveLength(1);
|
||||
expect(grants[0].accountId).toBe(second.body.id);
|
||||
});
|
||||
|
||||
it("revokes a single assignment", async () => {
|
||||
const { app, db } = mount();
|
||||
const created = await seed(app);
|
||||
await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" });
|
||||
const res = await request(app).delete(`/api/music-accounts/${created.body.id}/assign/u1`);
|
||||
expect(res.body).toEqual({ ok: true, removed: true });
|
||||
expect(db.getGrantedMusicAccount("u1", "netease")).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves a replacement assignment when an old assignment is revoked", async () => {
|
||||
const { app, db } = mount();
|
||||
const first = await seed(app, { label: "一号" });
|
||||
const second = await seed(app, { label: "二号" });
|
||||
for (const account of [first, second]) {
|
||||
await request(app).post(`/api/music-accounts/${account.body.id}/assign`).send({ userId: "u1" }).expect(200);
|
||||
}
|
||||
const res = await request(app).delete(`/api/music-accounts/${first.body.id}/assign/u1`).expect(200);
|
||||
expect(res.body.removed).toBe(false);
|
||||
expect(db.getGrantedMusicAccount("u1", "netease")?.accountId).toBe(second.body.id);
|
||||
});
|
||||
|
||||
it("does not lower the capacity below the current number of assignees", async () => {
|
||||
const { app, db } = mount();
|
||||
const id = (await seed(app)).body.id;
|
||||
for (const userId of ["u1", "u2"]) {
|
||||
await request(app).post(`/api/music-accounts/${id}/assign`).send({ userId }).expect(200);
|
||||
}
|
||||
await request(app).patch(`/api/music-accounts/${id}`).send({ capacity: 1 }).expect(409);
|
||||
expect(db.getMusicAccount(id)?.capacity).toBe(0);
|
||||
});
|
||||
|
||||
// Deleting the account must not leave grants pointing at a dead row.
|
||||
it("cascades grantees when the account is deleted", async () => {
|
||||
const { app, db } = mount();
|
||||
const created = await seed(app);
|
||||
await request(app).post(`/api/music-accounts/${created.body.id}/assign`).send({ userId: "u1" });
|
||||
expect((await request(app).delete(`/api/music-accounts/${created.body.id}`)).status).toBe(200);
|
||||
expect(db.listMusicAccounts()).toHaveLength(0);
|
||||
expect(db.getGrantedMusicAccount("u1", "netease")).toBeNull();
|
||||
});
|
||||
|
||||
it("probes the login and reports unsupported platforms", async () => {
|
||||
const { app } = mount();
|
||||
const created = await seed(app);
|
||||
const ok = await request(app).post(`/api/music-accounts/${created.body.id}/probe`);
|
||||
expect(ok.body).toEqual({ ok: true, loggedIn: true, nickname: "主号" });
|
||||
|
||||
// kugou without a withCookie implementation → 501, not a crash.
|
||||
const kugou = await seed(app, { platform: "kugou", label: "酷狗" });
|
||||
expect(kugou.status).toBe(201);
|
||||
expect((await request(app).post(`/api/music-accounts/${kugou.body.id}/probe`)).status).toBe(501);
|
||||
});
|
||||
|
||||
it("imports the shared login into the pool", async () => {
|
||||
const cookieStore = {
|
||||
save: vi.fn(),
|
||||
load: vi.fn(() => "MUSIC_U=shared"),
|
||||
};
|
||||
const { app } = mount({ cookieStore });
|
||||
const res = await request(app)
|
||||
.post("/api/music-accounts/import-shared")
|
||||
.send({ platform: "netease", label: "从共享导入" });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.label).toBe("从共享导入");
|
||||
expect(cookieStore.load).toHaveBeenCalledWith("netease");
|
||||
});
|
||||
|
||||
it("409s import-shared when the bot has no shared login", async () => {
|
||||
const cookieStore = { save: vi.fn(), load: vi.fn(() => "") };
|
||||
const { app } = mount({ cookieStore });
|
||||
const res = await request(app)
|
||||
.post("/api/music-accounts/import-shared")
|
||||
.send({ platform: "netease" });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error).toBe("no_shared_login");
|
||||
});
|
||||
|
||||
it("imports the running QQ cookie instead of the stale file copy", async () => {
|
||||
const cookieStore = { save: vi.fn(), load: vi.fn(() => "uin=999; qm_keyst=stale") };
|
||||
const qq = {
|
||||
platform: "qq",
|
||||
withCookie: vi.fn(),
|
||||
// 托管会话轮换后,内存里已经是新 cookie,qq.json 还是旧的
|
||||
getCookie: () => "uin=1; qm_keyst=rotated",
|
||||
};
|
||||
const { app, db } = mount({ cookieStore, providers: { qq } });
|
||||
const res = await request(app)
|
||||
.post("/api/music-accounts/import-shared")
|
||||
.send({ platform: "qq", label: "QQ 主号" });
|
||||
expect(res.status).toBe(201);
|
||||
expect(db.listMusicAccounts()[0]?.cookie).toBe("uin=1; qm_keyst=rotated");
|
||||
expect(cookieStore.load).not.toHaveBeenCalled();
|
||||
// cookie 不出服务器:响应里不能出现完整值
|
||||
expect(JSON.stringify(res.body)).not.toContain("rotated");
|
||||
});
|
||||
|
||||
it("409s a QQ import when the running provider has no login", async () => {
|
||||
const cookieStore = { save: vi.fn(), load: vi.fn(() => "uin=999; qm_keyst=stale") };
|
||||
const qq = { platform: "qq", withCookie: vi.fn(), getCookie: () => "" };
|
||||
const { app, db } = mount({ cookieStore, providers: { qq } });
|
||||
const res = await request(app)
|
||||
.post("/api/music-accounts/import-shared")
|
||||
.send({ platform: "qq" });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error).toBe("no_shared_login");
|
||||
expect(db.listMusicAccounts()).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,360 @@
|
||||
import { Router } from "express";
|
||||
import type { BotDatabase, MusicAccount } from "../../data/database.js";
|
||||
import type { MusicProvider } from "../../music/provider.js";
|
||||
import type { CookieStore } from "../../music/auth.js";
|
||||
import type { UserStore } from "../../data/users.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import { PERSONAL_MUSIC_PLATFORMS } from "./personal-music.js";
|
||||
|
||||
/**
|
||||
* Admin console for the music-account pool (#164 follow-up).
|
||||
*
|
||||
* Why a pool instead of "everyone links their own account":
|
||||
* - Most members do not own a paid NetEase/QQ/Kugou login, and the bot's
|
||||
* shared account is usually the ADMIN's. Handing the shared login to some
|
||||
* members while giving others their own is exactly the "mixed" case this
|
||||
* feature has to support.
|
||||
* - So the admin keeps a pool of logins (`music_accounts`) and assigns one to
|
||||
* a member (`music_account_grants`). Assignment is per platform, and a
|
||||
* member can hold at most one assigned account per platform.
|
||||
*
|
||||
* The controls that stop assignments from turning into a mess:
|
||||
* 1. OWN BEATS ASSIGNED. A member who linked their own account ignores the
|
||||
* assignment entirely (see provider-scope.ts). Assigning never overrides
|
||||
* a member's own login.
|
||||
* 2. CAPACITY. `capacity = 1` means exclusive: the API refuses to hand the
|
||||
* same login to a second member (409). `capacity = 0` means unlimited
|
||||
* (fine for a throwaway account, NOT for one whose recommendations you
|
||||
* care about — every grantee writes to that account's history).
|
||||
* 3. ENABLED FLAG. Disabling an account is an instant, reversible rollback:
|
||||
* every grantee falls back to their own login / the shared login without
|
||||
* the grants being deleted.
|
||||
* 4. DELETE CASCADES. Removing an account deletes its grants in the same
|
||||
* transaction (FK ON DELETE CASCADE), so no member is left pointing at a
|
||||
* row that no longer exists.
|
||||
* 5. COOKIES NEVER LEAVE THE SERVER. Every response carries a masked
|
||||
* preview only; the full value is only ever written, never read back.
|
||||
*
|
||||
* The whole router is admin-only (requireAdmin at the mount point): a member
|
||||
* with `bot.manage` still must not see what other people are assigned.
|
||||
*/
|
||||
export function createMusicAccountsRouter(
|
||||
database: BotDatabase,
|
||||
users: UserStore,
|
||||
providers: Partial<Record<string, MusicProvider>>,
|
||||
logger: Logger,
|
||||
cookieStore?: CookieStore,
|
||||
): Router {
|
||||
const router = Router();
|
||||
|
||||
const knownPlatforms = new Set<string>(PERSONAL_MUSIC_PLATFORMS);
|
||||
|
||||
/**
|
||||
* Cookies are bearer credentials: showing one in full once is enough to take
|
||||
* the account over. The console only ever needs to tell two logins apart.
|
||||
*/
|
||||
const maskCookie = (cookie: string): string => {
|
||||
if (!cookie) return "";
|
||||
if (cookie.length <= 16) return "••••••";
|
||||
return `${cookie.slice(0, 6)}…${cookie.slice(-4)} (${cookie.length} 字符)`;
|
||||
};
|
||||
|
||||
const toWire = (a: MusicAccount) => {
|
||||
const holders = database.listMusicAccountGrants(a.id);
|
||||
return {
|
||||
id: a.id,
|
||||
platform: a.platform,
|
||||
label: a.label,
|
||||
cookiePreview: maskCookie(a.cookie),
|
||||
ownerId: a.ownerId,
|
||||
capacity: a.capacity,
|
||||
enabled: a.enabled,
|
||||
createdAt: a.createdAt,
|
||||
updatedAt: a.updatedAt,
|
||||
// The UI needs the count to grey out "assign" on an exclusive account.
|
||||
granteeCount: holders.length,
|
||||
grantees: holders.map((g) => ({
|
||||
userId: g.userId,
|
||||
username: g.username,
|
||||
grantedAt: g.grantedAt,
|
||||
})),
|
||||
// A platform without withCookie stores the cookie but cannot build a
|
||||
// per-account view yet — surfaced so the admin is not left guessing.
|
||||
playbackSupported: typeof providers[a.platform]?.withCookie === "function",
|
||||
};
|
||||
};
|
||||
|
||||
const isPlatform = (v: unknown): v is (typeof PERSONAL_MUSIC_PLATFORMS)[number] =>
|
||||
typeof v === "string" && knownPlatforms.has(v);
|
||||
|
||||
const nonEmpty = (v: unknown, max: number): v is string =>
|
||||
typeof v === "string" && v.trim().length > 0 && v.length <= max;
|
||||
|
||||
const validCapacity = (value: unknown): value is number | undefined =>
|
||||
value === undefined || (typeof value === "number" && Number.isSafeInteger(value) && value >= 0);
|
||||
|
||||
/** Every real (non-guest) user, for the assign dropdown. */
|
||||
const assignableUsers = () =>
|
||||
users.listUsers().map((u) => ({ id: u.id, username: u.username, role: u.role }));
|
||||
|
||||
router.get("/", (_req, res) => {
|
||||
const accounts = database.listMusicAccounts().map(toWire);
|
||||
res.json({
|
||||
accounts,
|
||||
users: assignableUsers(),
|
||||
platforms: [...PERSONAL_MUSIC_PLATFORMS].map((p) => ({
|
||||
platform: p,
|
||||
// Only platforms that implement withCookie can actually play back a
|
||||
// per-user login; the rest accept a paste but fall back to shared.
|
||||
playbackSupported: typeof providers[p]?.withCookie === "function",
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
router.post("/", (req, res) => {
|
||||
const { platform, label, cookie, capacity, ownerId, enabled } = req.body ?? {};
|
||||
if (!isPlatform(platform)) {
|
||||
res.status(400).json({ error: "unsupported platform" });
|
||||
return;
|
||||
}
|
||||
if (!nonEmpty(label, 64)) {
|
||||
res.status(400).json({ error: "label is required (max 64 chars)" });
|
||||
return;
|
||||
}
|
||||
if (!nonEmpty(cookie, 8192)) {
|
||||
res.status(400).json({ error: "cookie is required" });
|
||||
return;
|
||||
}
|
||||
if (!validCapacity(capacity)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative integer" });
|
||||
return;
|
||||
}
|
||||
if (ownerId !== undefined && ownerId !== null && typeof ownerId !== "string") {
|
||||
res.status(400).json({ error: "ownerId must be a string or null" });
|
||||
return;
|
||||
}
|
||||
if (enabled !== undefined && typeof enabled !== "boolean") {
|
||||
res.status(400).json({ error: "enabled must be a boolean" });
|
||||
return;
|
||||
}
|
||||
const created = database.createMusicAccount({
|
||||
platform,
|
||||
label: label.trim(),
|
||||
cookie: cookie.trim(),
|
||||
ownerId: ownerId ?? null,
|
||||
capacity,
|
||||
// Creating a disabled account is allowed: it lets the admin stage a
|
||||
// cookie before handing it out.
|
||||
enabled: enabled !== false,
|
||||
});
|
||||
logger.info({ accountId: created.id, platform, label: created.label }, "Music account added");
|
||||
res.status(201).json(toWire(created));
|
||||
});
|
||||
|
||||
router.patch("/:id", (req, res) => {
|
||||
const account = database.getMusicAccount(req.params.id);
|
||||
if (!account) {
|
||||
res.status(404).json({ error: "not found" });
|
||||
return;
|
||||
}
|
||||
const { label, cookie, capacity, enabled } = req.body ?? {};
|
||||
if (label !== undefined && !nonEmpty(label, 64)) {
|
||||
res.status(400).json({ error: "invalid label" });
|
||||
return;
|
||||
}
|
||||
if (cookie !== undefined && !nonEmpty(cookie, 8192)) {
|
||||
res.status(400).json({ error: "invalid cookie" });
|
||||
return;
|
||||
}
|
||||
if (!validCapacity(capacity)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative integer" });
|
||||
return;
|
||||
}
|
||||
if (enabled !== undefined && typeof enabled !== "boolean") {
|
||||
res.status(400).json({ error: "enabled must be a boolean" });
|
||||
return;
|
||||
}
|
||||
// Replacing the cookie invalidates any device-bound session (Kugou binds
|
||||
// the token to guid/mid) — the existing grants keep pointing at the row,
|
||||
// so the admin only has to paste a fresh cookie to fix everyone at once.
|
||||
const updated = database.updateMusicAccount(account.id, {
|
||||
label: label === undefined ? undefined : label.trim(),
|
||||
cookie: cookie === undefined ? undefined : cookie.trim(),
|
||||
capacity,
|
||||
enabled,
|
||||
});
|
||||
if (!updated) {
|
||||
res.status(409).json({ error: "capacity_below_existing_grants" });
|
||||
return;
|
||||
}
|
||||
logger.info(
|
||||
{ accountId: account.id, enabled: enabled ?? account.enabled },
|
||||
"Music account updated",
|
||||
);
|
||||
res.json(toWire(database.getMusicAccount(account.id)!));
|
||||
});
|
||||
|
||||
router.delete("/:id", (req, res) => {
|
||||
const account = database.getMusicAccount(req.params.id);
|
||||
if (!account) {
|
||||
res.status(404).json({ error: "not found" });
|
||||
return;
|
||||
}
|
||||
// FK ON DELETE CASCADE removes the grants with it, so no member is left
|
||||
// pointing at a deleted row. `changes` on the parent is what we report.
|
||||
const deleted = database.deleteMusicAccount(account.id);
|
||||
logger.info(
|
||||
{ accountId: account.id, platform: account.platform, deleted },
|
||||
"Music account removed",
|
||||
);
|
||||
res.json({ ok: deleted, revokedGrants: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* Assign an account to a user (member OR another admin — an admin can be a
|
||||
* grantee too, they are just not forced onto the shared login).
|
||||
*/
|
||||
router.post("/:id/assign", (req, res) => {
|
||||
const account = database.getMusicAccount(req.params.id);
|
||||
if (!account) {
|
||||
res.status(404).json({ error: "not_found" });
|
||||
return;
|
||||
}
|
||||
const { userId } = req.body ?? {};
|
||||
if (typeof userId !== "string" || !userId) {
|
||||
res.status(400).json({ error: "userId is required" });
|
||||
return;
|
||||
}
|
||||
const target = users.findById(userId);
|
||||
if (!target || target.role === "guest") {
|
||||
res.status(404).json({ error: "user not found" });
|
||||
return;
|
||||
}
|
||||
|
||||
// Enabled + capacity are enforced inside a single transaction in the data
|
||||
// layer, so two concurrent assignments cannot both slip past the check.
|
||||
const result = database.assignMusicAccount(userId, account.id, req.user!.id);
|
||||
if (!result.ok) {
|
||||
if (result.reason === "not_found") {
|
||||
res.status(404).json({ error: "not_found" });
|
||||
return;
|
||||
}
|
||||
if (result.reason === "disabled") {
|
||||
res.status(409).json({ error: "account_disabled" });
|
||||
return;
|
||||
}
|
||||
const holders = database.listMusicAccountGrants(account.id).map((h) => ({
|
||||
userId: h.userId,
|
||||
username: h.username,
|
||||
}));
|
||||
if (result.reason === "exclusive") {
|
||||
res.status(409).json({ error: "account_exclusive", holders });
|
||||
return;
|
||||
}
|
||||
res.status(409).json({ error: "account_full", capacity: account.capacity, holders });
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(
|
||||
{ accountId: account.id, userId, replacedAccountId: result.replacedAccountId },
|
||||
"Music account assigned",
|
||||
);
|
||||
res.json({
|
||||
ok: true,
|
||||
userId,
|
||||
username: target.username,
|
||||
accountId: account.id,
|
||||
platform: account.platform,
|
||||
replacedAccountId: result.replacedAccountId,
|
||||
});
|
||||
});
|
||||
|
||||
router.delete("/:id/assign/:userId", (req, res) => {
|
||||
const account = database.getMusicAccount(req.params.id);
|
||||
if (!account) {
|
||||
res.status(404).json({ error: "not found" });
|
||||
return;
|
||||
}
|
||||
const removed = database.deleteMusicAccountGrant(req.params.userId, account.platform, account.id);
|
||||
logger.info(
|
||||
{ accountId: account.id, userId: req.params.userId, removed },
|
||||
"Music account assignment revoked",
|
||||
);
|
||||
res.json({ ok: true, removed });
|
||||
});
|
||||
|
||||
/** Live check: is this cookie still logged in? */
|
||||
router.post("/:id/probe", async (req, res) => {
|
||||
const account = database.getMusicAccount(req.params.id);
|
||||
if (!account) {
|
||||
res.status(404).json({ error: "not found" });
|
||||
return;
|
||||
}
|
||||
const provider = providers[account.platform];
|
||||
if (!provider || typeof provider.withCookie !== "function") {
|
||||
res.status(501).json({ error: "playback not supported for this platform" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const status = await provider.withCookie(account.cookie).getAuthStatus();
|
||||
res.json({ ok: true, ...status });
|
||||
} catch {
|
||||
logger.warn({ accountId: account.id }, "Music account probe failed");
|
||||
res.status(502).json({ error: "music_account_probe_failed", loggedIn: false });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Seed the pool with the login the bot already uses, so an admin who scanned
|
||||
* the shared account can hand it to selected members without re-scanning.
|
||||
*/
|
||||
router.post("/import-shared", (req, res) => {
|
||||
const { platform, label, capacity } = req.body ?? {};
|
||||
// QQ 的共享登录以"运行中的 provider"为准:登录写的是它内存里的 cookie,
|
||||
// qq.json 只是落盘副本。托管会话轮换凭据之后文件就旧了(#188),
|
||||
// 从这里导入会把一个过期 cookie 塞进账号池。
|
||||
const sharedQq = platform === "qq" ? providers.qq : undefined;
|
||||
if (!sharedQq && !cookieStore) {
|
||||
res.status(501).json({ error: "cookie store unavailable" });
|
||||
return;
|
||||
}
|
||||
if (!isPlatform(platform)) {
|
||||
res.status(400).json({ error: "unsupported platform" });
|
||||
return;
|
||||
}
|
||||
if (!validCapacity(capacity)) {
|
||||
res.status(400).json({ error: "capacity must be a non-negative integer" });
|
||||
return;
|
||||
}
|
||||
// 没有 qq provider(例如单测只挂了 netease)时仍然回落到 cookie store,
|
||||
// 所以这个改动对已有平台零影响。
|
||||
let cookie: string | undefined;
|
||||
if (sharedQq) {
|
||||
try {
|
||||
cookie = sharedQq.getCookie();
|
||||
} catch {
|
||||
// Provider 还没建立登录态时抛错等价于「没有可导入的登录」
|
||||
cookie = "";
|
||||
}
|
||||
} else {
|
||||
cookie = cookieStore?.load(platform);
|
||||
}
|
||||
if (!cookie || !cookie.trim()) {
|
||||
res.status(409).json({ error: "no_shared_login", platform });
|
||||
return;
|
||||
}
|
||||
const created = database.createMusicAccount({
|
||||
platform,
|
||||
label: nonEmpty(label, 64) ? label.trim() : `${platform} 共享账号`,
|
||||
cookie: cookie.trim(),
|
||||
// ownerId stays null: this login was provided by the bot, not a person.
|
||||
ownerId: null,
|
||||
capacity,
|
||||
enabled: true,
|
||||
});
|
||||
logger.info({ accountId: created.id, platform }, "Shared login imported into pool");
|
||||
res.status(201).json(toWire(created));
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import express from "express";
|
||||
import cookieParser from "cookie-parser";
|
||||
import request from "supertest";
|
||||
import pino from "pino";
|
||||
import { AxiosError } from "axios";
|
||||
import { mkdtempSync, rmSync, readFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
@@ -58,6 +59,18 @@ describe("music router GET /search offset pagination", () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(netease.search).toHaveBeenCalledWith("hello", 20, 0);
|
||||
});
|
||||
|
||||
it("keeps provider request credentials out of search errors", async () => {
|
||||
const logger = pino({ level: "silent" });
|
||||
const logError = vi.spyOn(logger, "error");
|
||||
const privateCookie = "MUSIC_U=test-private-session";
|
||||
vi.mocked(netease.search).mockRejectedValueOnce(new AxiosError(`Provider request failed: ${privateCookie}`));
|
||||
const route = express();
|
||||
route.use("/api/music", createMusicRouter(netease, fakeProvider("qq"), fakeProvider("bilibili"), logger));
|
||||
const res = await request(route).get("/api/music/search?q=test").expect(500);
|
||||
expect(res.text).not.toContain(privateCookie);
|
||||
expect(JSON.stringify(logError.mock.calls)).not.toContain(privateCookie);
|
||||
});
|
||||
});
|
||||
|
||||
describe("music router provider gating (enabledProviders) + jellyfin endpoints", () => {
|
||||
|
||||
+71
-36
@@ -1,11 +1,14 @@
|
||||
import express, { Router, type Response } from "express";
|
||||
import express, { Router, type Request, type Response } from "express";
|
||||
import type { MusicProvider, Song, Album, SearchResult } from "../../music/provider.js";
|
||||
import { musicRequestError } from "../../music/request-error.js";
|
||||
import { YouTubeProvider } from "../../music/youtube.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import { isProviderEnabled, defaultPlatform, saveConfig, type BotConfig } from "../../data/config.js";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
import { requirePermission } from "../middleware/requirePermission.js";
|
||||
import { requireNotGuest } from "../middleware/requireNotGuest.js";
|
||||
import { authorize } from "../middleware/authorize.js";
|
||||
import { resolveProviderForRequest } from "./provider-scope.js";
|
||||
|
||||
/**
|
||||
* Body cap for a local upload. express.raw buffers the whole body in memory,
|
||||
@@ -70,6 +73,10 @@ export function createMusicRouter(
|
||||
// When set (alongside config), a quality change is persisted to config.json so
|
||||
// it survives a restart (#125). Omitted by unit-test routers → no persistence.
|
||||
configPath?: string,
|
||||
// Per-user music accounts (#164 follow-up): when config.perUserMusicAccounts
|
||||
// is on, a request carrying a linked account reads through that account
|
||||
// instead of the bot's shared login. Omitted by unit-test routers → shared.
|
||||
database?: BotDatabase,
|
||||
): Router {
|
||||
const router = Router();
|
||||
const youtubeProvider: MusicProvider = new YouTubeProvider();
|
||||
@@ -95,14 +102,25 @@ export function createMusicRouter(
|
||||
* return immediately. Without a config (unit-test routers), everything
|
||||
* stays enabled.
|
||||
*/
|
||||
function resolveProvider(platform: unknown, res: Response): MusicProvider | null {
|
||||
function resolveProvider(
|
||||
platform: unknown,
|
||||
res: Response,
|
||||
req?: Request,
|
||||
): MusicProvider | null {
|
||||
const requested = typeof platform === "string" && platform ? platform : undefined;
|
||||
const target = requested ?? (config ? defaultPlatform(config) : "netease");
|
||||
if (config && !isProviderEnabled(config, target)) {
|
||||
res.status(400).json({ error: `音源未启用:${target} (provider disabled)` });
|
||||
return null;
|
||||
}
|
||||
return getProvider(target);
|
||||
// Per-user accounts: with the feature on, a user who linked their own
|
||||
// account reads search/playlists/lyrics/artists through THAT
|
||||
// login instead of the bot's shared one, so members stop seeing the
|
||||
// admin's library. Everyone else keeps the shared provider unchanged.
|
||||
return resolveProviderForRequest(req, target, getProvider(target), {
|
||||
database,
|
||||
config,
|
||||
});
|
||||
}
|
||||
|
||||
router.post(
|
||||
@@ -164,7 +182,7 @@ export function createMusicRouter(
|
||||
res.json({ songs: [], playlists: [], albums: [] });
|
||||
return;
|
||||
}
|
||||
const provider = resolveProvider(platform, res);
|
||||
const provider = resolveProvider(platform, res, req);
|
||||
if (!provider) return;
|
||||
// Server-side pagination: offset lets the web load past the first page.
|
||||
// Clamp to >= 0 so a bad/negative value falls back to the first page.
|
||||
@@ -176,8 +194,9 @@ export function createMusicRouter(
|
||||
);
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Search failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Search failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -199,13 +218,24 @@ export function createMusicRouter(
|
||||
// enabled — a self-hosted library match is almost always the wanted one.
|
||||
const enabled = (p: string) => !config || isProviderEnabled(config, p);
|
||||
const none: SearchResult = { songs: [], albums: [], playlists: [] };
|
||||
// Unified search hits every source at once, so each one has to be scoped
|
||||
// individually — otherwise a member with their own linked account would
|
||||
// still get the admin's results merged in from the other platforms.
|
||||
// Local audio and Jellyfin have no per-account login, so they stay shared.
|
||||
const scope = { database, config };
|
||||
const nProvider = resolveProviderForRequest(req, "netease", neteaseProvider, scope);
|
||||
const qProvider = resolveProviderForRequest(req, "qq", qqProvider, scope);
|
||||
const bProvider = resolveProviderForRequest(req, "bilibili", bilibiliProvider, scope);
|
||||
const kProvider = kugouProvider
|
||||
? resolveProviderForRequest(req, "kugou", kugouProvider, scope)
|
||||
: kugouProvider;
|
||||
const [jellyfinResult, neteaseResult, qqResult, bilibiliResult, localResult, kugouResult] = await Promise.allSettled([
|
||||
jellyfinProvider && enabled("jellyfin") ? jellyfinProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("netease") ? neteaseProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("qq") ? qqProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("bilibili") ? bilibiliProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("netease") ? nProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("qq") ? qProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
enabled("bilibili") ? bProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
localProvider && isLocalAudioEnabled() ? localProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
kugouProvider && enabled("kugou") ? kugouProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
kProvider && enabled("kugou") ? kProvider.search(q as string, parsedLimit) : Promise.resolve(none),
|
||||
]);
|
||||
|
||||
const songs = [
|
||||
@@ -235,8 +265,9 @@ export function createMusicRouter(
|
||||
|
||||
res.json({ songs, albums, playlists, artists });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Unified search failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Unified search failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -246,7 +277,7 @@ export function createMusicRouter(
|
||||
res.status(403).json({ error: "本地音频播放已关闭" });
|
||||
return;
|
||||
}
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
const song = await provider.getSongDetail(req.params.id);
|
||||
if (!song) {
|
||||
@@ -255,57 +286,57 @@ export function createMusicRouter(
|
||||
}
|
||||
res.json(song);
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/playlist/:id", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
const songs = await provider.getPlaylistSongs(req.params.id);
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/recommend/playlists", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
const playlists = await provider.getRecommendPlaylists();
|
||||
res.json({ playlists });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/album/:id", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
const songs = await provider.getAlbumSongs(req.params.id);
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/lyrics/:id", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
const lyrics = await provider.getLyrics(req.params.id);
|
||||
res.json({ lyrics });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/artist/:id", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
if (!provider.getArtistDetail) {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
@@ -329,13 +360,13 @@ export function createMusicRouter(
|
||||
}
|
||||
res.json({ artist, songs, albums });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/recommend/songs", requireNotGuest, async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
if (!provider.getDailyRecommendSongs) {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
@@ -344,14 +375,15 @@ export function createMusicRouter(
|
||||
const songs = await provider.getDailyRecommendSongs();
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get daily recommend songs failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get daily recommend songs failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/personal/fm", requireNotGuest, async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
if (!provider.getPersonalFm) {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
@@ -360,14 +392,15 @@ export function createMusicRouter(
|
||||
const songs = await provider.getPersonalFm();
|
||||
res.json({ songs });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get personal FM failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get personal FM failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/user/playlists", requireNotGuest, async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
if (!provider.getUserPlaylists) {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
@@ -376,14 +409,15 @@ export function createMusicRouter(
|
||||
const playlists = await provider.getUserPlaylists();
|
||||
res.json({ playlists });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get user playlists failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get user playlists failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/playlist/:id/detail", async (req, res) => {
|
||||
try {
|
||||
const provider = resolveProvider(req.query.platform, res);
|
||||
const provider = resolveProvider(req.query.platform, res, req);
|
||||
if (!provider) return;
|
||||
if (!provider.getPlaylistDetail) {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
@@ -396,8 +430,9 @@ export function createMusicRouter(
|
||||
}
|
||||
res.json({ playlist: detail });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Get playlist detail failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Get playlist detail failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -6,7 +6,10 @@ import { createDatabase } from "../../data/database.js";
|
||||
import { createPersonalMusicRouter } from "./personal-music.js";
|
||||
import { createPlayerRouter } from "./player.js";
|
||||
|
||||
function mount() {
|
||||
function mount(opts: {
|
||||
config?: { perUserMusicAccounts?: boolean };
|
||||
extraProviders?: Record<string, unknown>;
|
||||
} = {}) {
|
||||
const db = createDatabase(":memory:");
|
||||
db.db
|
||||
.prepare("INSERT INTO users (id, username, passwordHash, createdAt, updatedAt, role) VALUES (?,?,?,?,?,?)")
|
||||
@@ -27,16 +30,38 @@ function mount() {
|
||||
(req as any).user = { id: "u1", username: "alice", role: "member" };
|
||||
next();
|
||||
});
|
||||
app.use("/api/me/music", createPersonalMusicRouter(db, provider, pino({ level: "silent" })));
|
||||
app.use(
|
||||
"/api/me/music",
|
||||
createPersonalMusicRouter(
|
||||
db,
|
||||
{ netease: provider, ...(opts.extraProviders as object) },
|
||||
pino({ level: "silent" }),
|
||||
opts.config,
|
||||
),
|
||||
);
|
||||
return { app, db, provider, personalView };
|
||||
}
|
||||
|
||||
/** Seed an admin-owned account and assign it to u1. */
|
||||
function assignAccount(db: ReturnType<typeof createDatabase>, label = "网易云-主号") {
|
||||
const account = db.createMusicAccount({
|
||||
platform: "netease",
|
||||
label,
|
||||
cookie: "MUSIC_U=granted",
|
||||
});
|
||||
db.assignMusicAccount("u1", account.id, "admin");
|
||||
return account;
|
||||
}
|
||||
|
||||
describe("personal music account router (#164)", () => {
|
||||
it("reports not linked until the user logs in", async () => {
|
||||
const { app } = mount();
|
||||
const res = await request(app).get("/api/me/music/netease/status");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ linked: false, loggedIn: false });
|
||||
expect(res.body).toEqual({
|
||||
linked: false, loggedIn: false, source: "none", canUnlink: false, supportsQrLogin: true,
|
||||
preferShared: false, featureEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("creates a QR code", async () => {
|
||||
@@ -64,7 +89,16 @@ describe("personal music account router (#164)", () => {
|
||||
const { app, db, provider } = mount();
|
||||
db.setUserMusicCookie("u1", "netease", "MUSIC_U=alice");
|
||||
const res = await request(app).get("/api/me/music/netease/status");
|
||||
expect(res.body).toEqual({ linked: true, loggedIn: true, nickname: "Alice163" });
|
||||
expect(res.body).toEqual({
|
||||
linked: true,
|
||||
source: "personal",
|
||||
canUnlink: true,
|
||||
supportsQrLogin: true,
|
||||
preferShared: false,
|
||||
featureEnabled: false,
|
||||
loggedIn: true,
|
||||
nickname: "Alice163",
|
||||
});
|
||||
expect(provider.withCookie).toHaveBeenCalledWith("MUSIC_U=alice");
|
||||
});
|
||||
|
||||
@@ -74,6 +108,62 @@ describe("personal music account router (#164)", () => {
|
||||
expect((await request(app).delete("/api/me/music/netease")).status).toBe(200);
|
||||
expect(db.getUserMusicCookie("u1", "netease")).toBeNull();
|
||||
});
|
||||
|
||||
// 404 for a platform this build does not expose — keeps the param route from
|
||||
// silently answering "not linked" for a typo'd URL.
|
||||
it("404s an unknown platform", async () => {
|
||||
const { app } = mount();
|
||||
expect((await request(app).get("/api/me/music/deezer/status")).status).toBe(404);
|
||||
});
|
||||
|
||||
// qq/kugou/bilibili ship withCookie but not pollQrLogin yet: linking is 501,
|
||||
// while an admin-assigned account still works (see below).
|
||||
it("501s QR login on a platform without per-user polling", async () => {
|
||||
const { app } = mount({ extraProviders: { qq: { platform: "qq", withCookie: vi.fn() } } });
|
||||
expect((await request(app).post("/api/me/music/qq/qrcode")).status).toBe(501);
|
||||
});
|
||||
|
||||
describe("admin-assigned account", () => {
|
||||
it("reports source=granted with the admin's label and forbids unlinking", async () => {
|
||||
const { app, db, provider } = mount({ config: { perUserMusicAccounts: true } });
|
||||
assignAccount(db);
|
||||
const res = await request(app).get("/api/me/music/netease/status");
|
||||
expect(res.body).toEqual({
|
||||
linked: true,
|
||||
source: "granted",
|
||||
label: "网易云-主号",
|
||||
canUnlink: false,
|
||||
supportsQrLogin: true,
|
||||
preferShared: false,
|
||||
featureEnabled: true,
|
||||
loggedIn: true,
|
||||
nickname: "Alice163",
|
||||
});
|
||||
expect(provider.withCookie).toHaveBeenCalledWith("MUSIC_U=granted");
|
||||
});
|
||||
|
||||
it("is invisible while the admin toggle is off", async () => {
|
||||
const { app, db } = mount({ config: { perUserMusicAccounts: false } });
|
||||
assignAccount(db);
|
||||
const res = await request(app).get("/api/me/music/netease/status");
|
||||
expect(res.body).toEqual({
|
||||
linked: false, loggedIn: false, source: "none", canUnlink: false, supportsQrLogin: true,
|
||||
preferShared: false, featureEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
// Unlinking on the member side must never revoke what the admin granted:
|
||||
// the two live in separate tables on purpose.
|
||||
it("survives a member unlink and is reported as the fallback", async () => {
|
||||
const { app, db } = mount({ config: { perUserMusicAccounts: true } });
|
||||
assignAccount(db);
|
||||
db.setUserMusicCookie("u1", "netease", "MUSIC_U=alice");
|
||||
const res = await request(app).delete("/api/me/music/netease");
|
||||
expect(res.body).toEqual({ ok: true, removed: true, fallback: "granted" });
|
||||
expect(db.getUserMusicCookie("u1", "netease")).toBeNull();
|
||||
expect(db.getGrantedMusicAccount("u1", "netease")?.cookie).toBe("MUSIC_U=granted");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("web FM uses the caller's linked NetEase account (#164)", () => {
|
||||
@@ -123,3 +213,73 @@ describe("web FM uses the caller's linked NetEase account (#164)", () => {
|
||||
expect(bot.startFm.mock.calls[0][0]).toBe(qq);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// "Play through the shared account" preference (#164 follow-up)
|
||||
//
|
||||
// The case this exists for: the member's own NetEase login has no VIP, the
|
||||
// admin's does. The preference is per-platform and per-user, and it must not
|
||||
// touch either stored login.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("personal music — shared-account preference", () => {
|
||||
const ON = { config: { perUserMusicAccounts: true } };
|
||||
|
||||
it("defaults to the member's own account", async () => {
|
||||
const { app } = mount(ON);
|
||||
const res = await request(app).get("/api/me/music/netease/preference");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ platform: "netease", preferShared: false });
|
||||
});
|
||||
|
||||
it("stores the choice and reports it back", async () => {
|
||||
const { app } = mount(ON);
|
||||
const put = await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
|
||||
expect(put.status).toBe(200);
|
||||
expect(put.body).toEqual({ platform: "netease", preferShared: true });
|
||||
|
||||
const get = await request(app).get("/api/me/music/netease/preference");
|
||||
expect(get.body.preferShared).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the choice per platform", async () => {
|
||||
const { app } = mount({
|
||||
...ON,
|
||||
extraProviders: { qq: { platform: "qq", withCookie: () => ({ getAuthStatus: async () => ({ loggedIn: true }) }) } },
|
||||
});
|
||||
await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
|
||||
const qq = await request(app).get("/api/me/music/qq/preference");
|
||||
expect(qq.body.preferShared).toBe(false);
|
||||
});
|
||||
|
||||
it("does not touch the stored login", async () => {
|
||||
const { app, db } = mount(ON);
|
||||
db.setUserMusicCookie("u1", "netease", "MUSIC_U=mine");
|
||||
await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
|
||||
|
||||
expect(db.getUserMusicCookie("u1", "netease")).toBe("MUSIC_U=mine");
|
||||
expect(db.getUserMusicPreference("u1", "netease")).toEqual({ preferShared: true });
|
||||
});
|
||||
|
||||
it("surfaces the choice on the status payload the UI already reads", async () => {
|
||||
const { app, db } = mount(ON);
|
||||
db.setUserMusicCookie("u1", "netease", "MUSIC_U=mine");
|
||||
await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
|
||||
|
||||
const res = await request(app).get("/api/me/music/netease/status");
|
||||
expect(res.body.preferShared).toBe(true);
|
||||
expect(res.body.featureEnabled).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a non-boolean", async () => {
|
||||
const { app } = mount(ON);
|
||||
const res = await request(app).put("/api/me/music/netease/preference").send({ preferShared: "yes" });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("refuses when the admin has the feature off", async () => {
|
||||
const { app } = mount({ config: { perUserMusicAccounts: false } });
|
||||
const res = await request(app).put("/api/me/music/netease/preference").send({ preferShared: true });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error).toBe("per_user_accounts_disabled");
|
||||
});
|
||||
});
|
||||
+184
-27
@@ -2,6 +2,7 @@ import { Router } from "express";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
import type { MusicProvider, QrCodeResult } from "../../music/provider.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import { perUserMusicEnabled, type MusicScopeDeps } from "./provider-scope.js";
|
||||
|
||||
/**
|
||||
* A provider that can log a web user into their OWN account without touching
|
||||
@@ -17,56 +18,165 @@ export function supportsPersonalLogin(
|
||||
provider: MusicProvider | undefined,
|
||||
): provider is MusicProvider & PersonalLoginProvider {
|
||||
const p = provider as Partial<PersonalLoginProvider> | undefined;
|
||||
return typeof p?.pollQrLogin === "function" && typeof p.withCookie === "function";
|
||||
return typeof p?.pollQrLogin === "function" && typeof p?.withCookie === "function";
|
||||
}
|
||||
|
||||
/** Platforms a member can link an account for. Kept in sync with the providers map. */
|
||||
export const PERSONAL_MUSIC_PLATFORMS = ["netease", "qq", "kugou", "bilibili"] as const;
|
||||
|
||||
/**
|
||||
* The caller's own NetEase account, used for their personal FM instead of the
|
||||
* bot's shared login (#164). Every route acts on req.user only; the cookie is
|
||||
* stored server-side and never sent back to the browser.
|
||||
* A web user's own music account (#164), generalised to every platform that
|
||||
* implements `withCookie` (#164 follow-up).
|
||||
*
|
||||
* Three states are reported, and the member UI needs all three:
|
||||
* - `personal`: the caller scanned their own QR code. They may unlink it.
|
||||
* - `granted` : an ADMIN assigned one of the pool accounts to them. It cannot
|
||||
* be unlinked from here — only the admin can take it back —
|
||||
* which is why `canUnlink` is part of the payload instead of
|
||||
* the UI guessing from `linked`.
|
||||
* - `none` : nothing linked; playback falls back to the bot's shared login.
|
||||
*
|
||||
* The cookie is stored server-side and never sent back to the browser; the
|
||||
* `label` of an assigned account is what the member sees instead of a nickname.
|
||||
*/
|
||||
export function createPersonalMusicRouter(
|
||||
database: BotDatabase,
|
||||
neteaseProvider: MusicProvider,
|
||||
providers: Partial<Record<string, MusicProvider>>,
|
||||
logger: Logger,
|
||||
config?: MusicScopeDeps["config"],
|
||||
): Router {
|
||||
const router = Router();
|
||||
const platform = "netease";
|
||||
|
||||
router.use((_req, res, next) => {
|
||||
if (!supportsPersonalLogin(neteaseProvider)) {
|
||||
res.status(501).json({ error: "Personal login not supported" });
|
||||
const providerFor = (platform: string): MusicProvider | undefined => providers[platform];
|
||||
|
||||
/** 404 for platforms this build does not expose at all. */
|
||||
router.param("platform", (req, res, next, platform: string) => {
|
||||
if (!providerFor(platform)) {
|
||||
res.status(404).json({ error: `Unknown platform: ${platform}` });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
});
|
||||
const provider = neteaseProvider as MusicProvider & PersonalLoginProvider;
|
||||
|
||||
router.get("/netease/status", async (req, res) => {
|
||||
const cookie = database.getUserMusicCookie(req.user!.id, platform);
|
||||
if (!cookie) {
|
||||
res.json({ linked: false, loggedIn: false });
|
||||
/** Read the account state for one platform: own first, then admin-assigned. */
|
||||
const describeAccount = (
|
||||
userId: string,
|
||||
platform: string,
|
||||
): { source: "personal" | "granted" | "none"; cookie: string | null; label?: string; canUnlink: boolean } => {
|
||||
const own = database.getUserMusicCookie(userId, platform);
|
||||
if (own && own.trim()) {
|
||||
return { source: "personal", cookie: own, canUnlink: true };
|
||||
}
|
||||
// An assignment only exists because the admin turned the feature on, so it
|
||||
// stops applying the moment the toggle goes off (same rule as playback).
|
||||
if (perUserMusicEnabled({ database, config })) {
|
||||
const granted = database.getGrantedMusicAccount(userId, platform);
|
||||
if (granted) {
|
||||
return { source: "granted", cookie: granted.cookie, label: granted.label, canUnlink: false };
|
||||
}
|
||||
}
|
||||
return { source: "none", cookie: null, canUnlink: false };
|
||||
};
|
||||
|
||||
router.get("/:platform/status", async (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const provider = providerFor(platform)!;
|
||||
const account = describeAccount(req.user!.id, platform);
|
||||
// Lets the member UI hide "扫码绑定" on platforms that only accept an
|
||||
// admin-assigned account (qq / kugou / bilibili today).
|
||||
const supportsQrLogin = supportsPersonalLogin(provider);
|
||||
// The member's explicit "play through the shared login" choice, so the UI
|
||||
// can render the radio without a second round-trip.
|
||||
const preferShared =
|
||||
database.getUserMusicPreference(req.user!.id, platform)?.preferShared === true;
|
||||
// The choice only exists while the admin has per-user accounts on; with it
|
||||
// off everyone is already on the shared login and the radio is meaningless.
|
||||
const featureEnabled = perUserMusicEnabled({ database, config });
|
||||
|
||||
if (!account.cookie) {
|
||||
res.json({
|
||||
linked: false,
|
||||
loggedIn: false,
|
||||
source: "none",
|
||||
canUnlink: false,
|
||||
supportsQrLogin,
|
||||
preferShared,
|
||||
featureEnabled,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (typeof provider.withCookie !== "function") {
|
||||
// Account stored but this platform cannot build a per-account view yet.
|
||||
res.json({
|
||||
linked: true,
|
||||
loggedIn: false,
|
||||
source: account.source,
|
||||
label: account.label,
|
||||
canUnlink: account.canUnlink,
|
||||
supportsQrLogin,
|
||||
preferShared,
|
||||
featureEnabled,
|
||||
unsupported: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const status = await provider.withCookie(cookie).getAuthStatus();
|
||||
res.json({ linked: true, ...status });
|
||||
} catch (err) {
|
||||
logger.warn({ err }, "Personal NetEase status check failed");
|
||||
res.json({ linked: true, loggedIn: false });
|
||||
const status = await provider.withCookie(account.cookie).getAuthStatus();
|
||||
res.json({
|
||||
linked: true,
|
||||
source: account.source,
|
||||
label: account.label,
|
||||
canUnlink: account.canUnlink,
|
||||
supportsQrLogin,
|
||||
preferShared,
|
||||
featureEnabled,
|
||||
...status,
|
||||
});
|
||||
} catch {
|
||||
logger.warn({ platform, source: account.source }, "Personal music status check failed");
|
||||
res.json({
|
||||
linked: true,
|
||||
loggedIn: false,
|
||||
source: account.source,
|
||||
label: account.label,
|
||||
canUnlink: account.canUnlink,
|
||||
supportsQrLogin,
|
||||
preferShared,
|
||||
featureEnabled,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/netease/qrcode", async (_req, res) => {
|
||||
router.post("/:platform/qrcode", async (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const provider = providerFor(platform)!;
|
||||
if (!supportsPersonalLogin(provider)) {
|
||||
// Only NetEase ships "poll and hand back the cookie" today. The other
|
||||
// platforms can still receive an admin-assigned account.
|
||||
res.status(501).json({
|
||||
error: "Personal QR login is not implemented for this platform yet",
|
||||
platform,
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
res.json(await provider.getQrCode());
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Personal NetEase QR generation failed");
|
||||
logger.error({ err, platform }, "Personal music QR generation failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/netease/qrcode/status", async (req, res) => {
|
||||
router.get("/:platform/qrcode/status", async (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const provider = providerFor(platform)!;
|
||||
if (!supportsPersonalLogin(provider)) {
|
||||
res.status(501).json({
|
||||
error: "Personal QR login is not implemented for this platform yet",
|
||||
platform,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const key = req.query.key;
|
||||
if (typeof key !== "string" || !key) {
|
||||
res.status(400).json({ error: "key is required" });
|
||||
@@ -80,15 +190,62 @@ export function createPersonalMusicRouter(
|
||||
}
|
||||
res.json({ status });
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Personal NetEase QR status check failed");
|
||||
logger.error({ err, platform }, "Personal music QR status check failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
router.delete("/netease", (req, res) => {
|
||||
database.deleteUserMusicCookie(req.user!.id, platform);
|
||||
logger.info({ userId: req.user!.id, platform }, "Personal music account unlinked");
|
||||
res.json({ ok: true });
|
||||
router.delete("/:platform", (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const userId = req.user!.id;
|
||||
// Only the member's OWN login is removed. An admin-assigned account lives
|
||||
// in a different table and must stay put — otherwise a member could revoke
|
||||
// (or accidentally destroy) what the admin handed them.
|
||||
const removed = database.deleteUserMusicCookie(userId, platform);
|
||||
if (removed) {
|
||||
logger.info({ userId, platform }, "Personal music account unlinked");
|
||||
}
|
||||
const remaining = describeAccount(userId, platform);
|
||||
res.json({
|
||||
ok: true,
|
||||
removed,
|
||||
// What playback falls back to now — the member UI shows the right hint.
|
||||
fallback: remaining.source === "granted" ? "granted" : "shared",
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Which login this member plays through.
|
||||
*
|
||||
* `preferShared: true` = ignore my own (and any assigned) account and use the
|
||||
* bot's shared login — the admin's, usually the one with a membership. It is
|
||||
* the answer to "my NetEase account has no VIP, the admin's does, and I want
|
||||
* the paid track". Nothing is deleted: flipping it back restores the personal
|
||||
* account exactly as it was.
|
||||
*/
|
||||
router.put("/:platform/preference", (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const { preferShared } = req.body ?? {};
|
||||
if (typeof preferShared !== "boolean") {
|
||||
res.status(400).json({ error: "preferShared must be a boolean" });
|
||||
return;
|
||||
}
|
||||
// With the feature off there is nothing to choose between — everything
|
||||
// already runs on the shared login. Refuse instead of storing a value that
|
||||
// would silently do nothing.
|
||||
if (!perUserMusicEnabled({ database, config })) {
|
||||
res.status(409).json({ error: "per_user_accounts_disabled" });
|
||||
return;
|
||||
}
|
||||
database.setUserMusicPreference(req.user!.id, platform, preferShared);
|
||||
logger.info({ userId: req.user!.id, platform, preferShared }, "Music account preference set");
|
||||
res.json({ platform, preferShared });
|
||||
});
|
||||
|
||||
router.get("/:platform/preference", (req, res) => {
|
||||
const platform = req.params.platform;
|
||||
const pref = database.getUserMusicPreference(req.user!.id, platform);
|
||||
res.json({ platform, preferShared: pref?.preferShared === true });
|
||||
});
|
||||
|
||||
return router;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import express from "express";
|
||||
import pino from "pino";
|
||||
import request from "supertest";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createDatabase, type BotDatabase } from "../../data/database.js";
|
||||
import { createPlayerRouter } from "./player.js";
|
||||
|
||||
describe("play history deletion", () => {
|
||||
let db: BotDatabase;
|
||||
let app: express.Express;
|
||||
let firstId: number;
|
||||
let secondId: number;
|
||||
|
||||
beforeEach(() => {
|
||||
db = createDatabase(":memory:");
|
||||
for (const botId of ["first", "second"]) {
|
||||
db.addPlayHistory({ botId, songId: "song", songName: "Example", artist: "", album: "", coverUrl: "", platform: "netease" });
|
||||
}
|
||||
firstId = db.getPlayHistory("first", 1)[0].id;
|
||||
secondId = db.getPlayHistory("second", 1)[0].id;
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
req.user = { id: "u", username: "member", role: "member", capabilities: new Set(["player.queue"]), bots: new Set(["first"]) };
|
||||
next();
|
||||
});
|
||||
const bots = { getBot: (id: string) => ({ id }) } as unknown as Parameters<typeof createPlayerRouter>[0];
|
||||
app.use("/player", createPlayerRouter(bots, pino({ level: "silent" }), db));
|
||||
});
|
||||
|
||||
afterEach(() => db.close());
|
||||
|
||||
it("rejects malformed and ambiguous selections without deleting a row", async () => {
|
||||
await request(app).delete(`/player/first/history/${firstId}x`).expect(400);
|
||||
await request(app).delete("/player/first/history").send({ ids: [firstId, "bad"] }).expect(400);
|
||||
await request(app).delete("/player/first/history").send({ all: true, ids: [firstId] }).expect(400);
|
||||
expect(db.getPlayHistory("first", 10)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps song IDs compatible and scopes deletion to the authorized bot", async () => {
|
||||
const response = await request(app).get("/player/first/history").expect(200);
|
||||
expect(response.body.history[0]).toMatchObject({ id: "song", rowId: firstId });
|
||||
await request(app).delete("/player/second/history").send({ all: true }).expect(403);
|
||||
await request(app).delete("/player/first/history").send({ ids: [firstId, firstId, secondId] }).expect(200, { deleted: 1 });
|
||||
expect(db.getPlayHistory("second", 10)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
+145
-70
@@ -1,17 +1,25 @@
|
||||
import { Router } from "express";
|
||||
import { Router, type Request } from "express";
|
||||
import type { BotInstance } from "../../bot/instance.js";
|
||||
import type { QueuedSong } from "../../audio/queue.js";
|
||||
import type { BotManager } from "../../bot/manager.js";
|
||||
import type { BotDatabase } from "../../data/database.js";
|
||||
import type { MusicProvider, Song, ArtistSongPage } from "../../music/provider.js";
|
||||
import type { MusicProvider, Song, ArtistSongPage, PlayFailure } from "../../music/provider.js";
|
||||
import { musicRequestError } from "../../music/request-error.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
import { parseCommand } from "../../bot/commands.js";
|
||||
import { requireBotAccess } from "../middleware/requirePermission.js";
|
||||
import { authorize } from "../middleware/authorize.js";
|
||||
import { supportsPersonalLogin } from "./personal-music.js";
|
||||
import { resolveProviderForRequest } from "./provider-scope.js";
|
||||
|
||||
/** Hard cap on how many tracks one "播放全部" request may queue — a safety net
|
||||
* against a pathological catalogue (and against an upstream paging bug). */
|
||||
const MAX_ARTIST_QUEUE = 500;
|
||||
const ARTIST_QUEUE_PAGE = 100;
|
||||
const MAX_HISTORY_DELETE_BATCH = 500;
|
||||
|
||||
function isHistoryRowId(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
/** Walks every page of an artist's catalogue (best-first, de-duplicated). */
|
||||
export async function collectArtistSongs(
|
||||
@@ -41,9 +49,39 @@ export function createPlayerRouter(
|
||||
neteaseProvider?: MusicProvider,
|
||||
qqProvider?: MusicProvider,
|
||||
bilibiliProvider?: MusicProvider,
|
||||
// Per-user music accounts (#164 follow-up). Omitted by unit-test routers →
|
||||
// the feature reads as off and every request uses the shared login.
|
||||
config?: { perUserMusicAccounts?: boolean },
|
||||
): Router {
|
||||
const router = Router();
|
||||
|
||||
/** Platform names the bot resolves as-is; anything else means NetEase. */
|
||||
const PASSTHROUGH = new Set(["bilibili", "qq", "youtube", "local", "kugou", "jellyfin"]);
|
||||
const sharedProviderFor = (bot: any, platform: unknown): MusicProvider =>
|
||||
bot.getProviderFor(PASSTHROUGH.has(platform as string) ? platform : "netease");
|
||||
|
||||
/**
|
||||
* The provider this request should read from. With per-user accounts enabled,
|
||||
* a caller who linked their own account gets a view built from THEIR cookie;
|
||||
* otherwise the bot's shared provider comes back untouched.
|
||||
*/
|
||||
const scopedProvider = (req: Request, bot: any, platform: unknown): MusicProvider => {
|
||||
const shared = sharedProviderFor(bot, platform);
|
||||
return resolveProviderForRequest(req, shared.platform, shared, { database, config });
|
||||
};
|
||||
|
||||
/**
|
||||
* Personal FM predates the admin toggle (#164), so a linked account has always
|
||||
* driven it. `alwaysPersonal` keeps that guarantee while the toggle is off;
|
||||
* with the toggle on, FM simply inherits the same account as everything else.
|
||||
*/
|
||||
const fmProvider = (req: Pick<Request, "user">, bot: any, platform: unknown): MusicProvider => {
|
||||
const shared = sharedProviderFor(bot, platform);
|
||||
return resolveProviderForRequest(req, shared.platform, shared, { database, config }, {
|
||||
alwaysPersonal: true,
|
||||
});
|
||||
};
|
||||
|
||||
// Access check runs BEFORE the existence/resolver check so a member who is
|
||||
// not allowed a bot always gets a uniform 403 — whether or not the bot
|
||||
// exists — instead of a 404 that would leak which bot IDs are real.
|
||||
@@ -61,6 +99,21 @@ export function createPlayerRouter(
|
||||
next();
|
||||
});
|
||||
|
||||
const whyUnplayable = (song: { name?: string; id?: string }, reason?: string): string => {
|
||||
const label = song.name || song.id || "这首歌";
|
||||
return reason ? `无法播放「${label}」:${reason}` : `无法播放「${label}」`;
|
||||
};
|
||||
|
||||
async function startCollection(bot: BotInstance, first: QueuedSong | null) {
|
||||
let failure: PlayFailure | undefined;
|
||||
const capture = (reason: PlayFailure) => { failure = reason; };
|
||||
let started = first ? await bot.resolveAndPlay(first, capture) : false;
|
||||
if (first && !started && failure?.code !== "risk_control" && bot.getQueueManager().current() === first) {
|
||||
started = await bot.playNext(20, capture);
|
||||
}
|
||||
return { started, reason: failure?.message };
|
||||
}
|
||||
|
||||
/** Map API platform string to the corresponding command flag. */
|
||||
const platformFlag = (platform: unknown): string => {
|
||||
if (platform === "bilibili") return "-b";
|
||||
@@ -151,20 +204,11 @@ export function createPlayerRouter(
|
||||
rejectDisabledLocalAudio(res);
|
||||
return;
|
||||
}
|
||||
let provider = bot.getProviderFor(
|
||||
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
|
||||
? platform
|
||||
: "netease"
|
||||
);
|
||||
// A signed-in user who linked their own NetEase account gets FM from
|
||||
// THEIR taste, not the bot's shared login (#164). Songs still resolve
|
||||
// through the shared provider when played.
|
||||
const user = (req as any).user;
|
||||
if (provider.platform === "netease" && user && user.role !== "guest" && database) {
|
||||
const cookie = database.getUserMusicCookie(user.id, "netease");
|
||||
if (cookie && supportsPersonalLogin(provider)) provider = provider.withCookie(cookie);
|
||||
}
|
||||
const message = await bot.startFm(provider, requesterName(req));
|
||||
// Resolve FM recommendations with the caller's account. The bot resolves
|
||||
// each queued track's playback URL using the shared account.
|
||||
const scope = { user: req.user };
|
||||
const resolveFmProvider = () => fmProvider(scope, bot, platform);
|
||||
const message = await bot.startFm(resolveFmProvider(), requesterName(req), resolveFmProvider);
|
||||
res.json({
|
||||
ok:
|
||||
!message.startsWith("No FM songs") &&
|
||||
@@ -173,7 +217,7 @@ export function createPlayerRouter(
|
||||
message,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -335,11 +379,7 @@ export function createPlayerRouter(
|
||||
}
|
||||
// Use the bot's own provider lookup — it already knows about youtube,
|
||||
// which the router's constructor params did not.
|
||||
const provider = bot.getProviderFor(
|
||||
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
|
||||
? platform
|
||||
: "netease"
|
||||
);
|
||||
const provider = scopedProvider(req, bot, platform);
|
||||
|
||||
// Stop current playback
|
||||
bot.getPlayer().stop();
|
||||
@@ -370,7 +410,7 @@ export function createPlayerRouter(
|
||||
// the sequential retry path, which still has a chance.
|
||||
}
|
||||
if (queueable.length === 0) {
|
||||
res.json({ ok: false, message: `歌单 ${totalCount} 首歌曲均无版权可播放(区域/版权限制)` });
|
||||
res.json({ ok: false, message: `歌单 ${totalCount} 首歌曲均无法播放` });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -399,23 +439,21 @@ export function createPlayerRouter(
|
||||
// retry-skip behavior. Use a higher retry budget than the default
|
||||
// trackEnd auto-advance because user-initiated playlist plays
|
||||
// commonly have long contiguous runs of unplayable songs.
|
||||
let started = first ? await bot.resolveAndPlay(first) : false;
|
||||
if (first && !started) {
|
||||
started = await bot.playNext(20);
|
||||
}
|
||||
const { started, reason } = await startCollection(bot, first);
|
||||
|
||||
const playing = queue.current();
|
||||
const loadedMsg = queueable.length < totalCount
|
||||
? `已加载 ${queueable.length}/${totalCount} 首(其余区域/版权限制)`
|
||||
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
|
||||
: `已加载 ${queueable.length} 首`;
|
||||
if (started && playing) {
|
||||
res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` });
|
||||
} else {
|
||||
res.json({ ok: false, message: `${loadedMsg},但无法开始播放。` });
|
||||
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Play playlist failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "Play playlist failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -428,11 +466,7 @@ export function createPlayerRouter(
|
||||
rejectDisabledLocalAudio(res);
|
||||
return;
|
||||
}
|
||||
const provider = bot.getProviderFor(
|
||||
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
|
||||
? platform
|
||||
: "netease"
|
||||
);
|
||||
const provider = scopedProvider(req, bot, platform);
|
||||
|
||||
// Stop current playback
|
||||
bot.getPlayer().stop();
|
||||
@@ -456,7 +490,7 @@ export function createPlayerRouter(
|
||||
}
|
||||
}
|
||||
if (queueable.length === 0) {
|
||||
res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无版权可播放(区域/版权限制)` });
|
||||
res.json({ ok: false, message: `专辑 ${totalCount} 首歌曲均无法播放` });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -477,23 +511,21 @@ export function createPlayerRouter(
|
||||
first = queue.play();
|
||||
}
|
||||
|
||||
let started = first ? await bot.resolveAndPlay(first) : false;
|
||||
if (first && !started) {
|
||||
started = await bot.playNext(20);
|
||||
}
|
||||
const { started, reason } = await startCollection(bot, first);
|
||||
|
||||
const playing = queue.current();
|
||||
const loadedMsg = queueable.length < totalCount
|
||||
? `已加载 ${queueable.length}/${totalCount} 首(其余区域/版权限制)`
|
||||
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
|
||||
: `已加载 ${queueable.length} 首`;
|
||||
if (started && playing) {
|
||||
res.json({ ok: true, message: `${loadedMsg},正在播放:${playing.name}` });
|
||||
} else {
|
||||
res.json({ ok: false, message: `${loadedMsg},但无法开始播放。` });
|
||||
res.json({ ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` });
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error({ err }, "play-album failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "play-album failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -513,11 +545,7 @@ export function createPlayerRouter(
|
||||
rejectDisabledLocalAudio(res);
|
||||
return;
|
||||
}
|
||||
const provider = bot.getProviderFor(
|
||||
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
|
||||
? platform
|
||||
: "netease"
|
||||
);
|
||||
const provider = scopedProvider(req, bot, platform);
|
||||
if (typeof provider.getArtistSongs !== "function") {
|
||||
res.status(501).json({ error: "Not supported by this provider" });
|
||||
return;
|
||||
@@ -546,7 +574,7 @@ export function createPlayerRouter(
|
||||
}
|
||||
}
|
||||
if (queueable.length === 0) {
|
||||
res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无版权可播放(区域/版权限制)` });
|
||||
res.json({ ok: false, message: `歌手 ${totalCount} 首歌曲均无法播放` });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -572,21 +600,21 @@ export function createPlayerRouter(
|
||||
first = queue.play();
|
||||
}
|
||||
|
||||
let started = first ? await bot.resolveAndPlay(first) : false;
|
||||
if (first && !started) started = await bot.playNext(20);
|
||||
const { started, reason } = await startCollection(bot, first);
|
||||
|
||||
const playing = queue.current();
|
||||
const loadedMsg = queueable.length < totalCount
|
||||
? `已加载 ${queueable.length}/${totalCount} 首(其余区域/版权限制)`
|
||||
? `已加载 ${queueable.length}/${totalCount} 首(其余无法播放)`
|
||||
: `已加载 ${queueable.length} 首`;
|
||||
return started && playing
|
||||
? { ok: true, message: `${loadedMsg},正在播放:${playing.name}` }
|
||||
: { ok: false, message: `${loadedMsg},但无法开始播放。` };
|
||||
: { ok: false, message: `${loadedMsg},但无法开始播放${reason ? `:${reason}` : "。"}` };
|
||||
});
|
||||
res.json(body);
|
||||
} catch (err) {
|
||||
logger.error({ err }, "play-artist failed");
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
const error = musicRequestError(err);
|
||||
logger.error({ err: error }, "play-artist failed");
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -611,10 +639,11 @@ export function createPlayerRouter(
|
||||
// clear branch — do NOT also call it here, or it would delete retained
|
||||
// local uploads in keep-queue mode.
|
||||
const body = await bot.runExclusive(async () => {
|
||||
const ok = await bot.playSingleSong({ ...song }, requesterName(req));
|
||||
let reason: string | undefined;
|
||||
const ok = await bot.playSingleSong({ ...song }, requesterName(req), (failure: PlayFailure) => { reason = failure.message; });
|
||||
return ok
|
||||
? { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` }
|
||||
: { ok: false, message: `无法播放「${song.name || song.id}」(区域/版权限制)` };
|
||||
: { ok: false, message: whyUnplayable(song, reason) };
|
||||
});
|
||||
res.json(body);
|
||||
} catch (err) {
|
||||
@@ -654,9 +683,10 @@ export function createPlayerRouter(
|
||||
// Promote the just-added song to current and start it.
|
||||
queue.playAt(insertedAt);
|
||||
bot.getPlayer().resetFailures();
|
||||
const ok = await bot.resolveAndPlay(queue.current()!);
|
||||
let reason: string | undefined;
|
||||
const ok = await bot.resolveAndPlay(queue.current()!, (failure: PlayFailure) => { reason = failure.message; });
|
||||
if (!ok) {
|
||||
return { ok: false, message: `无法播放「${song.name || song.id}」(区域/版权限制)` };
|
||||
return { ok: false, message: whyUnplayable(song, reason) };
|
||||
}
|
||||
return { ok: true, message: `正在播放:${song.name || 'Unknown'} - ${song.artist || 'Unknown'}` };
|
||||
}
|
||||
@@ -693,9 +723,10 @@ export function createPlayerRouter(
|
||||
queue.addNext({ ...song, requestedBy: requesterName(req) });
|
||||
queue.playAt(insertedAt);
|
||||
bot.getPlayer().resetFailures();
|
||||
const ok = await bot.resolveAndPlay(queue.current()!);
|
||||
let reason: string | undefined;
|
||||
const ok = await bot.resolveAndPlay(queue.current()!, (failure: PlayFailure) => { reason = failure.message; });
|
||||
if (!ok) {
|
||||
return { ok: false, message: `无法播放「${song.name || song.id}」(区域/版权限制)` };
|
||||
return { ok: false, message: whyUnplayable(song, reason) };
|
||||
}
|
||||
return { ok: true, message: `正在播放:${song.name || "Unknown"} - ${song.artist || "Unknown"}` };
|
||||
});
|
||||
@@ -749,11 +780,7 @@ export function createPlayerRouter(
|
||||
rejectDisabledLocalAudio(res);
|
||||
return;
|
||||
}
|
||||
const provider = bot.getProviderFor(
|
||||
platform === "bilibili" || platform === "qq" || platform === "youtube" || platform === "local" || platform === "kugou" || platform === "jellyfin"
|
||||
? platform
|
||||
: "netease"
|
||||
);
|
||||
const provider = scopedProvider(req, bot, platform);
|
||||
|
||||
const song = await provider.getSongDetail(songId);
|
||||
if (!song) {
|
||||
@@ -772,7 +799,7 @@ export function createPlayerRouter(
|
||||
|
||||
res.json({ message: `Added: ${song.name} - ${song.artist} (position ${queue.size()})` });
|
||||
} catch (err) {
|
||||
res.status(500).json({ error: (err as Error).message });
|
||||
res.status(500).json({ error: musicRequestError(err).message });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -805,6 +832,9 @@ export function createPlayerRouter(
|
||||
const limit = parseInt(req.query.limit as string) || 50;
|
||||
const records = database.getPlayHistory(req.params.botId, limit);
|
||||
const history = records.map((r) => ({
|
||||
// rowId is the history row primary key — needed to delete a single record.
|
||||
// `id` stays the platform song id so existing players keep working.
|
||||
rowId: r.id,
|
||||
id: r.songId,
|
||||
name: r.songName,
|
||||
artist: r.artist,
|
||||
@@ -818,5 +848,50 @@ export function createPlayerRouter(
|
||||
res.json({ history });
|
||||
});
|
||||
|
||||
// Delete one history record: /:botId/history/:rowId
|
||||
router.delete(
|
||||
"/:botId/history/:rowId",
|
||||
authorize({ capability: "player.queue", guestFlag: "removeClear" }),
|
||||
(req, res) => {
|
||||
if (!database) {
|
||||
res.status(404).json({ error: "history unavailable" });
|
||||
return;
|
||||
}
|
||||
const rowId = Number(req.params.rowId);
|
||||
if (!/^\d+$/.test(req.params.rowId) || !isHistoryRowId(rowId)) {
|
||||
res.status(400).json({ error: "invalid rowId" });
|
||||
return;
|
||||
}
|
||||
const deleted = database.deletePlayHistory(req.params.botId, [rowId]);
|
||||
res.json({ deleted });
|
||||
}
|
||||
);
|
||||
|
||||
// Batch delete / clear all: body { ids: number[] } or { all: true }
|
||||
router.delete(
|
||||
"/:botId/history",
|
||||
authorize({ capability: "player.queue", guestFlag: "removeClear" }),
|
||||
(req, res) => {
|
||||
if (!database) {
|
||||
res.status(404).json({ error: "history unavailable" });
|
||||
return;
|
||||
}
|
||||
const body = (req.body ?? {}) as { ids?: unknown; all?: unknown };
|
||||
if (body.all === true && body.ids === undefined) {
|
||||
const deleted = database.clearPlayHistory(req.params.botId);
|
||||
res.json({ deleted });
|
||||
return;
|
||||
}
|
||||
const { ids } = body;
|
||||
if (body.all !== undefined || !Array.isArray(ids) || ids.length === 0 ||
|
||||
ids.length > MAX_HISTORY_DELETE_BATCH || !ids.every(isHistoryRowId)) {
|
||||
res.status(400).json({ error: "Provide 1 to 500 history IDs or all:true" });
|
||||
return;
|
||||
}
|
||||
const deleted = database.deletePlayHistory(req.params.botId, ids);
|
||||
res.json({ deleted });
|
||||
}
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Request } from "express";
|
||||
import type { BotDatabase, GrantedMusicAccount } from "../../data/database.js";
|
||||
import type { MusicProvider } from "../../music/provider.js";
|
||||
import {
|
||||
grantedAccountFor,
|
||||
perUserMusicEnabled,
|
||||
personalCookieFor,
|
||||
resolveMusicCookie,
|
||||
resolveProviderForRequest,
|
||||
} from "./provider-scope.js";
|
||||
|
||||
/** Minimal provider stand-in: only `platform` and an optional `withCookie` are
|
||||
* consulted by the scope resolver. */
|
||||
function fakeProvider(opts: {
|
||||
platform?: string;
|
||||
withCookie?: (cookie: string) => MusicProvider;
|
||||
} = {}): MusicProvider {
|
||||
const p: Partial<MusicProvider> = { platform: (opts.platform ?? "netease") as MusicProvider["platform"] };
|
||||
if (opts.withCookie) p.withCookie = opts.withCookie;
|
||||
return p as MusicProvider;
|
||||
}
|
||||
|
||||
/**
|
||||
* `own` is the member's self-linked cookie, `granted` an admin assignment.
|
||||
* Both default to null so a test only states the state it cares about.
|
||||
*/
|
||||
function fakeDb(
|
||||
own: string | null,
|
||||
granted: GrantedMusicAccount | null = null,
|
||||
preferShared = false,
|
||||
): BotDatabase {
|
||||
return {
|
||||
getUserMusicCookie: () => own,
|
||||
getGrantedMusicAccount: () => granted,
|
||||
getUserMusicPreference: () =>
|
||||
preferShared ? { preferShared: true } : null,
|
||||
} as unknown as BotDatabase;
|
||||
}
|
||||
|
||||
function fakeReq(user?: { id: string; role: string }): Request {
|
||||
return { user } as unknown as Request;
|
||||
}
|
||||
|
||||
const GRANTED: GrantedMusicAccount = {
|
||||
accountId: "acc-1",
|
||||
label: "网易云-主号",
|
||||
cookie: "MUSIC_U=shared-with-member",
|
||||
};
|
||||
|
||||
describe("provider-scope", () => {
|
||||
it("is off unless config explicitly enables it", () => {
|
||||
expect(perUserMusicEnabled({})).toBe(false);
|
||||
expect(perUserMusicEnabled({ config: {} })).toBe(false);
|
||||
expect(perUserMusicEnabled({ config: { perUserMusicAccounts: false } })).toBe(false);
|
||||
expect(perUserMusicEnabled({ config: { perUserMusicAccounts: true } })).toBe(true);
|
||||
});
|
||||
|
||||
it("returns the shared provider when the feature is off", () => {
|
||||
const shared = fakeProvider({ withCookie: () => fakeProvider() });
|
||||
const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, {
|
||||
database: fakeDb("MUSIC_U=abc"),
|
||||
config: { perUserMusicAccounts: false },
|
||||
});
|
||||
expect(scoped).toBe(shared);
|
||||
});
|
||||
|
||||
it("returns the shared provider for guests even with a linked cookie", () => {
|
||||
const shared = fakeProvider({ withCookie: () => fakeProvider() });
|
||||
const scoped = resolveProviderForRequest(fakeReq({ id: "g1", role: "guest" }), "netease", shared, {
|
||||
database: fakeDb("MUSIC_U=abc"),
|
||||
config: { perUserMusicAccounts: true },
|
||||
});
|
||||
expect(scoped).toBe(shared);
|
||||
});
|
||||
|
||||
it("falls back to the shared provider when the user has no linked cookie", () => {
|
||||
const shared = fakeProvider({ withCookie: () => fakeProvider() });
|
||||
const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, {
|
||||
database: fakeDb(null),
|
||||
config: { perUserMusicAccounts: true },
|
||||
});
|
||||
expect(scoped).toBe(shared);
|
||||
});
|
||||
|
||||
it("falls back to the shared provider when the source has no per-account login", () => {
|
||||
const shared = fakeProvider({ platform: "local" });
|
||||
const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "local", shared, {
|
||||
database: fakeDb("cookie"),
|
||||
config: { perUserMusicAccounts: true },
|
||||
});
|
||||
expect(scoped).toBe(shared);
|
||||
});
|
||||
|
||||
it("returns an account-scoped view when enabled, member, and linked", () => {
|
||||
const personal = fakeProvider();
|
||||
let seen = "";
|
||||
const shared = fakeProvider({
|
||||
withCookie: (cookie) => {
|
||||
seen = cookie;
|
||||
return personal;
|
||||
},
|
||||
});
|
||||
const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, {
|
||||
database: fakeDb("MUSIC_U=abc"),
|
||||
config: { perUserMusicAccounts: true },
|
||||
});
|
||||
expect(scoped).toBe(personal);
|
||||
expect(seen).toBe("MUSIC_U=abc");
|
||||
});
|
||||
|
||||
it("degrades to the shared provider when withCookie throws", () => {
|
||||
const shared = fakeProvider({
|
||||
withCookie: () => {
|
||||
throw new Error("bad cookie");
|
||||
},
|
||||
});
|
||||
const scoped = resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, {
|
||||
database: fakeDb("broken"),
|
||||
config: { perUserMusicAccounts: true },
|
||||
});
|
||||
expect(scoped).toBe(shared);
|
||||
});
|
||||
|
||||
it("treats a blank stored cookie as unlinked", () => {
|
||||
expect(
|
||||
personalCookieFor(fakeReq({ id: "u1", role: "member" }), "netease", {
|
||||
database: fakeDb(" "),
|
||||
config: { perUserMusicAccounts: true },
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores requests with no authenticated user", () => {
|
||||
const shared = fakeProvider({ withCookie: () => fakeProvider() });
|
||||
expect(
|
||||
resolveProviderForRequest(undefined, "netease", shared, {
|
||||
database: fakeDb("MUSIC_U=abc"),
|
||||
config: { perUserMusicAccounts: true },
|
||||
}),
|
||||
).toBe(shared);
|
||||
});
|
||||
|
||||
// Personal FM shipped before the admin toggle existed (#164). A linked account
|
||||
// has always driven it, so `alwaysPersonal` must keep working with the flag off
|
||||
// — otherwise turning the feature off would silently regress that release.
|
||||
it("still uses the linked account for personal FM while the toggle is off", () => {
|
||||
const personal = fakeProvider();
|
||||
const shared = fakeProvider({ withCookie: () => personal });
|
||||
const scoped = resolveProviderForRequest(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
shared,
|
||||
{ database: fakeDb("MUSIC_U=abc"), config: { perUserMusicAccounts: false } },
|
||||
{ alwaysPersonal: true },
|
||||
);
|
||||
expect(scoped).toBe(personal);
|
||||
});
|
||||
|
||||
it("keeps guests on the shared provider even for personal FM", () => {
|
||||
const shared = fakeProvider({ withCookie: () => fakeProvider() });
|
||||
const scoped = resolveProviderForRequest(
|
||||
fakeReq({ id: "g1", role: "guest" }),
|
||||
"netease",
|
||||
shared,
|
||||
{ database: fakeDb("MUSIC_U=abc"), config: { perUserMusicAccounts: true } },
|
||||
{ alwaysPersonal: true },
|
||||
);
|
||||
expect(scoped).toBe(shared);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Admin-assigned accounts (#164 follow-up)
|
||||
// ---------------------------------------------------------------------
|
||||
describe("admin-assigned accounts", () => {
|
||||
it("resolves an assigned account when the member linked nothing themselves", () => {
|
||||
const assigned = fakeProvider();
|
||||
let seen = "";
|
||||
const shared = fakeProvider({
|
||||
withCookie: (cookie) => {
|
||||
seen = cookie;
|
||||
return assigned;
|
||||
},
|
||||
});
|
||||
const scoped = resolveProviderForRequest(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
shared,
|
||||
{ database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: true } },
|
||||
);
|
||||
expect(scoped).toBe(assigned);
|
||||
expect(seen).toBe(GRANTED.cookie);
|
||||
});
|
||||
|
||||
// Own-beats-assigned: linking your own account must never be silently
|
||||
// overridden by whatever the admin handed out earlier.
|
||||
it("prefers the member's own login over an assigned one", () => {
|
||||
const ownView = fakeProvider();
|
||||
const grantedView = fakeProvider();
|
||||
let seen = "";
|
||||
const shared = fakeProvider({
|
||||
withCookie: (cookie) => {
|
||||
seen = cookie;
|
||||
return cookie === "MUSIC_U=own" ? ownView : grantedView;
|
||||
},
|
||||
});
|
||||
const scoped = resolveProviderForRequest(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
shared,
|
||||
{ database: fakeDb("MUSIC_U=own", GRANTED), config: { perUserMusicAccounts: true } },
|
||||
);
|
||||
expect(scoped).toBe(ownView);
|
||||
expect(seen).toBe("MUSIC_U=own");
|
||||
});
|
||||
|
||||
// An assignment only exists because the admin turned the feature on, so it
|
||||
// must stop applying the moment they turn it off — otherwise "disable"
|
||||
// would leave members reading the admin's account.
|
||||
it("ignores assignments while the toggle is off", () => {
|
||||
const shared = fakeProvider({ withCookie: () => fakeProvider() });
|
||||
expect(
|
||||
grantedAccountFor(fakeReq({ id: "u1", role: "member" }), "netease", {
|
||||
database: fakeDb(null, GRANTED),
|
||||
config: { perUserMusicAccounts: false },
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
resolveProviderForRequest(fakeReq({ id: "u1", role: "member" }), "netease", shared, {
|
||||
database: fakeDb(null, GRANTED),
|
||||
config: { perUserMusicAccounts: false },
|
||||
}),
|
||||
).toBe(shared);
|
||||
});
|
||||
|
||||
it("never hands an assignment to a guest", () => {
|
||||
expect(
|
||||
grantedAccountFor(fakeReq({ id: "guest", role: "guest" }), "netease", {
|
||||
database: fakeDb(null, GRANTED),
|
||||
config: { perUserMusicAccounts: true },
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("reports the source and label so the UI can say 由管理员分配", () => {
|
||||
const resolved = resolveMusicCookie(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
{ database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: true } },
|
||||
);
|
||||
expect(resolved).toEqual({
|
||||
source: "granted",
|
||||
cookie: GRANTED.cookie,
|
||||
label: "网易云-主号",
|
||||
accountId: "acc-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports source=personal for a self-linked account", () => {
|
||||
const resolved = resolveMusicCookie(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
{ database: fakeDb("MUSIC_U=own", GRANTED), config: { perUserMusicAccounts: true } },
|
||||
);
|
||||
expect(resolved).toEqual({ source: "personal", cookie: "MUSIC_U=own" });
|
||||
});
|
||||
|
||||
it("returns null when neither source applies", () => {
|
||||
expect(
|
||||
resolveMusicCookie(fakeReq({ id: "u1", role: "member" }), "netease", {
|
||||
database: fakeDb(null, null),
|
||||
config: { perUserMusicAccounts: true },
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("degrades to the shared provider when an assigned cookie is broken", () => {
|
||||
const shared = fakeProvider({
|
||||
withCookie: () => {
|
||||
throw new Error("bad assigned cookie");
|
||||
},
|
||||
});
|
||||
const scoped = resolveProviderForRequest(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
shared,
|
||||
{ database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: true } },
|
||||
);
|
||||
expect(scoped).toBe(shared);
|
||||
});
|
||||
|
||||
// Personal FM keeps the #164 guarantee for the member's OWN login; an
|
||||
// assignment is not a #164 artefact and must not ride along.
|
||||
it("does not use an assignment for personal FM while the toggle is off", () => {
|
||||
const shared = fakeProvider({ withCookie: () => fakeProvider() });
|
||||
const scoped = resolveProviderForRequest(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
shared,
|
||||
{ database: fakeDb(null, GRANTED), config: { perUserMusicAccounts: false } },
|
||||
{ alwaysPersonal: true },
|
||||
);
|
||||
expect(scoped).toBe(shared);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// "Play through the shared account" preference
|
||||
//
|
||||
// The real case: the member's own NetEase login has no VIP, the admin's does.
|
||||
// Switching to shared must override BOTH their own link and any assignment —
|
||||
// it is an explicit instruction, not a fallback.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("provider-scope — shared-account preference", () => {
|
||||
it("ignores the member's own cookie when they chose the shared login", () => {
|
||||
const resolved = resolveMusicCookie(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
{
|
||||
database: fakeDb("MUSIC_U=mine", null, true),
|
||||
config: { perUserMusicAccounts: true },
|
||||
},
|
||||
);
|
||||
expect(resolved).toBeNull();
|
||||
});
|
||||
|
||||
it("also overrides an admin assignment", () => {
|
||||
const resolved = resolveMusicCookie(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
{
|
||||
database: fakeDb(null, GRANTED, true),
|
||||
config: { perUserMusicAccounts: true },
|
||||
},
|
||||
);
|
||||
expect(resolved).toBeNull();
|
||||
});
|
||||
|
||||
it("outranks alwaysPersonal, so personal FM follows the choice too", () => {
|
||||
const resolved = resolveMusicCookie(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
{
|
||||
database: fakeDb("MUSIC_U=mine", null, true),
|
||||
config: { perUserMusicAccounts: true },
|
||||
},
|
||||
{ alwaysPersonal: true },
|
||||
);
|
||||
expect(resolved).toBeNull();
|
||||
});
|
||||
|
||||
it("hands the untouched shared provider back", () => {
|
||||
const shared = fakeProvider({ withCookie: () => fakeProvider() });
|
||||
const scoped = resolveProviderForRequest(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
shared,
|
||||
{
|
||||
database: fakeDb("MUSIC_U=mine", null, true),
|
||||
config: { perUserMusicAccounts: true },
|
||||
},
|
||||
);
|
||||
expect(scoped).toBe(shared);
|
||||
});
|
||||
|
||||
it("is ignored while the admin has the feature off", () => {
|
||||
const shared = fakeProvider({ withCookie: () => fakeProvider() });
|
||||
const scoped = resolveProviderForRequest(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
shared,
|
||||
{
|
||||
database: fakeDb("MUSIC_U=mine", null, true),
|
||||
config: { perUserMusicAccounts: false },
|
||||
},
|
||||
);
|
||||
expect(scoped).toBe(shared);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Automatic playback fallback
|
||||
//
|
||||
// Same scenario, minus an explicit choice: keep the member's own account for
|
||||
// search / playlists, but when THIS track cannot be resolved on it, try the
|
||||
// shared login instead of greying the track out.
|
||||
// ---------------------------------------------------------------------------
|
||||
describe("provider-scope — playback falls back to the shared login", () => {
|
||||
function view(
|
||||
getSongUrl: (songId: string, quality?: string) => Promise<{ url: string } | null>,
|
||||
): MusicProvider {
|
||||
return { platform: "netease", getSongUrl } as unknown as MusicProvider;
|
||||
}
|
||||
|
||||
function scopeWith(
|
||||
personal: MusicProvider,
|
||||
sharedUrl: () => Promise<{ url: string } | null>,
|
||||
options: { fallbackToShared?: boolean } = {},
|
||||
) {
|
||||
const shared = view(sharedUrl);
|
||||
(shared as Partial<MusicProvider>).withCookie = () => personal;
|
||||
return resolveProviderForRequest(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
shared,
|
||||
{
|
||||
database: fakeDb("MUSIC_U=mine"),
|
||||
config: { perUserMusicAccounts: true },
|
||||
},
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
it("uses the shared login when the personal account returns no url", async () => {
|
||||
const scoped = scopeWith(view(async () => null), async () => ({ url: "https://shared/x.mp3" }));
|
||||
expect((await scoped.getSongUrl("1"))?.url).toBe("https://shared/x.mp3");
|
||||
});
|
||||
|
||||
it("uses the shared login when the personal account throws", async () => {
|
||||
const scoped = scopeWith(
|
||||
view(async () => {
|
||||
throw new Error("no membership");
|
||||
}),
|
||||
async () => ({ url: "https://shared/x.mp3" }),
|
||||
);
|
||||
expect((await scoped.getSongUrl("1"))?.url).toBe("https://shared/x.mp3");
|
||||
});
|
||||
|
||||
it("keeps the personal result when it works", async () => {
|
||||
const scoped = scopeWith(
|
||||
view(async () => ({ url: "https://mine/x.mp3" })),
|
||||
async () => ({ url: "https://shared/x.mp3" }),
|
||||
);
|
||||
expect((await scoped.getSongUrl("1"))?.url).toBe("https://mine/x.mp3");
|
||||
});
|
||||
|
||||
it("can be switched off so playback stays on the member's account", async () => {
|
||||
const scoped = scopeWith(
|
||||
view(async () => null),
|
||||
async () => ({ url: "https://shared/x.mp3" }),
|
||||
{ fallbackToShared: false },
|
||||
);
|
||||
expect(await scoped.getSongUrl("1")).toBeNull();
|
||||
});
|
||||
|
||||
it("leaves the shared instance itself untouched", async () => {
|
||||
const shared = view(async () => ({ url: "https://shared/x.mp3" }));
|
||||
(shared as Partial<MusicProvider>).withCookie = () => view(async () => null);
|
||||
resolveProviderForRequest(
|
||||
fakeReq({ id: "u1", role: "member" }),
|
||||
"netease",
|
||||
shared,
|
||||
{ database: fakeDb("MUSIC_U=mine"), config: { perUserMusicAccounts: true } },
|
||||
);
|
||||
// Calling the shared provider directly must still hit its own implementation.
|
||||
expect((await shared.getSongUrl("1"))?.url).toBe("https://shared/x.mp3");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,225 @@
|
||||
import type { Request } from "express";
|
||||
import type { BotDatabase, GrantedMusicAccount } from "../../data/database.js";
|
||||
import type { MusicProvider } from "../../music/provider.js";
|
||||
|
||||
/**
|
||||
* Resolves which music provider a WEB request should read from (#164 follow-up).
|
||||
*
|
||||
* The bot keeps one shared login per platform (data/cookies/<platform>.json).
|
||||
* Before this module, a web user could only replace the SHARED login's taste for
|
||||
* their own private FM — every search, playlist and playback URL still came from
|
||||
* the admin's account, so members saw the admin's library.
|
||||
*
|
||||
* With `perUserMusicAccounts` enabled, the resolution order is:
|
||||
*
|
||||
* 1. the caller's OWN linked account (`user_music_cookies`, scanned by them)
|
||||
* 2. an account an admin ASSIGNED (`music_account_grants`, admin-owned)
|
||||
* 3. the bot's shared login (always the fallback)
|
||||
*
|
||||
* Own-beats-assigned is deliberate: someone who linked their own account keeps
|
||||
* it even if an admin later hands them a pool account, and unlinking on the
|
||||
* member side can never revoke an admin's assignment (different table).
|
||||
*
|
||||
* Everything falls back to the shared instance when:
|
||||
* - the admin left the feature off (the default — zero behaviour change),
|
||||
* - the caller is a guest (guests share one anonymous identity and cannot link
|
||||
* an account; /api/me/music already rejects them),
|
||||
* - the caller has no linked and no assigned account for that platform,
|
||||
* - the assigned account was disabled by the admin (instant rollback), or
|
||||
* - the platform has no per-account login implemented (`withCookie` absent).
|
||||
*
|
||||
* The cookie never reaches the browser: it is read from the database here and
|
||||
* only ever lives inside the provider view.
|
||||
*/
|
||||
export interface MusicScopeDeps {
|
||||
/** Omitted by unit-test routers → personal accounts are simply unavailable. */
|
||||
database?: BotDatabase;
|
||||
/** Omitted by unit-test routers → treated as "feature off". */
|
||||
config?: { perUserMusicAccounts?: boolean };
|
||||
}
|
||||
|
||||
interface ScopedUser {
|
||||
id?: string;
|
||||
role?: string;
|
||||
}
|
||||
|
||||
type ScopeRequest = Pick<Request, "user">;
|
||||
|
||||
/** Whether per-user music accounts are switched on for this router instance. */
|
||||
export function perUserMusicEnabled(deps: MusicScopeDeps): boolean {
|
||||
return deps.config?.perUserMusicAccounts === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The caller, when they may hold a per-user account at all. Guests never
|
||||
* qualify: they all map to one anonymous identity, so a linked or assigned
|
||||
* account would leak across every guest on the instance.
|
||||
*/
|
||||
function scopedUser(req: ScopeRequest | undefined): ScopedUser | null {
|
||||
if (!req) return null;
|
||||
const user = (req as { user?: ScopedUser }).user;
|
||||
if (!user?.id || user.role === "guest") return null;
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* The caller's own cookie for `platform`, or null when personal accounts do not
|
||||
* apply to this request.
|
||||
*
|
||||
* `alwaysPersonal` keeps the pre-existing #164 behaviour for personal FM: that
|
||||
* feature shipped BEFORE the admin toggle existed, so a linked account must keep
|
||||
* driving someone's private FM even while the toggle is off. Turning the toggle
|
||||
* on only widens the scope to search/playlists/playback URLs.
|
||||
*/
|
||||
export function personalCookieFor(
|
||||
req: ScopeRequest | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
alwaysPersonal = false,
|
||||
): string | null {
|
||||
if (!alwaysPersonal && !perUserMusicEnabled(deps)) return null;
|
||||
const user = scopedUser(req);
|
||||
if (!user || !deps.database) return null;
|
||||
const cookie = deps.database.getUserMusicCookie(user.id!, platform);
|
||||
return cookie && cookie.trim() ? cookie : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin-assigned account for this caller, or null.
|
||||
*
|
||||
* Unlike `personalCookieFor` this has NO `alwaysPersonal` escape hatch: an
|
||||
* assignment only exists because the admin turned the feature on, so turning it
|
||||
* off must hand everyone back to the shared login immediately. Doing otherwise
|
||||
* would leave members reading an admin's account after the admin "disabled"
|
||||
* the feature.
|
||||
*/
|
||||
export function grantedAccountFor(
|
||||
req: ScopeRequest | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
): GrantedMusicAccount | null {
|
||||
if (!perUserMusicEnabled(deps)) return null;
|
||||
const user = scopedUser(req);
|
||||
if (!user || !deps.database) return null;
|
||||
return deps.database.getGrantedMusicAccount(user.id!, platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the member explicitly asked to play through the shared login.
|
||||
*
|
||||
* This exists for one concrete case: their own account has no membership, the
|
||||
* admin's does, and they would rather hear the paid tracks than their own
|
||||
* recommendations. Choosing it overrides BOTH their own link and any admin
|
||||
* assignment — it is an explicit instruction, not a fallback.
|
||||
*/
|
||||
export function preferSharedFor(
|
||||
req: ScopeRequest | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
): boolean {
|
||||
if (!perUserMusicEnabled(deps)) return false;
|
||||
const user = scopedUser(req);
|
||||
if (!user || !deps.database) return false;
|
||||
return deps.database.getUserMusicPreference(user.id!, platform)?.preferShared === true;
|
||||
}
|
||||
|
||||
/** Where the cookie driving this request came from. */
|
||||
export interface ResolvedMusicCookie {
|
||||
source: "personal" | "granted";
|
||||
cookie: string;
|
||||
/** Admin-facing name of an assigned account; undefined for self-linked ones. */
|
||||
label?: string;
|
||||
/** Set for `source: "granted"` so callers can show "由管理员分配". */
|
||||
accountId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The single place that decides "which login does this request use".
|
||||
* Returns null when the shared login applies.
|
||||
*/
|
||||
export function resolveMusicCookie(
|
||||
req: ScopeRequest | undefined,
|
||||
platform: string,
|
||||
deps: MusicScopeDeps,
|
||||
options: { alwaysPersonal?: boolean } = {},
|
||||
): ResolvedMusicCookie | null {
|
||||
// An explicit "use the shared account" outranks everything, including the
|
||||
// `alwaysPersonal` escape hatch: someone who chose membership over their own
|
||||
// recommendations wants the shared login for FM too.
|
||||
if (preferSharedFor(req, platform, deps)) return null;
|
||||
const own = personalCookieFor(req, platform, deps, options.alwaysPersonal);
|
||||
if (own) return { source: "personal", cookie: own };
|
||||
const granted = grantedAccountFor(req, platform, deps);
|
||||
if (granted) {
|
||||
return {
|
||||
source: "granted",
|
||||
cookie: granted.cookie,
|
||||
label: granted.label,
|
||||
accountId: granted.accountId,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Give `view` a single-shot fallback to the shared login when its own playback
|
||||
* attempt comes up empty.
|
||||
*
|
||||
* The case this exists for: the member's own account is real but has no
|
||||
* membership, so `/song/url/v1` answers `url: null` (or 400 for the paid track)
|
||||
* while the admin's account plays it fine. Without this the member has to go
|
||||
* into settings and switch manually before every such track.
|
||||
*
|
||||
* Only `getSongUrl` is wrapped — search, playlists and FM stay on the member's
|
||||
* own account, which is the whole point of per-user logins. The wrapper keeps
|
||||
* the shared instance untouched, so nothing leaks between callers.
|
||||
*/
|
||||
function withSharedPlaybackFallback(view: MusicProvider, shared: MusicProvider): MusicProvider {
|
||||
// Guard for partial implementations (and for test doubles): without both
|
||||
// sides resolvable there is nothing to fall back to.
|
||||
if (typeof view.getSongUrl !== "function" || typeof shared.getSongUrl !== "function") {
|
||||
return view;
|
||||
}
|
||||
const ownResolve = view.getSongUrl.bind(view);
|
||||
view.getSongUrl = async (songId: string, quality?: string) => {
|
||||
try {
|
||||
const result = await ownResolve(songId, quality);
|
||||
if (result?.url) return result;
|
||||
} catch {
|
||||
// A failure on the personal side (no membership, -460, expired cookie)
|
||||
// is not a reason for this track to go grey — try the shared login.
|
||||
}
|
||||
return shared.getSongUrl(songId, quality);
|
||||
};
|
||||
return view;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap `shared` in a per-account view when the request carries a usable login;
|
||||
* otherwise return `shared` untouched.
|
||||
*
|
||||
* A provider whose `withCookie` throws (malformed/persisted cookie) degrades to
|
||||
* the shared login rather than failing the request — a bad stored cookie must
|
||||
* not break search/playback for that user.
|
||||
*/
|
||||
export function resolveProviderForRequest(
|
||||
req: ScopeRequest | undefined,
|
||||
platform: string,
|
||||
shared: MusicProvider,
|
||||
deps: MusicScopeDeps,
|
||||
options: { alwaysPersonal?: boolean; fallbackToShared?: boolean } = {},
|
||||
): MusicProvider {
|
||||
const resolved = resolveMusicCookie(req, platform, deps, options);
|
||||
if (!resolved) return shared;
|
||||
if (typeof shared.withCookie !== "function") return shared;
|
||||
let view: MusicProvider;
|
||||
try {
|
||||
view = shared.withCookie(resolved.cookie);
|
||||
} catch {
|
||||
return shared;
|
||||
}
|
||||
// On by default: the common complaint is "my account has no membership, the
|
||||
// admin's does". Set false to keep playback strictly on the member's account.
|
||||
if (options.fallbackToShared === false) return view;
|
||||
return withSharedPlaybackFallback(view, shared);
|
||||
}
|
||||
+38
-6
@@ -8,6 +8,7 @@ import type { MusicProvider } from "../music/provider.js";
|
||||
import type { BotDatabase } from "../data/database.js";
|
||||
import type { BotConfig, GuestModeConfig } from "../data/config.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { APP_VERSION } from "../version.js";
|
||||
import type { CookieStore } from "../music/auth.js";
|
||||
import type { AvatarStore } from "../data/avatars.js";
|
||||
import { createBotRouter } from "./api/bot.js";
|
||||
@@ -20,6 +21,7 @@ import { createAuditStore } from "../data/audit.js";
|
||||
import { createAuditRouter } from "./api/audit.js";
|
||||
import { createFavoritesRouter } from "./api/favorites.js";
|
||||
import { createPersonalMusicRouter } from "./api/personal-music.js";
|
||||
import { createMusicAccountsRouter } from "./api/music-accounts.js";
|
||||
import { createSavedQueuesRouter } from "./api/saved-queues.js";
|
||||
import { createSpotifyRouter } from "./api/spotify.js";
|
||||
import { createApiKeysRouter } from "./api/api-keys.js";
|
||||
@@ -115,7 +117,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
});
|
||||
|
||||
app.get("/api/health", (_req, res) => {
|
||||
res.json({ status: "ok", version: "0.1.0" });
|
||||
res.json({ status: "ok", version: APP_VERSION });
|
||||
});
|
||||
|
||||
app.get("/api/config/public-url", (_req, res) => {
|
||||
@@ -170,15 +172,16 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
);
|
||||
app.use(
|
||||
"/api/music",
|
||||
createMusicRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.localProvider, options.config, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.configPath)
|
||||
createMusicRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.localProvider, options.config, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.configPath, options.database)
|
||||
);
|
||||
app.use("/api/player", createPlayerRouter(
|
||||
options.botManager, logger, options.database,
|
||||
options.neteaseProvider, options.qqProvider, options.bilibiliProvider,
|
||||
options.config,
|
||||
));
|
||||
app.use(
|
||||
"/api/auth",
|
||||
createAuthRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.cookieStore, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.config)
|
||||
createAuthRouter(options.neteaseProvider, options.qqProvider, options.bilibiliProvider, logger, options.cookieStore, options.kugouProvider, options.spotifyProvider, options.jellyfinProvider, options.config, options.database)
|
||||
);
|
||||
if (options.spotifyOAuth) {
|
||||
app.use(
|
||||
@@ -207,12 +210,41 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
);
|
||||
}
|
||||
app.use("/api/favorites", requireNotGuest, createFavoritesRouter(options.database, logger));
|
||||
// The caller's own NetEase login for their personal FM (#164). Guests share
|
||||
// one anonymous identity, so they cannot link an account.
|
||||
// The caller's own music login, per platform (#164 + #164 follow-up). Guests
|
||||
// share one anonymous identity, so they cannot link an account.
|
||||
app.use(
|
||||
"/api/me/music",
|
||||
requireNotGuest,
|
||||
createPersonalMusicRouter(options.database, options.neteaseProvider, logger),
|
||||
createPersonalMusicRouter(
|
||||
options.database,
|
||||
{
|
||||
netease: options.neteaseProvider,
|
||||
qq: options.qqProvider,
|
||||
kugou: options.kugouProvider,
|
||||
bilibili: options.bilibiliProvider,
|
||||
},
|
||||
logger,
|
||||
options.config,
|
||||
),
|
||||
);
|
||||
// Admin-only pool of music logins + per-member assignments (#164 follow-up).
|
||||
// Mounted on requireAdmin, NOT bot.manage: members must never see which
|
||||
// account was handed to whom.
|
||||
app.use(
|
||||
"/api/music-accounts",
|
||||
requireAdmin,
|
||||
createMusicAccountsRouter(
|
||||
options.database,
|
||||
users,
|
||||
{
|
||||
netease: options.neteaseProvider,
|
||||
qq: options.qqProvider,
|
||||
kugou: options.kugouProvider,
|
||||
bilibili: options.bilibiliProvider,
|
||||
},
|
||||
logger,
|
||||
options.cookieStore,
|
||||
),
|
||||
);
|
||||
// Saved queues (Feature 1, #119). Members + admins only (requireNotGuest);
|
||||
// the router itself 403s every route unless savedQueuesEnabled is on.
|
||||
|
||||
+7
-8
@@ -10,12 +10,12 @@ import { QQMusicProvider } from "./src/music/qq.js";
|
||||
import { BotManager } from "./src/bot/manager.js";
|
||||
import { createWebServer } from "./src/web/server.js";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
generateIdentity,
|
||||
listClients,
|
||||
sendTextMessage,
|
||||
consoleLogger,
|
||||
} from "@honeybbq/teamspeak-client";
|
||||
} from "@honeybbq/teamspeak";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
generateIdentitySync,
|
||||
} from "@honeybbq/teamspeak/client";
|
||||
|
||||
const logger = createLogger();
|
||||
let passed = 0;
|
||||
@@ -83,7 +83,7 @@ async function main() {
|
||||
// ═══ Test 2: Verify bot is visible using a second client ═══
|
||||
log("\n═══ Test 2: Verify Bot Visibility ═══");
|
||||
|
||||
const verifyIdentity = generateIdentity(8);
|
||||
const verifyIdentity = generateIdentitySync(8);
|
||||
const verifyClient = new TS3FullClient(
|
||||
verifyIdentity,
|
||||
"127.0.0.1:9987",
|
||||
@@ -92,8 +92,7 @@ async function main() {
|
||||
);
|
||||
|
||||
await verifyClient.connect();
|
||||
await verifyClient.waitConnected();
|
||||
log(` Verification client connected (id=${verifyClient.clientID()})`);
|
||||
log(` Verification client connected (id=${verifyClient.clientID})`);
|
||||
|
||||
try {
|
||||
const clients = await listClients(verifyClient);
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
<template>
|
||||
<!-- Admin console for the music-account pool (#164 follow-up).
|
||||
One row per login the admin owns; each row can be handed to members (or
|
||||
to another admin). See src/web/api/music-accounts.ts for the rules. -->
|
||||
<div class="pool">
|
||||
<p class="hint">
|
||||
这里存放管理员拥有的音乐账号,可以逐个分配给成员。成员自己扫码绑定的账号优先级更高,
|
||||
管理员分配的账号只在他们没绑定自己的账号时生效。播放地址、搜索、歌单都会按被分配的账号获取。
|
||||
</p>
|
||||
|
||||
<!-- Create -->
|
||||
<div class="create-row">
|
||||
<select v-model="draft.platform" class="field">
|
||||
<option v-for="p in platforms" :key="p.platform" :value="p.platform">
|
||||
{{ PLATFORM_LABEL[p.platform] ?? p.platform }}
|
||||
{{ p.playbackSupported ? '' : '(暂不支持按账号播放)' }}
|
||||
</option>
|
||||
</select>
|
||||
<input v-model="draft.label" class="field" placeholder="名称,如 网易云-主号" maxlength="64" />
|
||||
<input
|
||||
v-model.number="draft.capacity"
|
||||
class="field field-narrow"
|
||||
type="number"
|
||||
min="0"
|
||||
title="0 = 可分配给多人;1 = 独占,只能给一个人"
|
||||
placeholder="人数上限"
|
||||
/>
|
||||
<button class="btn primary" :disabled="creating" @click="create">
|
||||
<Icon icon="mdi:plus" /> 添加账号
|
||||
</button>
|
||||
<button class="btn" :disabled="creating" @click="importShared">
|
||||
<Icon icon="mdi:download" /> 从共享账号导入
|
||||
</button>
|
||||
</div>
|
||||
<textarea
|
||||
v-model="draft.cookie"
|
||||
class="field cookie-input"
|
||||
rows="2"
|
||||
placeholder="粘贴该账号的 Cookie(仅保存在服务器,列表里只显示掩码)"
|
||||
></textarea>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
|
||||
<!-- List -->
|
||||
<div v-if="accounts.length === 0" class="empty">还没有添加任何账号</div>
|
||||
|
||||
<div v-for="a in accounts" :key="a.id" class="account" :class="{ disabled: !a.enabled }">
|
||||
<div class="account-head">
|
||||
<div class="account-title">
|
||||
<span class="badge">{{ PLATFORM_LABEL[a.platform] ?? a.platform }}</span>
|
||||
<span class="label">{{ a.label }}</span>
|
||||
<span v-if="a.capacity === 1" class="tag exclusive">独占</span>
|
||||
<span v-else-if="a.capacity > 1" class="tag">最多 {{ a.capacity }} 人</span>
|
||||
<span v-else class="tag">不限人数</span>
|
||||
<span v-if="!a.playbackSupported" class="tag warn">该平台暂不支持按账号播放</span>
|
||||
</div>
|
||||
<div class="account-actions">
|
||||
<button class="btn tiny" @click="probe(a)">
|
||||
<Icon icon="mdi:shield-check" /> 检测
|
||||
</button>
|
||||
<label class="switch" :title="a.enabled ? '已启用' : '已停用'">
|
||||
<input type="checkbox" :checked="a.enabled" @change="toggleEnabled(a)" />
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
<button class="btn tiny danger" @click="remove(a)">
|
||||
<Icon icon="mdi:trash-can-outline" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="account-meta">
|
||||
<span class="mono">{{ a.cookiePreview }}</span>
|
||||
<span v-if="probeResult[a.id]" class="probe" :class="{ ok: probeResult[a.id]!.loggedIn }">
|
||||
{{ probeResult[a.id]!.loggedIn ? `登录有效${probeResult[a.id]!.nickname ? ':' + probeResult[a.id]!.nickname : ''}` : '登录已失效' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="grantees">
|
||||
<span class="grantees-label">已分配:</span>
|
||||
<span v-if="a.grantees.length === 0" class="muted">无</span>
|
||||
<span v-for="g in a.grantees" :key="g.userId" class="chip">
|
||||
{{ g.username }}
|
||||
<button class="chip-x" title="收回" @click="revoke(a, g.userId)">×</button>
|
||||
</span>
|
||||
<select
|
||||
class="field field-narrow assign-select"
|
||||
:value="''"
|
||||
:disabled="assignable(a).length === 0"
|
||||
@change="onAssign(a, $event)"
|
||||
>
|
||||
<option value="">{{ assignable(a).length === 0 ? '已满额' : '+ 分配给…' }}</option>
|
||||
<option v-for="u in assignable(a)" :key="u.id" :value="u.id">
|
||||
{{ u.username }}{{ u.role === 'admin' ? '(管理员)' : '' }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="cookie-edit">
|
||||
<input
|
||||
v-model="cookieDraft[a.id]"
|
||||
class="field"
|
||||
type="password"
|
||||
placeholder="更新 Cookie(登录失效时用)"
|
||||
/>
|
||||
<button class="btn tiny" :disabled="!cookieDraft[a.id]" @click="updateCookie(a)">
|
||||
保存
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue';
|
||||
import { Icon } from '@iconify/vue';
|
||||
import axios from 'axios';
|
||||
|
||||
interface Grantee { userId: string; username: string; grantedAt: string }
|
||||
interface PoolAccount {
|
||||
id: string;
|
||||
platform: string;
|
||||
label: string;
|
||||
cookiePreview: string;
|
||||
capacity: number;
|
||||
enabled: boolean;
|
||||
playbackSupported: boolean;
|
||||
granteeCount: number;
|
||||
grantees: Grantee[];
|
||||
}
|
||||
interface AssignableUser { id: string; username: string; role: string }
|
||||
|
||||
const PLATFORM_LABEL: Record<string, string> = {
|
||||
netease: '网易云',
|
||||
qq: 'QQ音乐',
|
||||
kugou: '酷狗',
|
||||
bilibili: 'B站',
|
||||
};
|
||||
|
||||
const accounts = ref<PoolAccount[]>([]);
|
||||
const users = ref<AssignableUser[]>([]);
|
||||
const platforms = ref<Array<{ platform: string; playbackSupported: boolean }>>([]);
|
||||
const creating = ref(false);
|
||||
const error = ref('');
|
||||
// Default to exclusive: sharing one login between members mixes their
|
||||
// playback history and recommendations, which is almost never intended.
|
||||
const draft = reactive({ platform: 'netease', label: '', cookie: '', capacity: 1 });
|
||||
const cookieDraft = reactive<Record<string, string>>({});
|
||||
const probeResult = ref<Record<string, { loggedIn: boolean; nickname?: string } | undefined>>({});
|
||||
|
||||
const assignable = (a: PoolAccount) => {
|
||||
const held = new Set(a.grantees.map((g) => g.userId));
|
||||
// An exclusive account that already has a holder offers nobody: the API would
|
||||
// answer 409 anyway, so don't dangle options that cannot work.
|
||||
if (a.capacity === 1 && a.granteeCount >= 1) return [];
|
||||
if (a.capacity > 1 && a.granteeCount >= a.capacity) return [];
|
||||
return users.value.filter((u) => !held.has(u.id));
|
||||
};
|
||||
|
||||
const errText = (err: any, fallback: string) => {
|
||||
const e = err?.response?.data?.error;
|
||||
if (e === 'account_exclusive') return '该账号是独占的,请先收回其他成员';
|
||||
if (e === 'account_full') return '该账号已分配满额';
|
||||
if (e === 'account_disabled') return '该账号已停用';
|
||||
if (e === 'no_shared_login') return '机器人还没有登录该平台的共享账号';
|
||||
return e ?? fallback;
|
||||
};
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const res = await axios.get('/api/music-accounts');
|
||||
accounts.value = res.data.accounts ?? [];
|
||||
users.value = res.data.users ?? [];
|
||||
platforms.value = res.data.platforms ?? [];
|
||||
if (!platforms.value.some((p) => p.platform === draft.platform)) {
|
||||
draft.platform = platforms.value[0]?.platform ?? 'netease';
|
||||
}
|
||||
} catch (err) {
|
||||
error.value = errText(err, '加载失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function create() {
|
||||
error.value = '';
|
||||
if (!draft.label.trim() || !draft.cookie.trim()) {
|
||||
error.value = '名称和 Cookie 都要填';
|
||||
return;
|
||||
}
|
||||
creating.value = true;
|
||||
try {
|
||||
await axios.post('/api/music-accounts', {
|
||||
platform: draft.platform,
|
||||
label: draft.label.trim(),
|
||||
cookie: draft.cookie.trim(),
|
||||
capacity: Number(draft.capacity) || 0,
|
||||
});
|
||||
draft.label = '';
|
||||
draft.cookie = '';
|
||||
draft.capacity = 1;
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '添加失败');
|
||||
} finally {
|
||||
creating.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function importShared() {
|
||||
error.value = '';
|
||||
creating.value = true;
|
||||
try {
|
||||
await axios.post('/api/music-accounts/import-shared', {
|
||||
platform: draft.platform,
|
||||
label: `${PLATFORM_LABEL[draft.platform] ?? draft.platform} 共享账号`,
|
||||
capacity: Number(draft.capacity) || 0,
|
||||
});
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '导入失败');
|
||||
} finally {
|
||||
creating.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleEnabled(a: PoolAccount) {
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.patch(`/api/music-accounts/${a.id}`, { enabled: !a.enabled });
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '操作失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function updateCookie(a: PoolAccount) {
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.patch(`/api/music-accounts/${a.id}`, { cookie: cookieDraft[a.id] });
|
||||
cookieDraft[a.id] = '';
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '保存失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(a: PoolAccount) {
|
||||
if (!confirm(`删除「${a.label}」?已分配给成员的记录会一起收回。`)) return;
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.delete(`/api/music-accounts/${a.id}`);
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '删除失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function onAssign(a: PoolAccount, ev: Event) {
|
||||
const select = ev.target as HTMLSelectElement;
|
||||
const userId = select.value;
|
||||
select.value = '';
|
||||
if (!userId) return;
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.post(`/api/music-accounts/${a.id}/assign`, { userId });
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '分配失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function revoke(a: PoolAccount, userId: string) {
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.delete(`/api/music-accounts/${a.id}/assign/${userId}`);
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = errText(err, '收回失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function probe(a: PoolAccount) {
|
||||
error.value = '';
|
||||
try {
|
||||
const res = await axios.post(`/api/music-accounts/${a.id}/probe`);
|
||||
probeResult.value[a.id] = { loggedIn: Boolean(res.data.loggedIn), nickname: res.data.nickname };
|
||||
} catch (err) {
|
||||
probeResult.value[a.id] = { loggedIn: false };
|
||||
error.value = errText(err, '检测失败');
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.pool {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
line-height: 1.6;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.create-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.field {
|
||||
padding: 7px 10px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
color: inherit;
|
||||
font-size: 13px;
|
||||
min-width: 0;
|
||||
&:focus {
|
||||
outline: none;
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.field-narrow {
|
||||
width: 96px;
|
||||
}
|
||||
|
||||
.cookie-input {
|
||||
width: 100%;
|
||||
resize: vertical;
|
||||
font-family: var(--font-mono, monospace);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 7px 14px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
&:hover:not(:disabled) {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
&:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: default;
|
||||
}
|
||||
&.primary {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
&.tiny {
|
||||
padding: 4px 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
&.danger:hover {
|
||||
border-color: #e26a6a;
|
||||
color: #e26a6a;
|
||||
}
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 16px;
|
||||
font-size: 13px;
|
||||
color: var(--text-tertiary);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.account {
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-md);
|
||||
margin-bottom: 10px;
|
||||
background: var(--hover-bg);
|
||||
&.disabled {
|
||||
opacity: 0.6;
|
||||
}
|
||||
}
|
||||
|
||||
.account-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.account-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 11px;
|
||||
padding: 2px 7px;
|
||||
border-radius: 10px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.label {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.tag {
|
||||
font-size: 11px;
|
||||
color: var(--text-tertiary);
|
||||
&.exclusive {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
&.warn {
|
||||
color: #d19a3a;
|
||||
}
|
||||
}
|
||||
|
||||
.account-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.account-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: var(--font-mono, monospace);
|
||||
}
|
||||
|
||||
.probe {
|
||||
color: #e26a6a;
|
||||
&.ok {
|
||||
color: var(--color-online);
|
||||
}
|
||||
}
|
||||
|
||||
.grantees {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.grantees-label {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.muted {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
padding: 2px 8px;
|
||||
font-size: 12px;
|
||||
border-radius: 10px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.chip-x {
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--text-tertiary);
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
padding: 0 0 0 2px;
|
||||
&:hover {
|
||||
color: #e26a6a;
|
||||
}
|
||||
}
|
||||
|
||||
.assign-select {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.cookie-edit {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
.field {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.switch {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
width: 34px;
|
||||
height: 18px;
|
||||
input {
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
.slider {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: var(--border-color);
|
||||
border-radius: 9px;
|
||||
cursor: pointer;
|
||||
transition: background var(--transition-fast);
|
||||
}
|
||||
.slider::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
left: 2px;
|
||||
top: 2px;
|
||||
background: #fff;
|
||||
border-radius: 50%;
|
||||
transition: transform var(--transition-fast);
|
||||
}
|
||||
input:checked + .slider {
|
||||
background: var(--color-primary);
|
||||
}
|
||||
input:checked + .slider::before {
|
||||
transform: translateX(16px);
|
||||
}
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 6px 0;
|
||||
font-size: 12px;
|
||||
color: #e26a6a;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,552 @@
|
||||
<template>
|
||||
<!-- The signed-in user's own music accounts (#164 + #164 follow-up).
|
||||
Two ways an account can apply to this user:
|
||||
- 自己扫码绑定 (source = personal) → they may unlink it
|
||||
- 管理员分配 (source = granted) → only the admin can revoke it
|
||||
Everything is read from /api/me/music/<platform>/status; the cookie never
|
||||
reaches the browser. -->
|
||||
<div class="account-card">
|
||||
<div class="account-header">
|
||||
<Icon icon="mdi:account-music" class="account-icon" />
|
||||
<div class="account-info">
|
||||
<div class="account-name">我的音乐账号</div>
|
||||
<div class="account-status" :class="{ logged: status.loggedIn, granted: status.source === 'granted' }">
|
||||
<template v-if="status.source === 'granted'">
|
||||
由管理员分配:{{ status.label || '已分配的账号' }}
|
||||
<template v-if="status.loggedIn && status.nickname">({{ status.nickname }})</template>
|
||||
<template v-else-if="!status.loggedIn">,但登录已失效,请联系管理员</template>
|
||||
</template>
|
||||
<template v-else-if="status.loggedIn">已绑定:{{ status.nickname }}</template>
|
||||
<template v-else-if="status.linked">已绑定,但登录已失效,请重新扫码</template>
|
||||
<template v-else>未绑定 — 使用机器人的共享账号</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Platform switch: only the sources this instance has enabled. -->
|
||||
<div v-if="platforms.length > 1" class="platform-tabs">
|
||||
<button
|
||||
v-for="p in platforms"
|
||||
:key="p"
|
||||
class="platform-tab"
|
||||
:class="{ active: p === current }"
|
||||
@click="selectPlatform(p)"
|
||||
>
|
||||
{{ PLATFORM_LABEL[p] ?? p }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p class="hint">
|
||||
<template v-if="status.source === 'granted'">
|
||||
网页搜索、歌单和每日推荐默认使用管理员分配的账号。自己的绑定优先。
|
||||
</template>
|
||||
<template v-else-if="status.supportsQrLogin">
|
||||
管理员开启每用户独立账号后,可使用你绑定的{{ PLATFORM_LABEL[current] ?? current }}账号查看网页搜索、歌单和推荐。登录凭据保存在服务器。
|
||||
</template>
|
||||
<template v-else>
|
||||
该平台暂不支持在网页端自助绑定,需要账号请联系管理员分配。
|
||||
</template>
|
||||
</p>
|
||||
|
||||
<!-- 网页用哪个账号。只有真的持有个人/分配账号、且管理员开了这个功能时
|
||||
才有得选;否则本来就走共享账号。 -->
|
||||
<div
|
||||
v-if="status.featureEnabled && status.linked"
|
||||
class="account-choice"
|
||||
role="radiogroup"
|
||||
aria-label="网页端使用哪个账号"
|
||||
>
|
||||
<div class="account-choice-title">网页端使用哪个账号</div>
|
||||
|
||||
<div
|
||||
class="account-choice-option"
|
||||
:class="{ active: !status.preferShared }"
|
||||
role="radio"
|
||||
:aria-checked="!status.preferShared"
|
||||
tabindex="0"
|
||||
@click="setPreference(false)"
|
||||
@keydown.enter.prevent="setPreference(false)"
|
||||
@keydown.space.prevent="setPreference(false)"
|
||||
>
|
||||
<span class="account-choice-dot" :class="{ on: !status.preferShared }" />
|
||||
<span class="account-choice-text">
|
||||
<strong>我的账号</strong>
|
||||
<em>
|
||||
{{ status.source === 'granted' ? '管理员分配的账号' : '我扫码绑定的账号' }}
|
||||
</em>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="account-choice-option"
|
||||
:class="{ active: status.preferShared }"
|
||||
role="radio"
|
||||
:aria-checked="status.preferShared"
|
||||
tabindex="0"
|
||||
@click="setPreference(true)"
|
||||
@keydown.enter.prevent="setPreference(true)"
|
||||
@keydown.space.prevent="setPreference(true)"
|
||||
>
|
||||
<span class="account-choice-dot" :class="{ on: status.preferShared }" />
|
||||
<span class="account-choice-text">
|
||||
<strong>共享账号(管理员的)</strong>
|
||||
<em>查看共享账号的歌单和推荐</em>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="account-choice-note">
|
||||
这个选择影响网页端的搜索、歌单和推荐。房间播歌使用机器人共享账号。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="login-methods">
|
||||
<button
|
||||
v-if="status.supportsQrLogin"
|
||||
class="login-btn"
|
||||
:disabled="qr.loading"
|
||||
@click="startQrLogin"
|
||||
>
|
||||
<Icon icon="mdi:qrcode" />
|
||||
{{ status.linked ? '重新扫码绑定' : '扫码绑定' }}
|
||||
</button>
|
||||
<!-- Only the user's OWN login can be removed here; an admin-granted one
|
||||
is managed from Settings → 音乐账号分配. -->
|
||||
<button v-if="status.canUnlink" class="login-btn" @click="unlink">
|
||||
<Icon icon="mdi:link-off" />
|
||||
解除绑定
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="qr.loading" class="qr-loading">
|
||||
<Icon icon="mdi:loading" class="spin" />
|
||||
生成二维码中...
|
||||
</div>
|
||||
<div v-else-if="qr.dataUrl" class="qr-wrap">
|
||||
<img :src="qr.dataUrl" class="qr-image" alt="QR Code" />
|
||||
<div class="qr-status" :class="qr.status">
|
||||
<template v-if="qr.status === 'waiting'">
|
||||
<Icon icon="mdi:cellphone" /> 请使用{{ PLATFORM_LABEL[current] ?? '' }}APP扫码
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'scanned'">
|
||||
<Icon icon="mdi:check" /> 已扫码,请在手机上确认
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'confirmed'">
|
||||
<Icon icon="mdi:check-circle" /> 绑定成功!
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'expired'">
|
||||
<Icon icon="mdi:refresh" /> 二维码已过期
|
||||
<button class="btn-link" @click="startQrLogin">重新生成</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, reactive, ref, watch } from 'vue';
|
||||
import { Icon } from '@iconify/vue';
|
||||
import axios from 'axios';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
const props = withDefaults(defineProps<{ platforms?: string[] }>(), {
|
||||
platforms: () => ['netease'],
|
||||
});
|
||||
|
||||
const PLATFORM_LABEL: Record<string, string> = {
|
||||
netease: '网易云',
|
||||
qq: 'QQ音乐',
|
||||
kugou: '酷狗',
|
||||
bilibili: 'B站',
|
||||
};
|
||||
|
||||
const current = ref(props.platforms[0] ?? 'netease');
|
||||
const status = reactive({
|
||||
linked: false,
|
||||
loggedIn: false,
|
||||
nickname: '',
|
||||
label: '',
|
||||
source: 'none' as 'none' | 'personal' | 'granted',
|
||||
canUnlink: false,
|
||||
supportsQrLogin: false,
|
||||
preferShared: false,
|
||||
featureEnabled: false,
|
||||
});
|
||||
const qr = reactive({
|
||||
loading: false,
|
||||
dataUrl: '',
|
||||
key: '',
|
||||
status: 'waiting' as 'waiting' | 'scanned' | 'confirmed' | 'expired',
|
||||
});
|
||||
const error = ref('');
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const base = () => `/api/me/music/${current.value}`;
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
|
||||
async function refreshStatus() {
|
||||
try {
|
||||
const res = await axios.get(`${base()}/status`);
|
||||
status.linked = Boolean(res.data?.linked);
|
||||
status.loggedIn = Boolean(res.data?.loggedIn);
|
||||
status.nickname = res.data?.nickname ?? '';
|
||||
status.label = res.data?.label ?? '';
|
||||
status.source = res.data?.source ?? 'none';
|
||||
status.canUnlink = Boolean(res.data?.canUnlink);
|
||||
status.supportsQrLogin = Boolean(res.data?.supportsQrLogin);
|
||||
status.preferShared = Boolean(res.data?.preferShared);
|
||||
status.featureEnabled = Boolean(res.data?.featureEnabled);
|
||||
} catch {
|
||||
// Leave the last known state
|
||||
}
|
||||
}
|
||||
|
||||
function resetQr() {
|
||||
stopPolling();
|
||||
qr.dataUrl = '';
|
||||
qr.key = '';
|
||||
qr.status = 'waiting';
|
||||
}
|
||||
|
||||
function selectPlatform(p: string) {
|
||||
if (p === current.value) return;
|
||||
current.value = p;
|
||||
error.value = '';
|
||||
resetQr();
|
||||
void refreshStatus();
|
||||
}
|
||||
|
||||
async function startQrLogin() {
|
||||
stopPolling();
|
||||
error.value = '';
|
||||
qr.loading = true;
|
||||
qr.dataUrl = '';
|
||||
qr.status = 'waiting';
|
||||
try {
|
||||
const res = await axios.post(`${base()}/qrcode`);
|
||||
const { qrUrl, qrImg, key } = res.data;
|
||||
qr.key = key;
|
||||
// Dark-on-light only: many in-app scanners can't read an inverted code.
|
||||
qr.dataUrl = qrImg || (await QRCode.toDataURL(qrUrl, {
|
||||
width: 200,
|
||||
margin: 2,
|
||||
color: { dark: '#000000', light: '#ffffff' },
|
||||
}));
|
||||
pollTimer = setInterval(pollQrStatus, 2000);
|
||||
} catch (err: any) {
|
||||
const code = err?.response?.status;
|
||||
error.value = code === 501
|
||||
? '该平台暂不支持自助绑定,请联系管理员分配账号'
|
||||
: (err?.response?.data?.error ?? '二维码生成失败');
|
||||
} finally {
|
||||
qr.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function pollQrStatus() {
|
||||
if (!qr.key) return;
|
||||
try {
|
||||
const res = await axios.get(`${base()}/qrcode/status`, { params: { key: qr.key } });
|
||||
qr.status = res.data.status;
|
||||
if (qr.status === 'confirmed') {
|
||||
stopPolling();
|
||||
await refreshStatus();
|
||||
} else if (qr.status === 'expired') {
|
||||
stopPolling();
|
||||
}
|
||||
} catch {
|
||||
// Ignore poll errors
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch which login playback uses.
|
||||
*
|
||||
* `true` = the bot's shared account (usually the admin's, usually the one with
|
||||
* a membership), `false` = my own / the assigned one. Nothing is unlinked, so
|
||||
* switching back restores the personal account exactly as it was.
|
||||
*/
|
||||
async function setPreference(preferShared: boolean) {
|
||||
if (preferShared === status.preferShared) return;
|
||||
error.value = '';
|
||||
const previous = status.preferShared;
|
||||
status.preferShared = preferShared; // optimistic — the radio must feel instant
|
||||
try {
|
||||
await axios.put(`${base()}/preference`, { preferShared });
|
||||
} catch (err: any) {
|
||||
status.preferShared = previous;
|
||||
const code = err?.response?.status;
|
||||
error.value =
|
||||
code === 409
|
||||
? '管理员未开启「每用户独立账号」,暂时无法切换'
|
||||
: (err?.response?.data?.error ?? '切换失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function unlink() {
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.delete(base());
|
||||
resetQr();
|
||||
await refreshStatus();
|
||||
} catch (err: any) {
|
||||
error.value = err?.response?.data?.error ?? '解除绑定失败';
|
||||
}
|
||||
}
|
||||
|
||||
// Settings can render before the provider list is known; follow it if it changes.
|
||||
watch(
|
||||
() => props.platforms,
|
||||
(list) => {
|
||||
if (list.length > 0 && !list.includes(current.value)) {
|
||||
current.value = list[0];
|
||||
void refreshStatus();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
onMounted(refreshStatus);
|
||||
onUnmounted(stopPolling);
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.account-card {
|
||||
margin-top: 16px;
|
||||
padding: 20px;
|
||||
background: var(--hover-bg);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
.account-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.account-icon {
|
||||
font-size: 28px;
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.account-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.account-status {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
&.logged { color: var(--color-online); }
|
||||
&.granted { color: var(--text-secondary); }
|
||||
}
|
||||
|
||||
.platform-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.platform-tab {
|
||||
padding: 5px 12px;
|
||||
font-size: 12px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid var(--border-color);
|
||||
background: var(--bg-card);
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
&.active {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
margin: 0 0 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.account-choice {
|
||||
margin: 12px 0 16px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--border-color, rgba(128, 128, 128, 0.2));
|
||||
border-radius: var(--radius-sm, 8px);
|
||||
}
|
||||
|
||||
.account-choice-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.account-choice-option {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 8px 10px;
|
||||
border-radius: var(--radius-sm, 8px);
|
||||
cursor: pointer;
|
||||
transition: background-color 0.15s ease;
|
||||
|
||||
& + & {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: var(--hover-bg-strong, rgba(128, 128, 128, 0.08));
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: var(--hover-bg-strong, rgba(128, 128, 128, 0.1));
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.account-choice-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin-top: 2px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid var(--text-secondary, #888);
|
||||
position: relative;
|
||||
|
||||
&.on {
|
||||
border-color: var(--color-primary);
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 2px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.account-choice-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
|
||||
strong {
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
em {
|
||||
font-style: normal;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Scope disclaimer: the radio above governs the web player only. Members were
|
||||
reading "共享账号" as "房间里也用这个" — which is true, but for the opposite
|
||||
reason, so it needs saying. */
|
||||
.account-choice-note {
|
||||
margin-top: 8px;
|
||||
padding-top: 8px;
|
||||
border-top: 1px dashed var(--border-color, rgba(128, 128, 128, 0.2));
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-secondary);
|
||||
|
||||
code {
|
||||
font-size: 11px;
|
||||
padding: 1px 4px;
|
||||
border-radius: 3px;
|
||||
background: var(--hover-bg-strong, rgba(128, 128, 128, 0.12));
|
||||
}
|
||||
}
|
||||
|
||||
.login-methods {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.login-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px 16px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
&:hover:not(:disabled) { border-color: var(--color-primary); color: var(--color-primary); }
|
||||
&:disabled { opacity: 0.6; cursor: default; }
|
||||
}
|
||||
|
||||
.qr-loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.qr-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.qr-image {
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
border-radius: var(--radius-md);
|
||||
border: 2px solid var(--border-color);
|
||||
}
|
||||
|
||||
.qr-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
&.confirmed { color: var(--color-online); }
|
||||
}
|
||||
|
||||
.btn-link {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--color-primary);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #e26a6a;
|
||||
}
|
||||
|
||||
.spin {
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
@@ -1,261 +0,0 @@
|
||||
<template>
|
||||
<!-- The signed-in user's own NetEase account, used for THEIR 私人FM instead
|
||||
of the bot's shared login (#164). -->
|
||||
<div class="account-card">
|
||||
<div class="account-header">
|
||||
<Icon icon="mdi:radio" class="account-icon" />
|
||||
<div class="account-info">
|
||||
<div class="account-name">我的网易云账号(私人FM)</div>
|
||||
<div class="account-status" :class="{ logged: status.loggedIn }">
|
||||
<template v-if="status.loggedIn">已绑定: {{ status.nickname }}</template>
|
||||
<template v-else-if="status.linked">已绑定,但登录已失效,请重新扫码</template>
|
||||
<template v-else>未绑定 — 私人FM使用机器人的共享账号</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="hint">
|
||||
绑定后,你在网页端开启的网易云私人FM会按你自己的口味推荐;其他人不受影响。
|
||||
仅保存在服务器上,不会显示给任何人。
|
||||
</p>
|
||||
|
||||
<div class="login-methods">
|
||||
<button class="login-btn" :disabled="qr.loading" @click="startQrLogin">
|
||||
<Icon icon="mdi:qrcode" />
|
||||
{{ status.linked ? '重新扫码绑定' : '扫码绑定' }}
|
||||
</button>
|
||||
<button v-if="status.linked" class="login-btn" @click="unlink">
|
||||
<Icon icon="mdi:link-off" />
|
||||
解除绑定
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="qr.loading" class="qr-loading">
|
||||
<Icon icon="mdi:loading" class="spin" />
|
||||
生成二维码中...
|
||||
</div>
|
||||
<div v-else-if="qr.dataUrl" class="qr-wrap">
|
||||
<img :src="qr.dataUrl" class="qr-image" alt="QR Code" />
|
||||
<div class="qr-status" :class="qr.status">
|
||||
<template v-if="qr.status === 'waiting'">
|
||||
<Icon icon="mdi:cellphone" /> 请使用网易云音乐APP扫码
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'scanned'">
|
||||
<Icon icon="mdi:check" /> 已扫码,请在手机上确认
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'confirmed'">
|
||||
<Icon icon="mdi:check-circle" /> 绑定成功!
|
||||
</template>
|
||||
<template v-else-if="qr.status === 'expired'">
|
||||
<Icon icon="mdi:refresh" /> 二维码已过期
|
||||
<button class="btn-link" @click="startQrLogin">重新生成</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, reactive, ref } from 'vue';
|
||||
import { Icon } from '@iconify/vue';
|
||||
import axios from 'axios';
|
||||
import QRCode from 'qrcode';
|
||||
|
||||
const BASE = '/api/me/music/netease';
|
||||
|
||||
const status = reactive({ linked: false, loggedIn: false, nickname: '' });
|
||||
const qr = reactive({
|
||||
loading: false,
|
||||
dataUrl: '',
|
||||
key: '',
|
||||
status: 'waiting' as 'waiting' | 'scanned' | 'confirmed' | 'expired',
|
||||
});
|
||||
const error = ref('');
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
|
||||
async function refreshStatus() {
|
||||
try {
|
||||
const res = await axios.get(`${BASE}/status`);
|
||||
status.linked = Boolean(res.data?.linked);
|
||||
status.loggedIn = Boolean(res.data?.loggedIn);
|
||||
status.nickname = res.data?.nickname ?? '';
|
||||
} catch {
|
||||
// Leave the last known state
|
||||
}
|
||||
}
|
||||
|
||||
async function startQrLogin() {
|
||||
stopPolling();
|
||||
error.value = '';
|
||||
qr.loading = true;
|
||||
qr.dataUrl = '';
|
||||
qr.status = 'waiting';
|
||||
try {
|
||||
const res = await axios.post(`${BASE}/qrcode`);
|
||||
const { qrUrl, qrImg, key } = res.data;
|
||||
qr.key = key;
|
||||
// Dark-on-light only: many in-app scanners can't read an inverted code.
|
||||
qr.dataUrl = qrImg || (await QRCode.toDataURL(qrUrl, {
|
||||
width: 200,
|
||||
margin: 2,
|
||||
color: { dark: '#000000', light: '#ffffff' },
|
||||
}));
|
||||
pollTimer = setInterval(pollQrStatus, 2000);
|
||||
} catch (err: any) {
|
||||
error.value = err?.response?.data?.error ?? '二维码生成失败';
|
||||
} finally {
|
||||
qr.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function pollQrStatus() {
|
||||
if (!qr.key) return;
|
||||
try {
|
||||
const res = await axios.get(`${BASE}/qrcode/status`, { params: { key: qr.key } });
|
||||
qr.status = res.data.status;
|
||||
if (qr.status === 'confirmed') {
|
||||
stopPolling();
|
||||
await refreshStatus();
|
||||
} else if (qr.status === 'expired') {
|
||||
stopPolling();
|
||||
}
|
||||
} catch {
|
||||
// Ignore poll errors
|
||||
}
|
||||
}
|
||||
|
||||
async function unlink() {
|
||||
error.value = '';
|
||||
try {
|
||||
await axios.delete(BASE);
|
||||
stopPolling();
|
||||
qr.dataUrl = '';
|
||||
await refreshStatus();
|
||||
} catch (err: any) {
|
||||
error.value = err?.response?.data?.error ?? '解除绑定失败';
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(refreshStatus);
|
||||
onUnmounted(stopPolling);
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.account-card {
|
||||
margin-top: 16px;
|
||||
padding: 20px;
|
||||
background: var(--hover-bg);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
.account-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.account-icon {
|
||||
font-size: 28px;
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.account-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.account-status {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
&.logged { color: var(--color-online); }
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
margin: 0 0 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.login-methods {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.login-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px 16px;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
&:hover:not(:disabled) { border-color: var(--color-primary); color: var(--color-primary); }
|
||||
&:disabled { opacity: 0.6; cursor: default; }
|
||||
}
|
||||
|
||||
.qr-loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.qr-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.qr-image {
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
border-radius: var(--radius-md);
|
||||
border: 2px solid var(--border-color);
|
||||
}
|
||||
|
||||
.qr-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
&.confirmed { color: var(--color-online); }
|
||||
}
|
||||
|
||||
.btn-link {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--color-primary);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.error {
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #e26a6a;
|
||||
}
|
||||
|
||||
.spin {
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
+210
-25
@@ -6,56 +6,169 @@
|
||||
</button>
|
||||
<h1 class="page-title">播放历史</h1>
|
||||
|
||||
<p v-if="error" class="history-error" role="alert">{{ error }}</p>
|
||||
<div v-if="loading" class="loading">加载中...</div>
|
||||
|
||||
<div v-else-if="history.length === 0" class="empty">
|
||||
暂无播放记录
|
||||
</div>
|
||||
|
||||
<div v-else class="history-list">
|
||||
<SongCard
|
||||
v-for="(song, i) in history"
|
||||
:key="`${song.id}-${i}`"
|
||||
:song="song"
|
||||
:index="i + 1"
|
||||
:active="store.currentSong?.id === song.id"
|
||||
@play="store.playSong(song)"
|
||||
@playNext="store.playNextSong(song)"
|
||||
@add="store.addSong(song)"
|
||||
/>
|
||||
</div>
|
||||
<template v-else>
|
||||
<div v-if="canDelete" class="toolbar">
|
||||
<label class="select-all">
|
||||
<input type="checkbox" :checked="allSelected" :disabled="deleting" @change="toggleAll" />
|
||||
全选
|
||||
</label>
|
||||
<span class="spacer" />
|
||||
<button class="tool-btn" :disabled="deleting || selected.size === 0" @click="deleteSelected">
|
||||
<Icon icon="mdi:delete-outline" />
|
||||
删除选中{{ selected.size ? `(${selected.size})` : '' }}
|
||||
</button>
|
||||
<button class="tool-btn danger" :disabled="deleting" @click="clearAll">
|
||||
<Icon icon="mdi:delete-sweep-outline" />
|
||||
清空全部
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="history-list">
|
||||
<div
|
||||
v-for="(song, i) in history"
|
||||
:key="song.rowId"
|
||||
class="history-row"
|
||||
:class="{ selected: selected.has(song.rowId) }"
|
||||
>
|
||||
<input
|
||||
v-if="canDelete"
|
||||
type="checkbox"
|
||||
class="row-check"
|
||||
:aria-label="`选择 ${song.name}`"
|
||||
:checked="selected.has(song.rowId)"
|
||||
:disabled="deleting"
|
||||
@change="toggle(song.rowId)"
|
||||
/>
|
||||
<SongCard
|
||||
class="row-card"
|
||||
:song="song"
|
||||
:index="i + 1"
|
||||
:active="store.currentSong?.id === song.id"
|
||||
@play="store.playSong(song)"
|
||||
@playNext="store.playNextSong(song)"
|
||||
@add="store.addSong(song)"
|
||||
/>
|
||||
<button
|
||||
v-if="canDelete"
|
||||
class="row-del"
|
||||
title="删除这条记录"
|
||||
:aria-label="`删除 ${song.name} 的播放记录`"
|
||||
:disabled="deleting"
|
||||
@click.stop="deleteHistory([song.rowId])"
|
||||
>
|
||||
<Icon icon="mdi:close" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { ref, computed, onMounted, watch } from 'vue';
|
||||
import { Icon } from '@iconify/vue';
|
||||
import axios from 'axios';
|
||||
import { usePlayerStore } from '../stores/player.js';
|
||||
import { useSession } from '../composables/useSession.js';
|
||||
import SongCard from '../components/SongCard.vue';
|
||||
|
||||
const store = usePlayerStore();
|
||||
const { can, guestCan } = useSession();
|
||||
|
||||
import { Song } from '../stores/player.js';
|
||||
|
||||
const history = ref<Song[]>([]);
|
||||
/** History rows carry their DB primary key (`rowId`) so a single record can be removed. */
|
||||
type HistorySong = Song & { rowId: number };
|
||||
|
||||
const history = ref<HistorySong[]>([]);
|
||||
const loading = ref(true);
|
||||
const deleting = ref(false);
|
||||
const error = ref('');
|
||||
const selected = ref(new Set<number>());
|
||||
const canDelete = computed(() => can('player.queue') || guestCan('removeClear'));
|
||||
let historyVersion = 0;
|
||||
|
||||
const allSelected = computed(
|
||||
() => history.value.length > 0 && selected.value.size === history.value.length
|
||||
);
|
||||
|
||||
function toggle(rowId: number) {
|
||||
const next = new Set(selected.value);
|
||||
if (next.has(rowId)) next.delete(rowId);
|
||||
else next.add(rowId);
|
||||
selected.value = next;
|
||||
}
|
||||
|
||||
function toggleAll() {
|
||||
selected.value = allSelected.value
|
||||
? new Set<number>()
|
||||
: new Set(history.value.map((s) => s.rowId));
|
||||
}
|
||||
|
||||
async function deleteHistory(ids: number[] | null) {
|
||||
const botId = store.activeBotId;
|
||||
if (!botId || !canDelete.value || deleting.value) return;
|
||||
const version = historyVersion;
|
||||
const url = `/api/player/${encodeURIComponent(botId)}/history`;
|
||||
deleting.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
if (ids?.length === 1) {
|
||||
await axios.delete(`${url}/${ids[0]}`);
|
||||
} else {
|
||||
await axios.delete(url, { data: ids ? { ids } : { all: true } });
|
||||
}
|
||||
if (version !== historyVersion) return;
|
||||
const removed = new Set(ids);
|
||||
history.value = ids ? history.value.filter((song) => !removed.has(song.rowId)) : [];
|
||||
selected.value = ids ? new Set([...selected.value].filter((id) => !removed.has(id))) : new Set();
|
||||
} catch {
|
||||
if (version === historyVersion) error.value = '删除播放记录失败,请重试。';
|
||||
} finally {
|
||||
if (version === historyVersion) deleting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function deleteSelected() {
|
||||
if (selected.value.size) void deleteHistory([...selected.value]);
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
if (window.confirm('确定清空全部播放历史吗?此操作不可恢复。')) void deleteHistory(null);
|
||||
}
|
||||
|
||||
watch(() => store.activeBotId, async (botId, _previous, onCleanup) => {
|
||||
historyVersion++;
|
||||
history.value = [];
|
||||
selected.value = new Set();
|
||||
deleting.value = false;
|
||||
error.value = '';
|
||||
loading.value = !!botId;
|
||||
if (!botId) return;
|
||||
|
||||
const controller = new AbortController();
|
||||
onCleanup(() => controller.abort());
|
||||
try {
|
||||
const { data } = await axios.get(`/api/player/${encodeURIComponent(botId)}/history`, { signal: controller.signal });
|
||||
if (!controller.signal.aborted) history.value = data.history;
|
||||
} catch {
|
||||
if (!controller.signal.aborted) error.value = '加载播放历史失败。';
|
||||
} finally {
|
||||
if (!controller.signal.aborted) loading.value = false;
|
||||
}
|
||||
}, { immediate: true, flush: 'sync' });
|
||||
|
||||
onMounted(async () => {
|
||||
if (!store.activeBotId) {
|
||||
await store.fetchBots();
|
||||
}
|
||||
|
||||
if (store.activeBotId) {
|
||||
try {
|
||||
const res = await axios.get(`/api/player/${store.activeBotId}/history`);
|
||||
history.value = res.data.history;
|
||||
} catch {
|
||||
// Ignore if API not ready
|
||||
}
|
||||
}
|
||||
|
||||
loading.value = false;
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -77,12 +190,84 @@ onMounted(async () => {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.history-error {
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 12px;
|
||||
|
||||
.spacer { flex: 1; }
|
||||
|
||||
.select-all {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
}
|
||||
|
||||
.tool-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 12px;
|
||||
font-size: 13px;
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-secondary);
|
||||
transition: all var(--transition-fast);
|
||||
|
||||
&:hover:not(:disabled) { color: var(--text-primary); }
|
||||
&:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
|
||||
&.danger:hover:not(:disabled) { color: #f2555a; }
|
||||
}
|
||||
|
||||
.history-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.history-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border-radius: var(--radius-md);
|
||||
transition: background var(--transition-fast);
|
||||
|
||||
&.selected { background: rgba(51, 94, 234, 0.08); }
|
||||
|
||||
.row-check {
|
||||
flex: none;
|
||||
margin-left: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.row-card { flex: 1; min-width: 0; }
|
||||
|
||||
.row-del {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 4px;
|
||||
color: var(--text-tertiary);
|
||||
border-radius: var(--radius-sm);
|
||||
transition: all var(--transition-fast);
|
||||
|
||||
&:hover, &:focus-visible { color: #f2555a; }
|
||||
&:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
}
|
||||
}
|
||||
|
||||
.loading {
|
||||
text-align: center;
|
||||
padding: 60px;
|
||||
|
||||
@@ -116,7 +116,10 @@
|
||||
</form>
|
||||
<p v-if="ownPwError" class="user-error">{{ ownPwError }}</p>
|
||||
<p v-if="ownPwSuccess" class="user-success">{{ ownPwSuccess }}</p>
|
||||
<PersonalNeteaseAccount v-if="providerOn('netease') && !session.isGuest.value" />
|
||||
<PersonalMusicAccount
|
||||
v-if="!session.isGuest.value && personalPlatforms.length > 0"
|
||||
:platforms="personalPlatforms"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<!-- Bot Management (create/edit/delete/start-stop) requires bot.manage -->
|
||||
@@ -441,6 +444,12 @@
|
||||
<div class="account-status" :class="{ logged: qqAuth.loggedIn }">
|
||||
{{ qqAuth.loggedIn ? `已登录: ${qqAuth.nickname}` : '未登录' }}
|
||||
</div>
|
||||
<div v-if="qqRenewalMessage" class="account-status">
|
||||
{{ qqRenewalMessage }}
|
||||
</div>
|
||||
<div v-if="qqAuth.renewalStatus" class="account-status">
|
||||
上次成功续期 {{ qqAuth.lastRefreshAt ? new Date(qqAuth.lastRefreshAt).toLocaleString() : '暂无记录' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -967,6 +976,29 @@
|
||||
@change="savePlayKeepsQueue"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<!-- Admin-only: per-user music accounts. Off by default so an existing
|
||||
deployment keeps sharing one login with everyone. -->
|
||||
<label v-if="session.isAdmin.value" class="profile-toggle behavior-toggle">
|
||||
<div class="profile-toggle-text">
|
||||
<div class="profile-toggle-label">每个成员使用自己的音乐账号</div>
|
||||
<div class="profile-toggle-hint">开启后,成员可用自己绑定或管理员分配的账号访问网页搜索、歌单和推荐。仅网易云支持成员扫码绑定。没有专属账号时使用机器人共享账号。房间播歌始终使用共享账号。</div>
|
||||
</div>
|
||||
<input
|
||||
v-model="perUserMusicAccounts"
|
||||
type="checkbox"
|
||||
class="profile-toggle-switch"
|
||||
@change="savePerUserMusicAccounts"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<!-- Admin-only: the pool of logins that can be handed to members. Only
|
||||
meaningful while the toggle above is on. -->
|
||||
<div v-if="session.isAdmin.value && perUserMusicAccounts" class="pool-wrap">
|
||||
<div class="pool-title">音乐账号分配</div>
|
||||
<div class="pool-hint">添加管理员拥有的账号,分配给指定成员(也可以分配给其他管理员)。成员自己绑定的账号优先;未绑定的人使用分配给自己的账号;都没有时回到机器人的共享账号。这些账号同样只作用于<strong>网页端</strong>,房间里的播放始终用共享账号。</div>
|
||||
<MusicAccountPool />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Guest Mode (admin only) -->
|
||||
@@ -1305,7 +1337,8 @@ import axios from 'axios';
|
||||
import AvatarUpload from '../components/AvatarUpload.vue';
|
||||
import CustomAvatarRow from '../components/CustomAvatarRow.vue';
|
||||
import AccentColorPicker from '../components/AccentColorPicker.vue';
|
||||
import PersonalNeteaseAccount from '../components/PersonalNeteaseAccount.vue';
|
||||
import PersonalMusicAccount from '../components/PersonalMusicAccount.vue';
|
||||
import MusicAccountPool from '../components/MusicAccountPool.vue';
|
||||
import QRCode from 'qrcode';
|
||||
import { usePlayerStore } from '../stores/player.js';
|
||||
import { useSession } from '../composables/useSession.js';
|
||||
@@ -1418,7 +1451,22 @@ const kugouLoginMode = ref<'qr' | 'cookie' | null>(null);
|
||||
|
||||
// Auth status
|
||||
const neteaseAuth = reactive({ loggedIn: false, nickname: '', avatarUrl: '' });
|
||||
const qqAuth = reactive({ loggedIn: false, nickname: '', avatarUrl: '' });
|
||||
const qqAuth = reactive({
|
||||
loggedIn: false, nickname: '', avatarUrl: '',
|
||||
renewalStatus: '' as '' | 'cookie_only' | 'scheduled' | 'retrying' | 'reauth_required',
|
||||
nextRefreshAt: null as string | null,
|
||||
lastRefreshAt: null as string | null,
|
||||
});
|
||||
const qqRenewalMessage = computed(() => {
|
||||
const next = qqAuth.nextRefreshAt ? new Date(qqAuth.nextRefreshAt).toLocaleString() : '';
|
||||
switch (qqAuth.renewalStatus) {
|
||||
case 'cookie_only': return '没有续期凭据,请扫码授权';
|
||||
case 'reauth_required': return '续期已暂停,请重新扫码';
|
||||
case 'scheduled': return `下次自动续期 ${next}`;
|
||||
case 'retrying': return `续期将于 ${next} 重试`;
|
||||
default: return '';
|
||||
}
|
||||
});
|
||||
const bilibiliAuth = reactive({ loggedIn: false, nickname: '', avatarUrl: '' });
|
||||
const kugouAuth = reactive({ loggedIn: false, nickname: '', avatarUrl: '' });
|
||||
const jellyfinAuth = reactive({ loggedIn: false, nickname: '' });
|
||||
@@ -1431,6 +1479,11 @@ function providerOn(p: string): boolean {
|
||||
return enabledProviders.value.length === 0 || enabledProviders.value.includes(p);
|
||||
}
|
||||
|
||||
// Sources the member can hold a personal account for. Only enabled ones are
|
||||
// offered — /api/me/music serves a fixed set regardless of config.
|
||||
const PERSONAL_PLATFORMS = ['netease', 'qq', 'kugou', 'bilibili'] as const;
|
||||
const personalPlatforms = computed(() => PERSONAL_PLATFORMS.filter((p) => providerOn(p)));
|
||||
|
||||
// --- Default music source (issue #126) ---
|
||||
// Chinese labels for the gateable providers, shown in the default-source select.
|
||||
const PROVIDER_LABELS: Record<string, string> = {
|
||||
@@ -1825,6 +1878,8 @@ const localAudioEnabled = ref(true);
|
||||
// Saved-queues + play-keeps-queue toggles (#119), both default OFF.
|
||||
const savedQueuesEnabled = ref(false);
|
||||
const playKeepsQueue = ref(false);
|
||||
// Per-user music accounts (#164 follow-up). Admin toggle, default OFF.
|
||||
const perUserMusicAccounts = ref(false);
|
||||
|
||||
function normalizeVoiceDuckingVolume(): number {
|
||||
const raw = voiceDuckingVolumePercent.value as number | string;
|
||||
@@ -1865,6 +1920,7 @@ async function loadIdleTimeout() {
|
||||
localAudioEnabled.value = res.data.localAudioEnabled ?? true;
|
||||
savedQueuesEnabled.value = res.data.savedQueuesEnabled ?? false;
|
||||
playKeepsQueue.value = res.data.playKeepsQueue ?? false;
|
||||
perUserMusicAccounts.value = res.data.perUserMusicAccounts ?? false;
|
||||
store.savedQueuesEnabled = savedQueuesEnabled.value;
|
||||
applyGuestModeFromServer(res.data.guestMode);
|
||||
applyAdminGroupsFromServer(res.data.adminGroups);
|
||||
@@ -1943,6 +1999,15 @@ async function savePlayKeepsQueue() {
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
async function savePerUserMusicAccounts() {
|
||||
try {
|
||||
const res = await axios.post('/api/bot/settings', {
|
||||
perUserMusicAccounts: perUserMusicAccounts.value,
|
||||
});
|
||||
perUserMusicAccounts.value = res.data.perUserMusicAccounts ?? perUserMusicAccounts.value;
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// --- Spotify (Connect) settings (§8) ---
|
||||
// NOTE: This card's status comes ONLY from /api/spotify/status (playback OAuth
|
||||
// `authorized`). It is deliberately NOT wired to the player store's
|
||||
@@ -3383,6 +3448,26 @@ onUnmounted(() => {
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
// --- Music account pool (admin) ---
|
||||
.pool-wrap {
|
||||
margin-top: 8px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px dashed var(--border-color);
|
||||
}
|
||||
|
||||
.pool-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.pool-hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
line-height: 1.5;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.empty-hint {
|
||||
font-size: 13px;
|
||||
color: var(--text-tertiary);
|
||||
|
||||
Reference in new issue
Block a user